blob: 1921932d1f2d472330f05d2884983a9dfe1effe7 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020044 * make complex ${var%...} constructs support optional
45 * make here documents optional
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020046 * special variables (done: PWD, PPID, RANDOM)
47 * follow IFS rules more precisely, including update semantics
48 * tilde expansion
49 * aliases
Denys Vlasenko57000292018-01-12 14:41:45 +010050 * "command" missing features:
51 * command -p CMD: run CMD using default $PATH
52 * (can use this to override standalone shell as well?)
Denys Vlasenko1e660422017-07-17 21:10:50 +020053 * command BLTIN: disables special-ness (e.g. errors do not abort)
Denys Vlasenko57000292018-01-12 14:41:45 +010054 * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
55 * builtins mandated by standards we don't support:
56 * [un]alias, fc:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020057 * fc -l[nr] [BEG] [END]: list range of commands in history
58 * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
59 * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
Mike Frysinger25a6ca02009-03-28 13:59:26 +000060 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020061 * Bash compat TODO:
62 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020063 * reserved words: function select
64 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020065 * process substitution: <(list) and >(list)
66 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020067 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020068 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
69 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
70 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020071 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020072 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
73 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020074 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020075 * indirect expansion: ${!VAR}
76 * substring op on @: ${@:n:m}
Denys Vlasenkobbecd742010-10-03 17:22:52 +020077 *
78 * Won't do:
Denys Vlasenko203fd7b2017-07-17 16:13:35 +020079 * Some builtins mandated by standards:
80 * newgrp [GRP]: not a builtin in bash but a suid binary
81 * which spawns a new shell with new group ID
Denys Vlasenkobbecd742010-10-03 17:22:52 +020082 * In bash, export builtin is special, its arguments are assignments
Denys Vlasenko08218012009-06-03 14:43:56 +020083 * and therefore expansion of them should be "one-word" expansion:
84 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
85 * compare with:
86 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
87 * ls: cannot access i=a: No such file or directory
88 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020089 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020090 * Note2: bash 3.2.33(1) does this only if export word itself
91 * is not quoted:
92 * $ export i=`echo 'aaa bbb'`; echo "$i"
93 * aaa bbb
94 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
95 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000096 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config:config HUSH
Denys Vlasenko4eed2c62017-07-18 22:01:24 +020098//config: bool "hush (64 kb)"
Denys Vlasenko202a2d12010-07-16 12:36:14 +020099//config: default y
100//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200101//config: hush is a small shell. It handles the normal flow control
102//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
103//config: case/esac. Redirections, here documents, $((arithmetic))
104//config: and functions are supported.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200105//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200106//config: It will compile and work on no-mmu systems.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200107//config:
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200108//config: It does not handle select, aliases, tilde expansion,
109//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200110//config:
111//config:config HUSH_BASH_COMPAT
112//config: bool "bash-compatible extensions"
113//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100114//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200115//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200116//config:config HUSH_BRACE_EXPANSION
117//config: bool "Brace expansion"
118//config: default y
119//config: depends on HUSH_BASH_COMPAT
120//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200121//config: Enable {abc,def} extension.
Denys Vlasenko9e800222010-10-03 14:28:04 +0200122//config:
Denys Vlasenko5807e182018-02-08 19:19:04 +0100123//config:config HUSH_LINENO_VAR
124//config: bool "$LINENO variable"
125//config: default y
126//config: depends on HUSH_BASH_COMPAT
127//config:
Denys Vlasenko54c21112018-01-27 20:46:45 +0100128//config:config HUSH_BASH_SOURCE_CURDIR
129//config: bool "'source' and '.' builtins search current directory after $PATH"
130//config: default n # do not encourage non-standard behavior
131//config: depends on HUSH_BASH_COMPAT
132//config: help
133//config: This is not compliant with standards. Avoid if possible.
134//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200135//config:config HUSH_INTERACTIVE
136//config: bool "Interactive mode"
137//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100138//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200139//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200140//config: Enable interactive mode (prompt and command editing).
141//config: Without this, hush simply reads and executes commands
142//config: from stdin just like a shell script from a file.
143//config: No prompt, no PS1/PS2 magic shell variables.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200144//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200145//config:config HUSH_SAVEHISTORY
146//config: bool "Save command history to .hush_history"
147//config: default y
148//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200149//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200150//config:config HUSH_JOB
151//config: bool "Job control"
152//config: default y
153//config: depends on HUSH_INTERACTIVE
154//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200155//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
156//config: command (not entire shell), fg/bg builtins work. Without this option,
157//config: "cmd &" still works by simply spawning a process and immediately
158//config: prompting for next command (or executing next command in a script),
159//config: but no separate process group is formed.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200160//config:
161//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100162//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200163//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100164//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200166//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200167//config:
168//config:config HUSH_IF
169//config: bool "Support if/then/elif/else/fi"
170//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100171//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200172//config:
173//config:config HUSH_LOOPS
174//config: bool "Support for, while and until loops"
175//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100176//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200177//config:
178//config:config HUSH_CASE
179//config: bool "Support case ... esac statement"
180//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100181//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200183//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200184//config:
185//config:config HUSH_FUNCTIONS
186//config: bool "Support funcname() { commands; } syntax"
187//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100188//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200190//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200191//config:
192//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100193//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200194//config: default y
195//config: depends on HUSH_FUNCTIONS
196//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200197//config: Enable support for local variables in functions.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200198//config:
199//config:config HUSH_RANDOM_SUPPORT
200//config: bool "Pseudorandom generator and $RANDOM variable"
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: Enable pseudorandom generator and dynamic variable "$RANDOM".
205//config: Each read of "$RANDOM" will generate a new pseudorandom value.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200206//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200207//config:config HUSH_MODE_X
208//config: bool "Support 'hush -x' option and 'set -x' command"
209//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100210//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200211//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200212//config: This instructs hush to print commands before execution.
213//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200214//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100215//config:config HUSH_ECHO
216//config: bool "echo builtin"
217//config: default y
218//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100219//config:
220//config:config HUSH_PRINTF
221//config: bool "printf builtin"
222//config: default y
223//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100224//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100225//config:config HUSH_TEST
226//config: bool "test builtin"
227//config: default y
228//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
229//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100230//config:config HUSH_HELP
231//config: bool "help builtin"
232//config: default y
233//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100234//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100235//config:config HUSH_EXPORT
236//config: bool "export builtin"
237//config: default y
238//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100239//config:
240//config:config HUSH_EXPORT_N
241//config: bool "Support 'export -n' option"
242//config: default y
243//config: depends on HUSH_EXPORT
244//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200245//config: export -n unexports variables. It is a bash extension.
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100246//config:
Denys Vlasenko1e660422017-07-17 21:10:50 +0200247//config:config HUSH_READONLY
248//config: bool "readonly builtin"
249//config: default y
Denys Vlasenko6b0695b2017-07-17 21:47:27 +0200250//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1e660422017-07-17 21:10:50 +0200251//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +0200252//config: Enable support for read-only variables.
Denys Vlasenko1e660422017-07-17 21:10:50 +0200253//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100254//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100255//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100256//config: default y
257//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100258//config:
259//config:config HUSH_WAIT
260//config: bool "wait builtin"
261//config: default y
262//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100263//config:
Denys Vlasenko3bb3e1d2018-01-11 18:05:05 +0100264//config:config HUSH_COMMAND
265//config: bool "command builtin"
266//config: default y
267//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
268//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100269//config:config HUSH_TRAP
270//config: bool "trap builtin"
271//config: default y
272//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100273//config:
274//config:config HUSH_TYPE
275//config: bool "type builtin"
276//config: default y
277//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100278//config:
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200279//config:config HUSH_TIMES
280//config: bool "times builtin"
281//config: default y
282//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
283//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100284//config:config HUSH_READ
285//config: bool "read builtin"
286//config: default y
287//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100288//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100289//config:config HUSH_SET
290//config: bool "set builtin"
291//config: default y
292//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100293//config:
294//config:config HUSH_UNSET
295//config: bool "unset builtin"
296//config: default y
297//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100298//config:
299//config:config HUSH_ULIMIT
300//config: bool "ulimit builtin"
301//config: default y
302//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100303//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100304//config:config HUSH_UMASK
305//config: bool "umask builtin"
306//config: default y
307//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100308//config:
Denys Vlasenko74d40582017-08-11 01:32:46 +0200309//config:config HUSH_GETOPTS
310//config: bool "getopts builtin"
311//config: default y
312//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
313//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100314//config:config HUSH_MEMLEAK
315//config: bool "memleak builtin (debugging)"
316//config: default n
317//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200318
Denys Vlasenko20704f02011-03-23 17:59:27 +0100319//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100320// APPLET_ODDNAME:name main location suid_type help
Denys Vlasenko205d48e2017-01-29 14:57:33 +0100321//applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100322//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100323
324//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100325//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
326//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100327//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
328
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100329/* -i (interactive) and -s (read stdin) are also accepted,
330 * but currently do nothing, therefore aren't shown in help.
331 * NOMMU-specific options are not meant to be used by users,
332 * therefore we don't show them either.
333 */
334//usage:#define hush_trivial_usage
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200335//usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100336//usage:#define hush_full_usage "\n\n"
337//usage: "Unix shell interpreter"
338
Denys Vlasenko67047462016-12-22 15:21:58 +0100339#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
340 || defined(__APPLE__) \
341 )
342# include <malloc.h> /* for malloc_trim */
343#endif
344#include <glob.h>
345/* #include <dmalloc.h> */
346#if ENABLE_HUSH_CASE
347# include <fnmatch.h>
348#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +0200349#include <sys/times.h>
Denys Vlasenko67047462016-12-22 15:21:58 +0100350#include <sys/utsname.h> /* for setting $HOSTNAME */
351
352#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
353#include "unicode.h"
354#include "shell_common.h"
355#include "math.h"
356#include "match.h"
357#if ENABLE_HUSH_RANDOM_SUPPORT
358# include "random.h"
359#else
360# define CLEAR_RANDOM_T(rnd) ((void)0)
361#endif
362#ifndef F_DUPFD_CLOEXEC
363# define F_DUPFD_CLOEXEC F_DUPFD
364#endif
365#ifndef PIPE_BUF
366# define PIPE_BUF 4096 /* amount of buffering in a pipe */
367#endif
368
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000369
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100370/* So far, all bash compat is controlled by one config option */
371/* Separate defines document which part of code implements what */
372#define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
373#define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100374#define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
375#define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko4ee824f2017-07-03 01:22:13 +0200376#define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
Denys Vlasenko1f41c882017-08-09 13:52:36 +0200377#define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100378
379
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200380/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000381#define LEAK_HUNTING 0
382#define BUILD_AS_NOMMU 0
383/* Enable/disable sanity checks. Ok to enable in production,
384 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
385 * Keeping 1 for now even in released versions.
386 */
387#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200388/* Slightly bigger (+200 bytes), but faster hush.
389 * So far it only enables a trick with counting SIGCHLDs and forks,
390 * which allows us to do fewer waitpid's.
391 * (we can detect a case where neither forks were done nor SIGCHLDs happened
392 * and therefore waitpid will return the same result as last time)
393 */
394#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200395/* TODO: implement simplified code for users which do not need ${var%...} ops
396 * So far ${var%...} ops are always enabled:
397 */
398#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000399
400
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000401#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000402# undef BB_MMU
403# undef USE_FOR_NOMMU
404# undef USE_FOR_MMU
405# define BB_MMU 0
406# define USE_FOR_NOMMU(...) __VA_ARGS__
407# define USE_FOR_MMU(...)
408#endif
409
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200410#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100411#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000412/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000413# undef CONFIG_FEATURE_SH_STANDALONE
414# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000415# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100416# undef IF_NOT_FEATURE_SH_STANDALONE
417# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000418# define IF_FEATURE_SH_STANDALONE(...)
419# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000420#endif
421
Denis Vlasenko05743d72008-02-10 12:10:08 +0000422#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000423# undef ENABLE_FEATURE_EDITING
424# define ENABLE_FEATURE_EDITING 0
425# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
426# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200427# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
428# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000429#endif
430
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000431/* Do we support ANY keywords? */
432#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000433# define HAS_KEYWORDS 1
434# define IF_HAS_KEYWORDS(...) __VA_ARGS__
435# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000436#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000437# define HAS_KEYWORDS 0
438# define IF_HAS_KEYWORDS(...)
439# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000440#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000441
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000442/* If you comment out one of these below, it will be #defined later
443 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000444#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000445/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000446#define debug_printf_parse(...) do {} while (0)
447#define debug_print_tree(a, b) do {} while (0)
448#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000449#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000450#define debug_printf_jobs(...) do {} while (0)
451#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200452#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000453#define debug_printf_glob(...) do {} while (0)
Denys Vlasenko2db74612017-07-07 22:07:28 +0200454#define debug_printf_redir(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000455#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000456#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000457#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000458
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000459#define ERR_PTR ((void*)(long)1)
460
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100461#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000462
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200463#define _SPECIAL_VARS_STR "_*@$!?#"
464#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
465#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100466#if BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200467/* Support / and // replace ops */
468/* Note that // is stored as \ in "encoded" string representation */
469# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
470# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
471# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
472#else
473# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
474# define VAR_SUBST_OPS "%#:-=+?"
475# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
476#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200477
Denys Vlasenko932b9972018-01-11 12:39:48 +0100478#define SPECIAL_VAR_SYMBOL_STR "\3"
479#define SPECIAL_VAR_SYMBOL 3
480/* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
481#define SPECIAL_VAR_QUOTED_SVS 1
Eric Andersen25f27032001-04-26 23:22:31 +0000482
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200483struct variable;
484
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000485static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
486
487/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000488 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000489 */
490#if !BB_MMU
491typedef struct nommu_save_t {
492 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200493 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000494 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000495 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000496} nommu_save_t;
497#endif
498
Denys Vlasenko9b782552010-09-08 13:33:26 +0200499enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000500 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000501#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000502 RES_IF ,
503 RES_THEN ,
504 RES_ELIF ,
505 RES_ELSE ,
506 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000507#endif
508#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000509 RES_FOR ,
510 RES_WHILE ,
511 RES_UNTIL ,
512 RES_DO ,
513 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000514#endif
515#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000516 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000517#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000518#if ENABLE_HUSH_CASE
519 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200520 /* three pseudo-keywords support contrived "case" syntax: */
521 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
522 RES_MATCH , /* "word)" */
523 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000524 RES_ESAC ,
525#endif
526 RES_XXXX ,
527 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200528};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000529
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000530typedef struct o_string {
531 char *data;
532 int length; /* position where data is appended */
533 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200534 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000535 /* At least some part of the string was inside '' or "",
536 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200537 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000538 smallint has_empty_slot;
539 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
540} o_string;
541enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200542 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
543 EXP_FLAG_GLOB = 0x2,
544 /* Protect newly added chars against globbing
545 * by prepending \ to *, ?, [, \ */
546 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
547};
548enum {
549 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000550 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200551 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200552 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200553 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000554};
555/* Used for initialization: o_string foo = NULL_O_STRING; */
556#define NULL_O_STRING { NULL }
557
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200558#ifndef debug_printf_parse
559static const char *const assignment_flag[] = {
560 "MAYBE_ASSIGNMENT",
561 "DEFINITELY_ASSIGNMENT",
562 "NOT_ASSIGNMENT",
563 "WORD_IS_KEYWORD",
564};
565#endif
566
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000567typedef struct in_str {
568 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000569#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000570 smallint promptmode; /* 0: PS1, 1: PS2 */
571#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200572 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200573 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000574 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000575} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000576
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200577/* The descrip member of this structure is only used to make
578 * debugging output pretty */
579static const struct {
580 int mode;
581 signed char default_fd;
582 char descrip[3];
583} redir_table[] = {
584 { O_RDONLY, 0, "<" },
585 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
586 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
587 { O_CREAT|O_RDWR, 1, "<>" },
588 { O_RDONLY, 0, "<<" },
589/* Should not be needed. Bogus default_fd helps in debugging */
590/* { O_RDONLY, 77, "<<" }, */
591};
592
Eric Andersen25f27032001-04-26 23:22:31 +0000593struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000594 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000595 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000596 int rd_fd; /* fd to redirect */
597 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
598 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000599 smallint rd_type; /* (enum redir_type) */
600 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000601 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200602 * bit 0: do we need to trim leading tabs?
603 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000604 */
Eric Andersen25f27032001-04-26 23:22:31 +0000605};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000606typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200607 REDIRECT_INPUT = 0,
608 REDIRECT_OVERWRITE = 1,
609 REDIRECT_APPEND = 2,
610 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000611 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200612 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000613
614 REDIRFD_CLOSE = -3,
615 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000616 REDIRFD_TO_FILE = -1,
617 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000618
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000619 HEREDOC_SKIPTABS = 1,
620 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000621} redir_type;
622
Eric Andersen25f27032001-04-26 23:22:31 +0000623
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000624struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000625 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000626 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko5807e182018-02-08 19:19:04 +0100627#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100628 unsigned lineno;
629#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200630 smallint cmd_type; /* CMD_xxx */
631#define CMD_NORMAL 0
632#define CMD_SUBSHELL 1
Kang-Che Sung027d3ab2017-01-11 14:18:15 +0100633#if BASH_TEST2
Denys Vlasenkod383b492010-09-06 10:22:13 +0200634/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200635# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000636#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200637#if ENABLE_HUSH_FUNCTIONS
638# define CMD_FUNCDEF 3
639#endif
640
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100641 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200642 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
643 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000644#if !BB_MMU
645 char *group_as_string;
646#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000647#if ENABLE_HUSH_FUNCTIONS
648 struct function *child_func;
649/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200650 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000651 * When we execute "f1() {a;}" cmd, we create new function and clear
652 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200653 * When we execute "f1() {b;}", we notice that f1 exists,
654 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000655 * we put those fields back into cmd->xxx
656 * (struct function has ->parent_cmd ptr to facilitate that).
657 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
658 * Without this trick, loop would execute a;b;b;b;...
659 * instead of correct sequence a;b;a;b;...
660 * When command is freed, it severs the link
661 * (sets ->child_func->parent_cmd to NULL).
662 */
663#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000664 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000665/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
666 * and on execution these are substituted with their values.
667 * Substitution can make _several_ words out of one argv[n]!
668 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000669 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000670 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000671 struct redir_struct *redirects; /* I/O redirections */
672};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000673/* Is there anything in this command at all? */
674#define IS_NULL_CMD(cmd) \
675 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
676
Eric Andersen25f27032001-04-26 23:22:31 +0000677struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000678 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000679 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000680 int alive_cmds; /* number of commands running (not exited) */
681 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000682#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100683 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000684 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000685 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000686#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000687 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000688 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000689 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
690 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000691};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000692typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100693 PIPE_SEQ = 0,
694 PIPE_AND = 1,
695 PIPE_OR = 2,
696 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000697} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000698/* Is there anything in this pipe at all? */
699#define IS_NULL_PIPE(pi) \
700 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000701
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000702/* This holds pointers to the various results of parsing */
703struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000704 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000705 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000706 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000707 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000708 /* last command in pipe (being constructed right now) */
709 struct command *command;
710 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000711 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000712#if !BB_MMU
713 o_string as_string;
714#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000715#if HAS_KEYWORDS
716 smallint ctx_res_w;
717 smallint ctx_inverted; /* "! cmd | cmd" */
718#if ENABLE_HUSH_CASE
719 smallint ctx_dsemicolon; /* ";;" seen */
720#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000721 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
722 int old_flag;
723 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000724 * example: "if pipe1; pipe2; then pipe3; fi"
725 * when we see "if" or "then", we malloc and copy current context,
726 * and make ->stack point to it. then we parse pipeN.
727 * when closing "then" / fi" / whatever is found,
728 * we move list_head into ->stack->command->group,
729 * copy ->stack into current context, and delete ->stack.
730 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000731 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000732 struct parse_context *stack;
733#endif
734};
735
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000736/* On program start, environ points to initial environment.
737 * putenv adds new pointers into it, unsetenv removes them.
738 * Neither of these (de)allocates the strings.
739 * setenv allocates new strings in malloc space and does putenv,
740 * and thus setenv is unusable (leaky) for shell's purposes */
741#define setenv(...) setenv_is_leaky_dont_use()
742struct variable {
743 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000744 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200745#if ENABLE_HUSH_LOCAL
746 unsigned func_nest_level;
747#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000748 int max_len; /* if > 0, name is part of initial env; else name is malloced */
749 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000750 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000751};
752
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000753enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000754 BC_BREAK = 1,
755 BC_CONTINUE = 2,
756};
757
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000758#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000759struct function {
760 struct function *next;
761 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000762 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000763 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200764# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000765 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200766# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000767};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000768#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000769
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000770
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100771/* set -/+o OPT support. (TODO: make it optional)
772 * bash supports the following opts:
773 * allexport off
774 * braceexpand on
775 * emacs on
776 * errexit off
777 * errtrace off
778 * functrace off
779 * hashall on
780 * histexpand off
781 * history on
782 * ignoreeof off
783 * interactive-comments on
784 * keyword off
785 * monitor on
786 * noclobber off
787 * noexec off
788 * noglob off
789 * nolog off
790 * notify off
791 * nounset off
792 * onecmd off
793 * physical off
794 * pipefail off
795 * posix off
796 * privileged off
797 * verbose off
798 * vi off
799 * xtrace off
800 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800801static const char o_opt_strings[] ALIGN1 =
802 "pipefail\0"
803 "noexec\0"
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200804 "errexit\0"
Dan Fandrich85c62472010-11-20 13:05:17 -0800805#if ENABLE_HUSH_MODE_X
806 "xtrace\0"
807#endif
808 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100809enum {
810 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800811 OPT_O_NOEXEC,
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200812 OPT_O_ERREXIT,
Dan Fandrich85c62472010-11-20 13:05:17 -0800813#if ENABLE_HUSH_MODE_X
814 OPT_O_XTRACE,
815#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100816 NUM_OPT_O
817};
818
819
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200820struct FILE_list {
821 struct FILE_list *next;
822 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200823 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200824};
825
826
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000827/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000828/* Sorted roughly by size (smaller offsets == smaller code) */
829struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000830 /* interactive_fd != 0 means we are an interactive shell.
831 * If we are, then saved_tty_pgrp can also be != 0, meaning
832 * that controlling tty is available. With saved_tty_pgrp == 0,
833 * job control still works, but terminal signals
834 * (^C, ^Z, ^Y, ^\) won't work at all, and background
835 * process groups can only be created with "cmd &".
836 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
837 * to give tty to the foreground process group,
838 * and will take it back when the group is stopped (^Z)
839 * or killed (^C).
840 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000841#if ENABLE_HUSH_INTERACTIVE
842 /* 'interactive_fd' is a fd# open to ctty, if we have one
843 * _AND_ if we decided to act interactively */
844 int interactive_fd;
845 const char *PS1;
846 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000847# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000848#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000849# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850#endif
851#if ENABLE_FEATURE_EDITING
852 line_input_t *line_input_state;
853#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000854 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200855 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000856 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200857#if ENABLE_HUSH_RANDOM_SUPPORT
858 random_t random_gen;
859#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000860#if ENABLE_HUSH_JOB
861 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100862 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000863 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000864 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400865# define G_saved_tty_pgrp (G.saved_tty_pgrp)
866#else
867# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000868#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +0200869 /* How deeply are we in context where "set -e" is ignored */
870 int errexit_depth;
871 /* "set -e" rules (do we follow them correctly?):
872 * Exit if pipe, list, or compound command exits with a non-zero status.
873 * Shell does not exit if failed command is part of condition in
874 * if/while, part of && or || list except the last command, any command
875 * in a pipe but the last, or if the command's return value is being
876 * inverted with !. If a compound command other than a subshell returns a
877 * non-zero status because a command failed while -e was being ignored, the
878 * shell does not exit. A trap on ERR, if set, is executed before the shell
879 * exits [ERR is a bashism].
880 *
881 * If a compound command or function executes in a context where -e is
882 * ignored, none of the commands executed within are affected by the -e
883 * setting. If a compound command or function sets -e while executing in a
884 * context where -e is ignored, that setting does not have any effect until
885 * the compound command or the command containing the function call completes.
886 */
887
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100888 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100889#if ENABLE_HUSH_MODE_X
890# define G_x_mode (G.o_opt[OPT_O_XTRACE])
891#else
892# define G_x_mode 0
893#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000894 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000895#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000896 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000897#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000898#if ENABLE_HUSH_FUNCTIONS
899 /* 0: outside of a function (or sourced file)
900 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000901 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000902 */
903 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200904# define G_flag_return_in_progress (G.flag_return_in_progress)
905#else
906# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000907#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000908 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000909 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000910 smalluint last_exitcode;
Denys Vlasenko840a4352017-07-07 22:56:02 +0200911 smalluint last_bg_pid_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100912#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000913 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000914 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100915# define G_global_args_malloced (G.global_args_malloced)
916#else
917# define G_global_args_malloced 0
918#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000919 /* how many non-NULL argv's we have. NB: $# + 1 */
920 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000921 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000922#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000923 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000924#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000925#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000926 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000927 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000928#endif
Denys Vlasenko238ff982017-08-29 13:38:30 +0200929#if ENABLE_HUSH_GETOPTS
930 unsigned getopt_count;
931#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000932 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000933 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200934 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200935 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000936#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000937 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200938# if ENABLE_HUSH_LOCAL
939 struct variable **shadowed_vars_pp;
940 unsigned func_nest_level;
941# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000942#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000943 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200944#if ENABLE_HUSH_FAST
945 unsigned count_SIGCHLD;
946 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200947 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200948#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +0100949#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100950 unsigned lineno;
951 char *lineno_var;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +0100952#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200953 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200954 /* Which signals have non-DFL handler (even with no traps set)?
955 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200956 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200957 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200958 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200959 * Other than these two times, never modified.
960 */
961 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200962#if ENABLE_HUSH_JOB
963 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100964# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200965#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200966# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200967#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100968#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000969 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100970# define G_traps G.traps
971#else
972# define G_traps ((char**)NULL)
973#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200974 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100975#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000976 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100977#endif
978#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000979 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000980#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200981 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200982#if ENABLE_FEATURE_EDITING
983 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
984#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000985};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000986#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000987/* Not #defining name to G.name - this quickly gets unwieldy
988 * (too many defines). Also, I actually prefer to see when a variable
989 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000990#define INIT_G() do { \
991 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200992 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
993 sigfillset(&G.sa.sa_mask); \
994 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000995} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000996
997
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000998/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200999static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001000#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001001static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001002#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001003static int builtin_eval(char **argv) FAST_FUNC;
1004static int builtin_exec(char **argv) FAST_FUNC;
1005static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001006#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001007static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001008#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001009#if ENABLE_HUSH_READONLY
1010static int builtin_readonly(char **argv) FAST_FUNC;
1011#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001012#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001013static int builtin_fg_bg(char **argv) FAST_FUNC;
1014static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001015#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001016#if ENABLE_HUSH_GETOPTS
1017static int builtin_getopts(char **argv) FAST_FUNC;
1018#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001019#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001020static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001021#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001022#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001023static int builtin_history(char **argv) FAST_FUNC;
1024#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001025#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001026static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001027#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001028#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001029static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001030#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001031#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001032static int builtin_printf(char **argv) FAST_FUNC;
1033#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001034static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001035#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001036static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001037#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001038#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001039static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001040#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001041static int builtin_shift(char **argv) FAST_FUNC;
1042static int builtin_source(char **argv) FAST_FUNC;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001043#if ENABLE_HUSH_TEST || BASH_TEST2
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001044static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +01001045#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001046#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001047static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001048#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001049#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001050static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001051#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001052#if ENABLE_HUSH_TIMES
1053static int builtin_times(char **argv) FAST_FUNC;
1054#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001055static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001056#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001057static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001058#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001059#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001060static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001061#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001062#if ENABLE_HUSH_KILL
1063static int builtin_kill(char **argv) FAST_FUNC;
1064#endif
1065#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001066static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001067#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001068#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001069static int builtin_break(char **argv) FAST_FUNC;
1070static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001071#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001072#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001073static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001074#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001075
1076/* Table of built-in functions. They can be forked or not, depending on
1077 * context: within pipes, they fork. As simple commands, they do not.
1078 * When used in non-forking context, they can change global variables
1079 * in the parent shell process. If forked, of course they cannot.
1080 * For example, 'unset foo | whatever' will parse and run, but foo will
1081 * still be set at the end. */
1082struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +01001083 const char *b_cmd;
1084 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001085#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +01001086 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001087# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001088#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001089# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001090#endif
1091};
1092
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001093static const struct built_in_command bltins1[] = {
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001094 BLTIN("." , builtin_source , "Run commands in file"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001095 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001096#if ENABLE_HUSH_JOB
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001097 BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001098#endif
1099#if ENABLE_HUSH_LOOPS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001100 BLTIN("break" , builtin_break , "Exit loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001101#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001102 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001103#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001104 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001105#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001106 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1107 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001108 BLTIN("exit" , builtin_exit , NULL),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001109#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001110 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001111#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001112#if ENABLE_HUSH_JOB
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001113 BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001114#endif
Denys Vlasenko74d40582017-08-11 01:32:46 +02001115#if ENABLE_HUSH_GETOPTS
1116 BLTIN("getopts" , builtin_getopts , NULL),
1117#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001118#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001119 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001120#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001121#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001122 BLTIN("history" , builtin_history , "Show history"),
Flemming Madsend96ffda2013-04-07 18:47:24 +02001123#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001124#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001125 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001126#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001127#if ENABLE_HUSH_KILL
1128 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1129#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001130#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001131 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001132#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001133#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001134 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001135#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001136#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001137 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001138#endif
Denys Vlasenko1e660422017-07-17 21:10:50 +02001139#if ENABLE_HUSH_READONLY
1140 BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
1141#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001142#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001143 BLTIN("return" , builtin_return , "Return from function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001144#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001145#if ENABLE_HUSH_SET
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001146 BLTIN("set" , builtin_set , "Set positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001147#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001148 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01001149#if BASH_SOURCE
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001150 BLTIN("source" , builtin_source , NULL),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001151#endif
Denys Vlasenko11f2e992017-08-10 16:34:03 +02001152#if ENABLE_HUSH_TIMES
1153 BLTIN("times" , builtin_times , NULL),
1154#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001155#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001156 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001157#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001158 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001159#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001160 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001161#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001162#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001163 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001164#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001165#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001166 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001167#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001168#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001169 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001170#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001171#if ENABLE_HUSH_WAIT
Denys Vlasenkod2c15bc2017-07-18 18:14:42 +02001172 BLTIN("wait" , builtin_wait , "Wait for process to finish"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001173#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001174};
Denys Vlasenko80f806c2017-01-10 16:51:10 +01001175/* These builtins won't be used if we are on NOMMU and need to re-exec
1176 * (it's cheaper to run an external program in this case):
1177 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001178static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001179#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001180 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001181#endif
Denys Vlasenko8944c672017-01-11 14:22:00 +01001182#if BASH_TEST2
1183 BLTIN("[[" , builtin_test , NULL),
1184#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001185#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001186 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001187#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001188#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001189 BLTIN("printf" , builtin_printf , NULL),
1190#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001191 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001192#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001193 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001194#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001195};
1196
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001197
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001198/* Debug printouts.
1199 */
1200#if HUSH_DEBUG
1201/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001202# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001203# define debug_enter() (G.debug_indent++)
1204# define debug_leave() (G.debug_indent--)
1205#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001206# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001207# define debug_enter() ((void)0)
1208# define debug_leave() ((void)0)
1209#endif
1210
1211#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001212# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001213#endif
1214
1215#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001216# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001217#endif
1218
1219#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001220#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001221#endif
1222
1223#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001224# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001225#endif
1226
1227#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001228# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001229# define DEBUG_JOBS 1
1230#else
1231# define DEBUG_JOBS 0
1232#endif
1233
1234#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001235# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001236# define DEBUG_EXPAND 1
1237#else
1238# define DEBUG_EXPAND 0
1239#endif
1240
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001241#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001242# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001243#endif
1244
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001245#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001246# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001247# define DEBUG_GLOB 1
1248#else
1249# define DEBUG_GLOB 0
1250#endif
1251
Denys Vlasenko2db74612017-07-07 22:07:28 +02001252#ifndef debug_printf_redir
1253# define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
1254#endif
1255
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001256#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001257# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001258#endif
1259
1260#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001261# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001262#endif
1263
1264#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001265# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001266# define DEBUG_CLEAN 1
1267#else
1268# define DEBUG_CLEAN 0
1269#endif
1270
1271#if DEBUG_EXPAND
1272static void debug_print_strings(const char *prefix, char **vv)
1273{
1274 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001275 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001276 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001277 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001278}
1279#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001280# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001281#endif
1282
1283
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001284/* Leak hunting. Use hush_leaktool.sh for post-processing.
1285 */
1286#if LEAK_HUNTING
1287static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001288{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001289 void *ptr = xmalloc((size + 0xff) & ~0xff);
1290 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1291 return ptr;
1292}
1293static void *xxrealloc(int lineno, void *ptr, size_t size)
1294{
1295 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1296 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1297 return ptr;
1298}
1299static char *xxstrdup(int lineno, const char *str)
1300{
1301 char *ptr = xstrdup(str);
1302 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1303 return ptr;
1304}
1305static void xxfree(void *ptr)
1306{
1307 fdprintf(2, "free %p\n", ptr);
1308 free(ptr);
1309}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001310# define xmalloc(s) xxmalloc(__LINE__, s)
1311# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1312# define xstrdup(s) xxstrdup(__LINE__, s)
1313# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001314#endif
1315
1316
1317/* Syntax and runtime errors. They always abort scripts.
1318 * In interactive use they usually discard unparsed and/or unexecuted commands
1319 * and return to the prompt.
1320 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1321 */
1322#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001323# define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001324# define syntax_error(lineno, msg) syntax_error(msg)
1325# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1326# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1327# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1328# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001329#endif
1330
Denys Vlasenko39701202017-08-02 19:44:05 +02001331static void die_if_script(void)
1332{
1333 if (!G_interactive_fd) {
1334 if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
1335 xfunc_error_retval = G.last_exitcode;
1336 xfunc_die();
1337 }
1338}
1339
1340static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001341{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001342 va_list p;
1343
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001344#if HUSH_DEBUG >= 2
1345 bb_error_msg("hush.c:%u", lineno);
1346#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001347 va_start(p, fmt);
1348 bb_verror_msg(fmt, p, NULL);
1349 va_end(p);
Denys Vlasenko39701202017-08-02 19:44:05 +02001350 die_if_script();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001351}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001352
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001353static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001354{
1355 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001356 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001357 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001358 bb_error_msg("syntax error");
Denys Vlasenko39701202017-08-02 19:44:05 +02001359 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001360}
1361
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001362static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001363{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001364 bb_error_msg("syntax error at '%s'", msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001365 die_if_script();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001366}
1367
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001368static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001369{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001370 bb_error_msg("syntax error: unterminated %s", s);
Denys Vlasenko39701202017-08-02 19:44:05 +02001371//? source4.tests fails: in bash, echo ${^} in script does not terminate the script
1372// die_if_script();
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001373}
1374
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001375static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001376{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001377 char msg[2] = { ch, '\0' };
1378 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001379}
1380
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001381static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001382{
1383 char msg[2];
1384 msg[0] = ch;
1385 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001386#if HUSH_DEBUG >= 2
1387 bb_error_msg("hush.c:%u", lineno);
1388#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001389 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denys Vlasenko39701202017-08-02 19:44:05 +02001390 die_if_script();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001391}
1392
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001393#if HUSH_DEBUG < 2
Denys Vlasenko39701202017-08-02 19:44:05 +02001394# undef msg_and_die_if_script
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001395# undef syntax_error
1396# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001397# undef syntax_error_unterm_ch
1398# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001399# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001400#else
Denys Vlasenko39701202017-08-02 19:44:05 +02001401# define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001402# define syntax_error(msg) syntax_error(__LINE__, msg)
1403# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1404# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1405# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1406# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001407#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001408
Denis Vlasenko552433b2009-04-04 19:29:21 +00001409
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001410#if ENABLE_HUSH_INTERACTIVE
1411static void cmdedit_update_prompt(void);
1412#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001413# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001414#endif
1415
1416
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001417/* Utility functions
1418 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001419/* Replace each \x with x in place, return ptr past NUL. */
1420static char *unbackslash(char *src)
1421{
Denys Vlasenko71885402009-09-24 01:44:13 +02001422 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001423 while (1) {
1424 if (*src == '\\')
1425 src++;
1426 if ((*dst++ = *src++) == '\0')
1427 break;
1428 }
1429 return dst;
1430}
1431
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001432static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001433{
1434 int i;
1435 unsigned count1;
1436 unsigned count2;
1437 char **v;
1438
1439 v = strings;
1440 count1 = 0;
1441 if (v) {
1442 while (*v) {
1443 count1++;
1444 v++;
1445 }
1446 }
1447 count2 = 0;
1448 v = add;
1449 while (*v) {
1450 count2++;
1451 v++;
1452 }
1453 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1454 v[count1 + count2] = NULL;
1455 i = count2;
1456 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001457 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001458 return v;
1459}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001460#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001461static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1462{
1463 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1464 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1465 return ptr;
1466}
1467#define add_strings_to_strings(strings, add, need_to_dup) \
1468 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1469#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001470
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001471/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001472static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001473{
1474 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001475 v[0] = add;
1476 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001477 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001478}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001479#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001480static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1481{
1482 char **ptr = add_string_to_strings(strings, add);
1483 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1484 return ptr;
1485}
1486#define add_string_to_strings(strings, add) \
1487 xx_add_string_to_strings(__LINE__, strings, add)
1488#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001489
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001490static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001491{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001492 char **v;
1493
1494 if (!strings)
1495 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001496 v = strings;
1497 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001498 free(*v);
1499 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001500 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001501 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001502}
1503
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001504static int dup_CLOEXEC(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001505{
Denys Vlasenko2db74612017-07-07 22:07:28 +02001506 int newfd;
1507 repeat:
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02001508 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
1509 if (newfd >= 0) {
1510 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1511 fcntl(newfd, F_SETFD, FD_CLOEXEC);
1512 } else { /* newfd < 0 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02001513 if (errno == EBUSY)
1514 goto repeat;
1515 if (errno == EINTR)
1516 goto repeat;
1517 }
1518 return newfd;
1519}
1520
Denys Vlasenko657e9002017-07-30 23:34:04 +02001521static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001522{
1523 int newfd;
1524 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001525 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001526 if (newfd < 0) {
1527 if (errno == EBUSY)
1528 goto repeat;
1529 if (errno == EINTR)
1530 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001531 /* fd was not open? */
1532 if (errno == EBADF)
1533 return fd;
1534 xfunc_die();
1535 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001536 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1537 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001538 close(fd);
1539 return newfd;
1540}
1541
1542
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001543/* Manipulating the list of open FILEs */
1544static FILE *remember_FILE(FILE *fp)
1545{
1546 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001547 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001548 n->next = G.FILE_list;
1549 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001550 n->fp = fp;
1551 n->fd = fileno(fp);
1552 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001553 }
1554 return fp;
1555}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001556static void fclose_and_forget(FILE *fp)
1557{
1558 struct FILE_list **pp = &G.FILE_list;
1559 while (*pp) {
1560 struct FILE_list *cur = *pp;
1561 if (cur->fp == fp) {
1562 *pp = cur->next;
1563 free(cur);
1564 break;
1565 }
1566 pp = &cur->next;
1567 }
1568 fclose(fp);
1569}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001570static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001571{
1572 struct FILE_list *fl = G.FILE_list;
1573 while (fl) {
1574 if (fd == fl->fd) {
1575 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001576 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001577 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 +02001578 return 1;
1579 }
1580 fl = fl->next;
1581 }
1582 return 0;
1583}
1584static void restore_redirected_FILEs(void)
1585{
1586 struct FILE_list *fl = G.FILE_list;
1587 while (fl) {
1588 int should_be = fileno(fl->fp);
1589 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001590 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001591 xmove_fd(fl->fd, should_be);
1592 fl->fd = should_be;
1593 }
1594 fl = fl->next;
1595 }
1596}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001597#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001598static void close_all_FILE_list(void)
1599{
1600 struct FILE_list *fl = G.FILE_list;
1601 while (fl) {
1602 /* fclose would also free FILE object.
1603 * It is disastrous if we share memory with a vforked parent.
1604 * I'm not sure we never come here after vfork.
1605 * Therefore just close fd, nothing more.
1606 */
1607 /*fclose(fl->fp); - unsafe */
1608 close(fl->fd);
1609 fl = fl->next;
1610 }
1611}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001612#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001613static int fd_in_FILEs(int fd)
1614{
1615 struct FILE_list *fl = G.FILE_list;
1616 while (fl) {
1617 if (fl->fd == fd)
1618 return 1;
1619 fl = fl->next;
1620 }
1621 return 0;
1622}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001623
1624
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001625/* Helpers for setting new $n and restoring them back
1626 */
1627typedef struct save_arg_t {
1628 char *sv_argv0;
1629 char **sv_g_argv;
1630 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001631 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001632} save_arg_t;
1633
1634static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1635{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001636 sv->sv_argv0 = argv[0];
1637 sv->sv_g_argv = G.global_argv;
1638 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001639 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001640
1641 argv[0] = G.global_argv[0]; /* retain $0 */
1642 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001643 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001644
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001645 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001646}
1647
1648static void restore_G_args(save_arg_t *sv, char **argv)
1649{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001650#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001651 if (G.global_args_malloced) {
1652 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001653 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001654 while (*++pp) /* note: does not free $0 */
1655 free(*pp);
1656 free(G.global_argv);
1657 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001658#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001659 argv[0] = sv->sv_argv0;
1660 G.global_argv = sv->sv_g_argv;
1661 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001662 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001663}
1664
1665
Denis Vlasenkod5762932009-03-31 11:22:57 +00001666/* Basic theory of signal handling in shell
1667 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001668 * This does not describe what hush does, rather, it is current understanding
1669 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001670 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1671 *
1672 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1673 * is finished or backgrounded. It is the same in interactive and
1674 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001675 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001676 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001677 * backgrounds (i.e. stops) or kills all members of currently running
1678 * pipe.
1679 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001680 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001681 * or by SIGINT in interactive shell.
1682 *
1683 * Trap handlers will execute even within trap handlers. (right?)
1684 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001685 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1686 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001687 *
1688 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001689 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001690 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001691 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001692 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001693 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001694 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001695 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001696 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001697 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001698 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001699 *
1700 * SIGQUIT: ignore
1701 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001702 * SIGHUP (interactive):
1703 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001704 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001705 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1706 * that all pipe members are stopped. Try this in bash:
1707 * while :; do :; done - ^Z does not background it
1708 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001709 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001710 * of the command line, show prompt. NB: ^C does not send SIGINT
1711 * to interactive shell while shell is waiting for a pipe,
1712 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001713 * Example 1: this waits 5 sec, but does not execute ls:
1714 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1715 * Example 2: this does not wait and does not execute ls:
1716 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1717 * Example 3: this does not wait 5 sec, but executes ls:
1718 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001719 * Example 4: this does not wait and does not execute ls:
1720 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001721 *
1722 * (What happens to signals which are IGN on shell start?)
1723 * (What happens with signal mask on shell start?)
1724 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001725 * Old implementation
1726 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001727 * We use in-kernel pending signal mask to determine which signals were sent.
1728 * We block all signals which we don't want to take action immediately,
1729 * i.e. we block all signals which need to have special handling as described
1730 * above, and all signals which have traps set.
1731 * After each pipe execution, we extract any pending signals via sigtimedwait()
1732 * and act on them.
1733 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001734 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001735 * sigset_t blocked_set: current blocked signal set
1736 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001737 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001738 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001739 * "trap 'cmd' SIGxxx":
1740 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001741 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001742 * unblock signals with special interactive handling
1743 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001744 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001745 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001746 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001747 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001748 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001749 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001750 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001751 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001752 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001753 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001754 * Standard says "When a subshell is entered, traps that are not being ignored
1755 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001756 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001757 *
1758 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001759 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001760 * masked signals are not visible!
1761 *
1762 * New implementation
1763 * ==================
1764 * We record each signal we are interested in by installing signal handler
1765 * for them - a bit like emulating kernel pending signal mask in userspace.
1766 * We are interested in: signals which need to have special handling
1767 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001768 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001769 * After each pipe execution, we extract any pending signals
1770 * and act on them.
1771 *
1772 * unsigned special_sig_mask: a mask of shell-special signals.
1773 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1774 * char *traps[sig] if trap for sig is set (even if it's '').
1775 * sigset_t pending_set: set of sigs we received.
1776 *
1777 * "trap - SIGxxx":
1778 * if sig is in special_sig_mask, set handler back to:
1779 * record_pending_signo, or to IGN if it's a tty stop signal
1780 * if sig is in fatal_sig_mask, set handler back to sigexit.
1781 * else: set handler back to SIG_DFL
1782 * "trap 'cmd' SIGxxx":
1783 * set handler to record_pending_signo.
1784 * "trap '' SIGxxx":
1785 * set handler to SIG_IGN.
1786 * after [v]fork, if we plan to be a shell:
1787 * set signals with special interactive handling to SIG_DFL
1788 * (because child shell is not interactive),
1789 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1790 * after [v]fork, if we plan to exec:
1791 * POSIX says fork clears pending signal mask in child - no need to clear it.
1792 *
1793 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1794 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1795 *
1796 * Note (compat):
1797 * Standard says "When a subshell is entered, traps that are not being ignored
1798 * are set to the default actions". bash interprets it so that traps which
1799 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001800 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001801enum {
1802 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001803 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001804 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001805 | (1 << SIGHUP)
1806 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001807 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001808#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001809 | (1 << SIGTTIN)
1810 | (1 << SIGTTOU)
1811 | (1 << SIGTSTP)
1812#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001813 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001814};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001815
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001816static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001817{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001818 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001819#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001820 if (sig == SIGCHLD) {
1821 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001822//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 +02001823 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001824#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001825}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001826
Denys Vlasenko0806e402011-05-12 23:06:20 +02001827static sighandler_t install_sighandler(int sig, sighandler_t handler)
1828{
1829 struct sigaction old_sa;
1830
1831 /* We could use signal() to install handlers... almost:
1832 * except that we need to mask ALL signals while handlers run.
1833 * I saw signal nesting in strace, race window isn't small.
1834 * SA_RESTART is also needed, but in Linux, signal()
1835 * sets SA_RESTART too.
1836 */
1837 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1838 /* sigfillset(&G.sa.sa_mask); - already done */
1839 /* G.sa.sa_flags = SA_RESTART; - already done */
1840 G.sa.sa_handler = handler;
1841 sigaction(sig, &G.sa, &old_sa);
1842 return old_sa.sa_handler;
1843}
1844
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001845static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001846
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001847static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001848static void restore_ttypgrp_and__exit(void)
1849{
1850 /* xfunc has failed! die die die */
1851 /* no EXIT traps, this is an escape hatch! */
1852 G.exiting = 1;
1853 hush_exit(xfunc_error_retval);
1854}
1855
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001856#if ENABLE_HUSH_JOB
1857
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001858/* Needed only on some libc:
1859 * It was observed that on exit(), fgetc'ed buffered data
1860 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1861 * With the net effect that even after fork(), not vfork(),
1862 * exit() in NOEXECed applet in "sh SCRIPT":
1863 * noexec_applet_here
1864 * echo END_OF_SCRIPT
1865 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1866 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001867 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001868 * and in `cmd` handling.
1869 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1870 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001871static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001872static void fflush_and__exit(void)
1873{
1874 fflush_all();
1875 _exit(xfunc_error_retval);
1876}
1877
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001878/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001879# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001880/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001881# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001882
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001883/* Restores tty foreground process group, and exits.
1884 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001885 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001886 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001887 * We also call it if xfunc is exiting.
1888 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001889static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001890static void sigexit(int sig)
1891{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001892 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001893 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001894 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1895 /* Disable all signals: job control, SIGPIPE, etc.
1896 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1897 */
1898 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001899 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001900 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001901
1902 /* Not a signal, just exit */
1903 if (sig <= 0)
1904 _exit(- sig);
1905
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001906 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001907}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001908#else
1909
Denys Vlasenko8391c482010-05-22 17:50:43 +02001910# define disable_restore_tty_pgrp_on_exit() ((void)0)
1911# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001912
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001913#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001914
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001915static sighandler_t pick_sighandler(unsigned sig)
1916{
1917 sighandler_t handler = SIG_DFL;
1918 if (sig < sizeof(unsigned)*8) {
1919 unsigned sigmask = (1 << sig);
1920
1921#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001922 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001923 if (G_fatal_sig_mask & sigmask)
1924 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001925 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001926#endif
1927 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001928 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001929 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001930 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001931 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001932 * in an endless loop when we try to do some
1933 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001934 */
1935 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1936 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001937 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001938 }
1939 return handler;
1940}
1941
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001942/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001943static void hush_exit(int exitcode)
1944{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001945#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1946 save_history(G.line_input_state);
1947#endif
1948
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001949 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001950 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001951 char *argv[3];
1952 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001953 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001954 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001955 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001956 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001957 * "trap" will still show it, if executed
1958 * in the handler */
1959 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001960 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001961
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001962#if ENABLE_FEATURE_CLEAN_UP
1963 {
1964 struct variable *cur_var;
1965 if (G.cwd != bb_msg_unknown)
1966 free((char*)G.cwd);
1967 cur_var = G.top_var;
1968 while (cur_var) {
1969 struct variable *tmp = cur_var;
1970 if (!cur_var->max_len)
1971 free(cur_var->varstr);
1972 cur_var = cur_var->next;
1973 free(tmp);
1974 }
1975 }
1976#endif
1977
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001978 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001979#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001980 sigexit(- (exitcode & 0xff));
1981#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001982 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001983#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001984}
1985
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001986
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001987//TODO: return a mask of ALL handled sigs?
1988static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001989{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001990 int last_sig = 0;
1991
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001992 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001993 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001994
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001995 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001996 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001997 sig = 0;
1998 do {
1999 sig++;
2000 if (sigismember(&G.pending_set, sig)) {
2001 sigdelset(&G.pending_set, sig);
2002 goto got_sig;
2003 }
2004 } while (sig < NSIG);
2005 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002006 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002007 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002008 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002009 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002010 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002011 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002012 char *argv[3];
2013 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002014 argv[1] = xstrdup(G_traps[sig]);
2015 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002016 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002017 save_rcode = G.last_exitcode;
2018 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002019 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002020//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002021 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002022 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002023 } /* else: "" trap, ignoring signal */
2024 continue;
2025 }
2026 /* not a trap: special action */
2027 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002028 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002029 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002030 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002031 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002032 break;
2033#if ENABLE_HUSH_JOB
2034 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002035//TODO: why are we doing this? ash and dash don't do this,
2036//they have no handler for SIGHUP at all,
2037//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002038 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002039 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002040 /* bash is observed to signal whole process groups,
2041 * not individual processes */
2042 for (job = G.job_list; job; job = job->next) {
2043 if (job->pgrp <= 0)
2044 continue;
2045 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2046 if (kill(- job->pgrp, SIGHUP) == 0)
2047 kill(- job->pgrp, SIGCONT);
2048 }
2049 sigexit(SIGHUP);
2050 }
2051#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002052#if ENABLE_HUSH_FAST
2053 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002054 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002055 G.count_SIGCHLD++;
2056//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2057 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002058 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002059 * This simplifies wait builtin a bit.
2060 */
2061 break;
2062#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002063 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002064 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002065 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002066 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002067 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002068 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002069 * in interactive shell, because TERM is ignored.
2070 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002071 break;
2072 }
2073 }
2074 return last_sig;
2075}
2076
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002077
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002078static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002079{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002080 if (force || G.cwd == NULL) {
2081 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2082 * we must not try to free(bb_msg_unknown) */
2083 if (G.cwd == bb_msg_unknown)
2084 G.cwd = NULL;
2085 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2086 if (!G.cwd)
2087 G.cwd = bb_msg_unknown;
2088 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002089 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002090}
2091
Denis Vlasenko83506862007-11-23 13:11:42 +00002092
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002093/*
2094 * Shell and environment variable support
2095 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002096static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002097{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002098 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002099 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002100
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002101 pp = &G.top_var;
2102 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002103 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002104 return pp;
2105 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002106 }
2107 return NULL;
2108}
2109
Denys Vlasenko03dad222010-01-12 23:29:57 +01002110static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002111{
Denys Vlasenko29082232010-07-16 13:52:32 +02002112 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002113 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002114
2115 if (G.expanded_assignments) {
2116 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002117 while (*cpp) {
2118 char *cp = *cpp;
2119 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2120 return cp + len + 1;
2121 cpp++;
2122 }
2123 }
2124
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002125 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002126 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002127 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002128
Denys Vlasenkodea47882009-10-09 15:40:49 +02002129 if (strcmp(name, "PPID") == 0)
2130 return utoa(G.root_ppid);
2131 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002132#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002133 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002134 return utoa(next_random(&G.random_gen));
2135#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002136 return NULL;
2137}
2138
2139/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002140 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002141 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002142#define SETFLAG_EXPORT (1 << 0)
2143#define SETFLAG_UNEXPORT (1 << 1)
2144#define SETFLAG_MAKE_RO (1 << 2)
2145#define SETFLAG_LOCAL_SHIFT 3
2146static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002147{
Denys Vlasenko295fef82009-06-03 12:47:26 +02002148 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002149 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002150 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002151 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002152 int name_len;
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002153 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002154
Denis Vlasenko950bd722009-04-21 11:23:56 +00002155 eq_sign = strchr(str, '=');
2156 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002157 free(str);
2158 return -1;
2159 }
2160
Denis Vlasenko950bd722009-04-21 11:23:56 +00002161 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko5807e182018-02-08 19:19:04 +01002162#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002163 if (G.lineno_var) {
2164 if (name_len == 7 && strncmp("LINENO", str, 6) == 0)
2165 G.lineno_var = NULL;
2166 }
2167#endif
2168
Denys Vlasenko295fef82009-06-03 12:47:26 +02002169 var_pp = &G.top_var;
2170 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002171 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002172 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002173 continue;
2174 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002175
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002176 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002177 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002178 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002179 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002180//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2181//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002182 return -1;
2183 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002184 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002185 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2186 *eq_sign = '\0';
2187 unsetenv(str);
2188 *eq_sign = '=';
2189 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002190#if ENABLE_HUSH_LOCAL
2191 if (cur->func_nest_level < local_lvl) {
2192 /* New variable is declared as local,
2193 * and existing one is global, or local
2194 * from enclosing function.
2195 * Remove and save old one: */
2196 *var_pp = cur->next;
2197 cur->next = *G.shadowed_vars_pp;
2198 *G.shadowed_vars_pp = cur;
2199 /* bash 3.2.33(1) and exported vars:
2200 * # export z=z
2201 * # f() { local z=a; env | grep ^z; }
2202 * # f
2203 * z=a
2204 * # env | grep ^z
2205 * z=z
2206 */
2207 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002208 flags |= SETFLAG_EXPORT;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002209 break;
2210 }
2211#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00002212 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002213 free_and_exp:
2214 free(str);
2215 goto exp;
2216 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002217 if (cur->max_len != 0) {
2218 if (cur->max_len >= strlen(str)) {
2219 /* This one is from startup env, reuse space */
2220 strcpy(cur->varstr, str);
2221 goto free_and_exp;
2222 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002223 /* Can't reuse */
2224 cur->max_len = 0;
2225 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002226 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002227 /* max_len == 0 signifies "malloced" var, which we can
2228 * (and have to) free. But we can't free(cur->varstr) here:
2229 * if cur->flg_export is 1, it is in the environment.
2230 * We should either unsetenv+free, or wait until putenv,
2231 * then putenv(new)+free(old).
2232 */
2233 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002234 goto set_str_and_exp;
2235 }
2236
Denys Vlasenko295fef82009-06-03 12:47:26 +02002237 /* Not found - create new variable struct */
2238 cur = xzalloc(sizeof(*cur));
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002239 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
Denys Vlasenko295fef82009-06-03 12:47:26 +02002240 cur->next = *var_pp;
2241 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002242
2243 set_str_and_exp:
2244 cur->varstr = str;
2245 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002246#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002247 if (flags & SETFLAG_MAKE_RO) {
2248 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002249 }
2250#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002251 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002252 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002253 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2254 cmdedit_update_prompt();
Denys Vlasenko238ff982017-08-29 13:38:30 +02002255#if ENABLE_HUSH_GETOPTS
Denys Vlasenko55af51c2017-08-29 13:48:49 +02002256 /* defoptindvar is a "OPTIND=..." constant string */
2257 if (strncmp(cur->varstr, defoptindvar, 7) == 0)
Denys Vlasenko238ff982017-08-29 13:38:30 +02002258 G.getopt_count = 0;
2259#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002260 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002261 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002262 cur->flg_export = 0;
2263 /* unsetenv was already done */
2264 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002265 int i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002266 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002267 i = putenv(cur->varstr);
2268 /* only now we can free old exported malloced string */
2269 free(free_me);
2270 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002271 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002272 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002273 free(free_me);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002274 return 0;
2275}
2276
Denys Vlasenko6db47842009-09-05 20:15:17 +02002277/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002278static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002279{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002280 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002281}
2282
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002283static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002284{
2285 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002286 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002287
2288 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002289 return EXIT_SUCCESS;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002290
Denys Vlasenko238ff982017-08-29 13:38:30 +02002291#if ENABLE_HUSH_GETOPTS
2292 if (name_len == 6 && strncmp(name, "OPTIND", 6) == 0)
2293 G.getopt_count = 0;
2294#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +01002295#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002296 if (name_len == 6 && G.lineno_var && strncmp(name, "LINENO", 6) == 0)
2297 G.lineno_var = NULL;
2298#endif
2299
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002300 var_pp = &G.top_var;
2301 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002302 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2303 if (cur->flg_read_only) {
2304 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002305 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002306 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002307 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002308 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2309 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002310 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2311 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002312 if (!cur->max_len)
2313 free(cur->varstr);
2314 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002315 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002316 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002317 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002318 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002319 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002320}
2321
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002322#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002323static int unset_local_var(const char *name)
2324{
2325 return unset_local_var_len(name, strlen(name));
2326}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002327#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002328
2329static void unset_vars(char **strings)
2330{
2331 char **v;
2332
2333 if (!strings)
2334 return;
2335 v = strings;
2336 while (*v) {
2337 const char *eq = strchrnul(*v, '=');
2338 unset_local_var_len(*v, (int)(eq - *v));
2339 v++;
2340 }
2341 free(strings);
2342}
2343
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002344#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
Denys Vlasenko03dad222010-01-12 23:29:57 +01002345static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002346{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002347 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002348 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002349}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002350#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002351
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002352
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002353/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002354 * Helpers for "var1=val1 var2=val2 cmd" feature
2355 */
2356static void add_vars(struct variable *var)
2357{
2358 struct variable *next;
2359
2360 while (var) {
2361 next = var->next;
2362 var->next = G.top_var;
2363 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002364 if (var->flg_export) {
2365 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002366 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002367 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002368 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002369 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002370 var = next;
2371 }
2372}
2373
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002374static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002375{
2376 char **s;
2377 struct variable *old = NULL;
2378
2379 if (!strings)
2380 return old;
2381 s = strings;
2382 while (*s) {
2383 struct variable *var_p;
2384 struct variable **var_pp;
2385 char *eq;
2386
2387 eq = strchr(*s, '=');
2388 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002389 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002390 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002391 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002392 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002393 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002394 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002395 /*
2396 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2397 * If VAR is readonly, leaving it in the list
2398 * after asssignment error (msg above)
2399 * causes doubled error message later, on unset.
2400 */
2401 debug_printf_env("removing/freeing '%s' element\n", *s);
2402 free(*s);
2403 p = s;
2404 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002405 goto next;
2406 }
2407 /* Remove variable from global linked list */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002408 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002409 *var_pp = var_p->next;
2410 /* Add it to returned list */
2411 var_p->next = old;
2412 old = var_p;
2413 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002414 set_local_var(*s, SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002415 }
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002416 next:
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002417 s++;
2418 }
2419 return old;
2420}
2421
2422
2423/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002424 * Unicode helper
2425 */
2426static void reinit_unicode_for_hush(void)
2427{
2428 /* Unicode support should be activated even if LANG is set
2429 * _during_ shell execution, not only if it was set when
2430 * shell was started. Therefore, re-check LANG every time:
2431 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002432 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2433 || ENABLE_UNICODE_USING_LOCALE
2434 ) {
2435 const char *s = get_local_var_value("LC_ALL");
2436 if (!s) s = get_local_var_value("LC_CTYPE");
2437 if (!s) s = get_local_var_value("LANG");
2438 reinit_unicode(s);
2439 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002440}
2441
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002442/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002443 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002444 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002445
2446#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002447/* To test correct lineedit/interactive behavior, type from command line:
2448 * echo $P\
2449 * \
2450 * AT\
2451 * H\
2452 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002453 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002454 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002455static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002456{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002457 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002458 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002459 if (G.PS1 == NULL)
2460 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002461 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002462 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002463 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002464 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002465 if (G.PS2 == NULL)
2466 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002467}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002468static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002469{
2470 const char *prompt_str;
2471 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002472 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2473 /* Set up the prompt */
2474 if (promptmode == 0) { /* PS1 */
2475 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002476 /* bash uses $PWD value, even if it is set by user.
2477 * It uses current dir only if PWD is unset.
2478 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002479 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002480 prompt_str = G.PS1;
2481 } else
2482 prompt_str = G.PS2;
2483 } else
2484 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002485 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002486 return prompt_str;
2487}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002488static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002489{
2490 int r;
2491 const char *prompt_str;
2492
2493 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002494# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002495 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002496 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002497 if (G.flag_SIGINT) {
2498 /* There was ^C'ed, make it look prettier: */
2499 bb_putchar('\n');
2500 G.flag_SIGINT = 0;
2501 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002502 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002503 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002504 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002505 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002506 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002507 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002508 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002509 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002510 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002511 if (r != 0 && !G.flag_SIGINT)
2512 break;
2513 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002514 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2515 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002516 G.last_exitcode = 128 + SIGINT;
2517 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002518 if (r < 0) {
2519 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002520 i->p = NULL;
2521 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002522 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002523 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002524 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002525 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002526# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002527 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002528 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002529 if (i->last_char == '\0' || i->last_char == '\n') {
2530 /* Why check_and_run_traps here? Try this interactively:
2531 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2532 * $ <[enter], repeatedly...>
2533 * Without check_and_run_traps, handler never runs.
2534 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002535 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002536 fputs(prompt_str, stdout);
2537 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002538 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002539//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002540 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002541 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2542 * no ^C masking happens during fgetc, no special code for ^C:
2543 * it generates SIGINT as usual.
2544 */
2545 check_and_run_traps();
2546 if (G.flag_SIGINT)
2547 G.last_exitcode = 128 + SIGINT;
2548 if (r != '\0')
2549 break;
2550 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002551 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002552# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002553}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002554/* This is the magic location that prints prompts
2555 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002556static int fgetc_interactive(struct in_str *i)
2557{
2558 int ch;
2559 /* If it's interactive stdin, get new line. */
2560 if (G_interactive_fd && i->file == stdin) {
2561 /* Returns first char (or EOF), the rest is in i->p[] */
2562 ch = get_user_input(i);
2563 i->promptmode = 1; /* PS2 */
2564 } else {
2565 /* Not stdin: script file, sourced file, etc */
2566 do ch = fgetc(i->file); while (ch == '\0');
2567 }
2568 return ch;
2569}
2570#else
2571static inline int fgetc_interactive(struct in_str *i)
2572{
2573 int ch;
2574 do ch = fgetc(i->file); while (ch == '\0');
2575 return ch;
2576}
2577#endif /* INTERACTIVE */
2578
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002579static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002580{
2581 int ch;
2582
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002583 if (!i->file) {
2584 /* string-based in_str */
2585 ch = (unsigned char)*i->p;
2586 if (ch != '\0') {
2587 i->p++;
2588 i->last_char = ch;
2589 return ch;
2590 }
2591 return EOF;
2592 }
2593
2594 /* FILE-based in_str */
2595
Denys Vlasenko4074d492016-09-30 01:49:53 +02002596#if ENABLE_FEATURE_EDITING
2597 /* This can be stdin, check line editing char[] buffer */
2598 if (i->p && *i->p != '\0') {
2599 ch = (unsigned char)*i->p++;
2600 goto out;
2601 }
2602#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002603 /* peek_buf[] is an int array, not char. Can contain EOF. */
2604 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002605 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002606 int ch2 = i->peek_buf[1];
2607 i->peek_buf[0] = ch2;
2608 if (ch2 == 0) /* very likely, avoid redundant write */
2609 goto out;
2610 i->peek_buf[1] = 0;
2611 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002612 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002613
Denys Vlasenko4074d492016-09-30 01:49:53 +02002614 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002615 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002616 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002617 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002618#if ENABLE_HUSH_LINENO_VAR
2619 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002620 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002621 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2622 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002623#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002624 return ch;
2625}
2626
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002627static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002628{
2629 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002630
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002631 if (!i->file) {
2632 /* string-based in_str */
2633 /* Doesn't report EOF on NUL. None of the callers care. */
2634 return (unsigned char)*i->p;
2635 }
2636
2637 /* FILE-based in_str */
2638
Denys Vlasenko4074d492016-09-30 01:49:53 +02002639#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002640 /* This can be stdin, check line editing char[] buffer */
2641 if (i->p && *i->p != '\0')
2642 return (unsigned char)*i->p;
2643#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002644 /* peek_buf[] is an int array, not char. Can contain EOF. */
2645 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002646 if (ch != 0)
2647 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002648
Denys Vlasenko4074d492016-09-30 01:49:53 +02002649 /* Need to get a new char */
2650 ch = fgetc_interactive(i);
2651 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2652
2653 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2654#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2655 if (i->p) {
2656 i->p -= 1;
2657 return ch;
2658 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002659#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002660 i->peek_buf[0] = ch;
2661 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002662 return ch;
2663}
2664
Denys Vlasenko4074d492016-09-30 01:49:53 +02002665/* Only ever called if i_peek() was called, and did not return EOF.
2666 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2667 * not end-of-line. Therefore we never need to read a new editing line here.
2668 */
2669static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002670{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002671 int ch;
2672
2673 /* There are two cases when i->p[] buffer exists.
2674 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002675 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002676 * In both cases, we know that i->p[0] exists and not NUL, and
2677 * the peek2 result is in i->p[1].
2678 */
2679 if (i->p)
2680 return (unsigned char)i->p[1];
2681
2682 /* Now we know it is a file-based in_str. */
2683
2684 /* peek_buf[] is an int array, not char. Can contain EOF. */
2685 /* Is there 2nd char? */
2686 ch = i->peek_buf[1];
2687 if (ch == 0) {
2688 /* We did not read it yet, get it now */
2689 do ch = fgetc(i->file); while (ch == '\0');
2690 i->peek_buf[1] = ch;
2691 }
2692
2693 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2694 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002695}
2696
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02002697static int i_getch_and_eat_bkslash_nl(struct in_str *input)
2698{
2699 for (;;) {
2700 int ch, ch2;
2701
2702 ch = i_getch(input);
2703 if (ch != '\\')
2704 return ch;
2705 ch2 = i_peek(input);
2706 if (ch2 != '\n')
2707 return ch;
2708 /* backslash+newline, skip it */
2709 i_getch(input);
2710 }
2711}
2712
2713/* Note: this function _eats_ \<newline> pairs, safe to use plain
2714 * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
2715 */
2716static int i_peek_and_eat_bkslash_nl(struct in_str *input)
2717{
2718 for (;;) {
2719 int ch, ch2;
2720
2721 ch = i_peek(input);
2722 if (ch != '\\')
2723 return ch;
2724 ch2 = i_peek2(input);
2725 if (ch2 != '\n')
2726 return ch;
2727 /* backslash+newline, skip it */
2728 i_getch(input);
2729 i_getch(input);
2730 }
2731}
2732
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002733static void setup_file_in_str(struct in_str *i, FILE *f)
2734{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002735 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002736 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002737 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002738 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002739}
2740
2741static void setup_string_in_str(struct in_str *i, const char *s)
2742{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002743 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002744 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002745 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002746 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002747}
2748
2749
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002750/*
2751 * o_string support
2752 */
2753#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002754
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002755static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002756{
2757 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002758 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002759 if (o->data)
2760 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002761}
2762
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002763static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002764{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002765 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002766 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002767}
2768
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002769static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2770{
2771 free(o->data);
2772}
2773
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002774static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002775{
2776 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002777 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002778 o->data = xrealloc(o->data, 1 + o->maxlen);
2779 }
2780}
2781
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002782static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002783{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002784 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002785 if (o->length < o->maxlen) {
2786 /* likely. avoid o_grow_by() call */
2787 add:
2788 o->data[o->length] = ch;
2789 o->length++;
2790 o->data[o->length] = '\0';
2791 return;
2792 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002793 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002794 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002795}
2796
Denys Vlasenko657086a2016-09-29 18:07:42 +02002797#if 0
2798/* Valid only if we know o_string is not empty */
2799static void o_delchr(o_string *o)
2800{
2801 o->length--;
2802 o->data[o->length] = '\0';
2803}
2804#endif
2805
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002806static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002807{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002808 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002809 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002810 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002811}
2812
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002813static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002814{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002815 o_addblock(o, str, strlen(str));
2816}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002817
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002818#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002819static void nommu_addchr(o_string *o, int ch)
2820{
2821 if (o)
2822 o_addchr(o, ch);
2823}
2824#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002825# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002826#endif
2827
2828static void o_addstr_with_NUL(o_string *o, const char *str)
2829{
2830 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002831}
2832
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002833/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002834 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002835 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2836 * Apparently, on unquoted $v bash still does globbing
2837 * ("v='*.txt'; echo $v" prints all .txt files),
2838 * but NOT brace expansion! Thus, there should be TWO independent
2839 * quoting mechanisms on $v expansion side: one protects
2840 * $v from brace expansion, and other additionally protects "$v" against globbing.
2841 * We have only second one.
2842 */
2843
Denys Vlasenko9e800222010-10-03 14:28:04 +02002844#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002845# define MAYBE_BRACES "{}"
2846#else
2847# define MAYBE_BRACES ""
2848#endif
2849
Eric Andersen25f27032001-04-26 23:22:31 +00002850/* My analysis of quoting semantics tells me that state information
2851 * is associated with a destination, not a source.
2852 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002853static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002854{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002855 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002856 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002857 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002858 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002859 o_grow_by(o, sz);
2860 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002861 o->data[o->length] = '\\';
2862 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002863 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002864 o->data[o->length] = ch;
2865 o->length++;
2866 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002867}
2868
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002869static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002870{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002871 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002872 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2873 && strchr("*?[\\" MAYBE_BRACES, ch)
2874 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002875 sz++;
2876 o->data[o->length] = '\\';
2877 o->length++;
2878 }
2879 o_grow_by(o, sz);
2880 o->data[o->length] = ch;
2881 o->length++;
2882 o->data[o->length] = '\0';
2883}
2884
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002885static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002886{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002887 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002888 char ch;
2889 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002890 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002891 if (ordinary_cnt > len) /* paranoia */
2892 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002893 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002894 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002895 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002896 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002897 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002898
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002899 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002900 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002901 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002902 sz++;
2903 o->data[o->length] = '\\';
2904 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002905 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002906 o_grow_by(o, sz);
2907 o->data[o->length] = ch;
2908 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002909 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002910 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002911}
2912
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002913static void o_addQblock(o_string *o, const char *str, int len)
2914{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002915 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002916 o_addblock(o, str, len);
2917 return;
2918 }
2919 o_addqblock(o, str, len);
2920}
2921
Denys Vlasenko38292b62010-09-05 14:49:40 +02002922static void o_addQstr(o_string *o, const char *str)
2923{
2924 o_addQblock(o, str, strlen(str));
2925}
2926
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002927/* A special kind of o_string for $VAR and `cmd` expansion.
2928 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002929 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002930 * list[i] contains an INDEX (int!) into this string data.
2931 * It means that if list[] needs to grow, data needs to be moved higher up
2932 * but list[i]'s need not be modified.
2933 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002934 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002935 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2936 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002937#if DEBUG_EXPAND || DEBUG_GLOB
2938static void debug_print_list(const char *prefix, o_string *o, int n)
2939{
2940 char **list = (char**)o->data;
2941 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2942 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002943
2944 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002945 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 +02002946 prefix, list, n, string_start, o->length, o->maxlen,
2947 !!(o->o_expflags & EXP_FLAG_GLOB),
2948 o->has_quoted_part,
2949 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002950 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002951 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002952 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2953 o->data + (int)(uintptr_t)list[i] + string_start,
2954 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002955 i++;
2956 }
2957 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002958 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002959 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002960 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002961 }
2962}
2963#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002964# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002965#endif
2966
2967/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2968 * in list[n] so that it points past last stored byte so far.
2969 * It returns n+1. */
2970static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002971{
2972 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002973 int string_start;
2974 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002975
2976 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002977 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2978 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002979 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002980 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002981 /* list[n] points to string_start, make space for 16 more pointers */
2982 o->maxlen += 0x10 * sizeof(list[0]);
2983 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002984 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002985 memmove(list + n + 0x10, list + n, string_len);
2986 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002987 } else {
2988 debug_printf_list("list[%d]=%d string_start=%d\n",
2989 n, string_len, string_start);
2990 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002991 } else {
2992 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002993 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2994 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002995 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2996 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002997 o->has_empty_slot = 0;
2998 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002999 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003000 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003001 return n + 1;
3002}
3003
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003004/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003005static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003006{
3007 char **list = (char**)o->data;
3008 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3009
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003010 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003011}
3012
Denys Vlasenko9e800222010-10-03 14:28:04 +02003013#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003014/* There in a GNU extension, GLOB_BRACE, but it is not usable:
3015 * first, it processes even {a} (no commas), second,
3016 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01003017 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003018 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003019
3020/* Helper */
3021static int glob_needed(const char *s)
3022{
3023 while (*s) {
3024 if (*s == '\\') {
3025 if (!s[1])
3026 return 0;
3027 s += 2;
3028 continue;
3029 }
3030 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
3031 return 1;
3032 s++;
3033 }
3034 return 0;
3035}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003036/* Return pointer to next closing brace or to comma */
3037static const char *next_brace_sub(const char *cp)
3038{
3039 unsigned depth = 0;
3040 cp++;
3041 while (*cp != '\0') {
3042 if (*cp == '\\') {
3043 if (*++cp == '\0')
3044 break;
3045 cp++;
3046 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003047 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003048 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003049 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003050 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003051 depth++;
3052 }
3053
3054 return *cp != '\0' ? cp : NULL;
3055}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003056/* Recursive brace globber. Note: may garble pattern[]. */
3057static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003058{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003059 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003060 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003061 const char *next;
3062 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003063 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003064 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003065
3066 debug_printf_glob("glob_brace('%s')\n", pattern);
3067
3068 begin = pattern;
3069 while (1) {
3070 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003071 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003072 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003073 /* Find the first sub-pattern and at the same time
3074 * find the rest after the closing brace */
3075 next = next_brace_sub(begin);
3076 if (next == NULL) {
3077 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003078 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003079 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003080 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003081 /* "{abc}" with no commas - illegal
3082 * brace expr, disregard and skip it */
3083 begin = next + 1;
3084 continue;
3085 }
3086 break;
3087 }
3088 if (*begin == '\\' && begin[1] != '\0')
3089 begin++;
3090 begin++;
3091 }
3092 debug_printf_glob("begin:%s\n", begin);
3093 debug_printf_glob("next:%s\n", next);
3094
3095 /* Now find the end of the whole brace expression */
3096 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003097 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003098 rest = next_brace_sub(rest);
3099 if (rest == NULL) {
3100 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003101 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003102 }
3103 debug_printf_glob("rest:%s\n", rest);
3104 }
3105 rest_len = strlen(++rest) + 1;
3106
3107 /* We are sure the brace expression is well-formed */
3108
3109 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003110 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003111
3112 /* We have a brace expression. BEGIN points to the opening {,
3113 * NEXT points past the terminator of the first element, and REST
3114 * points past the final }. We will accumulate result names from
3115 * recursive runs for each brace alternative in the buffer using
3116 * GLOB_APPEND. */
3117
3118 p = begin + 1;
3119 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003120 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003121 memcpy(
3122 mempcpy(
3123 mempcpy(new_pattern_buf,
3124 /* We know the prefix for all sub-patterns */
3125 pattern, begin - pattern),
3126 p, next - p),
3127 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003128
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003129 /* Note: glob_brace() may garble new_pattern_buf[].
3130 * That's why we re-copy prefix every time (1st memcpy above).
3131 */
3132 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003133 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003134 /* We saw the last entry */
3135 break;
3136 }
3137 p = next + 1;
3138 next = next_brace_sub(next);
3139 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003140 free(new_pattern_buf);
3141 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003142
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003143 simple_glob:
3144 {
3145 int gr;
3146 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003147
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003148 memset(&globdata, 0, sizeof(globdata));
3149 gr = glob(pattern, 0, NULL, &globdata);
3150 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3151 if (gr != 0) {
3152 if (gr == GLOB_NOMATCH) {
3153 globfree(&globdata);
3154 /* NB: garbles parameter */
3155 unbackslash(pattern);
3156 o_addstr_with_NUL(o, pattern);
3157 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3158 return o_save_ptr_helper(o, n);
3159 }
3160 if (gr == GLOB_NOSPACE)
3161 bb_error_msg_and_die(bb_msg_memory_exhausted);
3162 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3163 * but we didn't specify it. Paranoia again. */
3164 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3165 }
3166 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3167 char **argv = globdata.gl_pathv;
3168 while (1) {
3169 o_addstr_with_NUL(o, *argv);
3170 n = o_save_ptr_helper(o, n);
3171 argv++;
3172 if (!*argv)
3173 break;
3174 }
3175 }
3176 globfree(&globdata);
3177 }
3178 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003179}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003180/* Performs globbing on last list[],
3181 * saving each result as a new list[].
3182 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003183static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003184{
3185 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003186
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003187 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003188 if (!o->data)
3189 return o_save_ptr_helper(o, n);
3190 pattern = o->data + o_get_last_ptr(o, n);
3191 debug_printf_glob("glob pattern '%s'\n", pattern);
3192 if (!glob_needed(pattern)) {
3193 /* unbackslash last string in o in place, fix length */
3194 o->length = unbackslash(pattern) - o->data;
3195 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3196 return o_save_ptr_helper(o, n);
3197 }
3198
3199 copy = xstrdup(pattern);
3200 /* "forget" pattern in o */
3201 o->length = pattern - o->data;
3202 n = glob_brace(copy, o, n);
3203 free(copy);
3204 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003205 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003206 return n;
3207}
3208
Denys Vlasenko238081f2010-10-03 14:26:26 +02003209#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003210
3211/* Helper */
3212static int glob_needed(const char *s)
3213{
3214 while (*s) {
3215 if (*s == '\\') {
3216 if (!s[1])
3217 return 0;
3218 s += 2;
3219 continue;
3220 }
3221 if (*s == '*' || *s == '[' || *s == '?')
3222 return 1;
3223 s++;
3224 }
3225 return 0;
3226}
3227/* Performs globbing on last list[],
3228 * saving each result as a new list[].
3229 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003230static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003231{
3232 glob_t globdata;
3233 int gr;
3234 char *pattern;
3235
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003236 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003237 if (!o->data)
3238 return o_save_ptr_helper(o, n);
3239 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003240 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003241 if (!glob_needed(pattern)) {
3242 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003243 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003244 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003245 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003246 return o_save_ptr_helper(o, n);
3247 }
3248
3249 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003250 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3251 * If we glob "*.\*" and don't find anything, we need
3252 * to fall back to using literal "*.*", but GLOB_NOCHECK
3253 * will return "*.\*"!
3254 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003255 gr = glob(pattern, 0, NULL, &globdata);
3256 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003257 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003258 if (gr == GLOB_NOMATCH) {
3259 globfree(&globdata);
3260 goto literal;
3261 }
3262 if (gr == GLOB_NOSPACE)
3263 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003264 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3265 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003266 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003267 }
3268 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3269 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003270 /* "forget" pattern in o */
3271 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003272 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003273 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003274 n = o_save_ptr_helper(o, n);
3275 argv++;
3276 if (!*argv)
3277 break;
3278 }
3279 }
3280 globfree(&globdata);
3281 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003282 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003283 return n;
3284}
3285
Denys Vlasenko238081f2010-10-03 14:26:26 +02003286#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003287
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003288/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003289 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003290static int o_save_ptr(o_string *o, int n)
3291{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003292 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003293 /* If o->has_empty_slot, list[n] was already globbed
3294 * (if it was requested back then when it was filled)
3295 * so don't do that again! */
3296 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003297 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003298 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003299 return o_save_ptr_helper(o, n);
3300}
3301
3302/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003303static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003304{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003305 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003306 int string_start;
3307
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003308 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3309 if (DEBUG_EXPAND)
3310 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003311 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003312 list = (char**)o->data;
3313 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3314 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003315 while (n) {
3316 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003317 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003318 }
3319 return list;
3320}
3321
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003322static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003323
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003324/* Returns pi->next - next pipe in the list */
3325static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003326{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003327 struct pipe *next;
3328 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003329
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003330 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003331 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003332 struct command *command;
3333 struct redir_struct *r, *rnext;
3334
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003335 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003336 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003337 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003338 if (DEBUG_CLEAN) {
3339 int a;
3340 char **p;
3341 for (a = 0, p = command->argv; *p; a++, p++) {
3342 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3343 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003344 }
3345 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003346 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003347 }
3348 /* not "else if": on syntax error, we may have both! */
3349 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003350 debug_printf_clean(" begin group (cmd_type:%d)\n",
3351 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003352 free_pipe_list(command->group);
3353 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003354 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003355 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003356 /* else is crucial here.
3357 * If group != NULL, child_func is meaningless */
3358#if ENABLE_HUSH_FUNCTIONS
3359 else if (command->child_func) {
3360 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3361 command->child_func->parent_cmd = NULL;
3362 }
3363#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003364#if !BB_MMU
3365 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003366 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003367#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003368 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003369 debug_printf_clean(" redirect %d%s",
3370 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003371 /* guard against the case >$FOO, where foo is unset or blank */
3372 if (r->rd_filename) {
3373 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3374 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003375 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003376 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003377 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003378 rnext = r->next;
3379 free(r);
3380 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003381 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003382 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003383 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003384 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003385#if ENABLE_HUSH_JOB
3386 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003387 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003388#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003389
3390 next = pi->next;
3391 free(pi);
3392 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003393}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003394
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003395static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003396{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003397 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003398#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003399 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003400#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003401 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003402 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003403 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003404}
3405
3406
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003407/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003408
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003409#ifndef debug_print_tree
3410static void debug_print_tree(struct pipe *pi, int lvl)
3411{
3412 static const char *const PIPE[] = {
3413 [PIPE_SEQ] = "SEQ",
3414 [PIPE_AND] = "AND",
3415 [PIPE_OR ] = "OR" ,
3416 [PIPE_BG ] = "BG" ,
3417 };
3418 static const char *RES[] = {
3419 [RES_NONE ] = "NONE" ,
3420# if ENABLE_HUSH_IF
3421 [RES_IF ] = "IF" ,
3422 [RES_THEN ] = "THEN" ,
3423 [RES_ELIF ] = "ELIF" ,
3424 [RES_ELSE ] = "ELSE" ,
3425 [RES_FI ] = "FI" ,
3426# endif
3427# if ENABLE_HUSH_LOOPS
3428 [RES_FOR ] = "FOR" ,
3429 [RES_WHILE] = "WHILE",
3430 [RES_UNTIL] = "UNTIL",
3431 [RES_DO ] = "DO" ,
3432 [RES_DONE ] = "DONE" ,
3433# endif
3434# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3435 [RES_IN ] = "IN" ,
3436# endif
3437# if ENABLE_HUSH_CASE
3438 [RES_CASE ] = "CASE" ,
3439 [RES_CASE_IN ] = "CASE_IN" ,
3440 [RES_MATCH] = "MATCH",
3441 [RES_CASE_BODY] = "CASE_BODY",
3442 [RES_ESAC ] = "ESAC" ,
3443# endif
3444 [RES_XXXX ] = "XXXX" ,
3445 [RES_SNTX ] = "SNTX" ,
3446 };
3447 static const char *const CMDTYPE[] = {
3448 "{}",
3449 "()",
3450 "[noglob]",
3451# if ENABLE_HUSH_FUNCTIONS
3452 "func()",
3453# endif
3454 };
3455
3456 int pin, prn;
3457
3458 pin = 0;
3459 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003460 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3461 lvl*2, "",
3462 pin,
3463 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3464 RES[pi->res_word],
3465 pi->followup, PIPE[pi->followup]
3466 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003467 prn = 0;
3468 while (prn < pi->num_cmds) {
3469 struct command *command = &pi->cmds[prn];
3470 char **argv = command->argv;
3471
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003472 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003473 lvl*2, "", prn,
3474 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003475#if ENABLE_HUSH_LINENO_VAR
3476 fdprintf(2, " LINENO:%u", command->lineno);
3477#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003478 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003479 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003480 CMDTYPE[command->cmd_type],
3481 argv
3482# if !BB_MMU
3483 , " group_as_string:", command->group_as_string
3484# else
3485 , "", ""
3486# endif
3487 );
3488 debug_print_tree(command->group, lvl+1);
3489 prn++;
3490 continue;
3491 }
3492 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003493 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003494 argv++;
3495 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003496 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003497 prn++;
3498 }
3499 pi = pi->next;
3500 pin++;
3501 }
3502}
3503#endif /* debug_print_tree */
3504
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003505static struct pipe *new_pipe(void)
3506{
Eric Andersen25f27032001-04-26 23:22:31 +00003507 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003508 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003509 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003510 return pi;
3511}
3512
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003513/* Command (member of a pipe) is complete, or we start a new pipe
3514 * if ctx->command is NULL.
3515 * No errors possible here.
3516 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003517static int done_command(struct parse_context *ctx)
3518{
3519 /* The command is really already in the pipe structure, so
3520 * advance the pipe counter and make a new, null command. */
3521 struct pipe *pi = ctx->pipe;
3522 struct command *command = ctx->command;
3523
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003524#if 0 /* Instead we emit error message at run time */
3525 if (ctx->pending_redirect) {
3526 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003527 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003528 ctx->pending_redirect = NULL;
3529 }
3530#endif
3531
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003532 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003533 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003534 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003535 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003536 }
3537 pi->num_cmds++;
3538 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003539 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003540 } else {
3541 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3542 }
3543
3544 /* Only real trickiness here is that the uncommitted
3545 * command structure is not counted in pi->num_cmds. */
3546 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003547 ctx->command = command = &pi->cmds[pi->num_cmds];
3548 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003549 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003550#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003551 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003552 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003553#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003554 return pi->num_cmds; /* used only for 0/nonzero check */
3555}
3556
3557static void done_pipe(struct parse_context *ctx, pipe_style type)
3558{
3559 int not_null;
3560
3561 debug_printf_parse("done_pipe entered, followup %d\n", type);
3562 /* Close previous command */
3563 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003564#if HAS_KEYWORDS
3565 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3566 ctx->ctx_inverted = 0;
3567 ctx->pipe->res_word = ctx->ctx_res_w;
3568#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003569 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3570 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003571 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3572 * in a backgrounded subshell.
3573 */
3574 struct pipe *pi;
3575 struct command *command;
3576
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003577 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003578 pi = ctx->list_head;
3579 while (pi != ctx->pipe) {
3580 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3581 goto no_conv;
3582 pi = pi->next;
3583 }
3584
3585 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3586 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3587 pi = xzalloc(sizeof(*pi));
3588 pi->followup = PIPE_BG;
3589 pi->num_cmds = 1;
3590 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3591 command = &pi->cmds[0];
3592 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3593 command->cmd_type = CMD_NORMAL;
3594 command->group = ctx->list_head;
3595#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003596 command->group_as_string = xstrndup(
3597 ctx->as_string.data,
3598 ctx->as_string.length - 1 /* do not copy last char, "&" */
3599 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003600#endif
3601 /* Replace all pipes in ctx with one newly created */
3602 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003603 } else {
3604 no_conv:
3605 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003606 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003607
3608 /* Without this check, even just <enter> on command line generates
3609 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003610 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003611 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003612#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003613 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003614#endif
3615#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003616 || ctx->ctx_res_w == RES_DONE
3617 || ctx->ctx_res_w == RES_FOR
3618 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003619#endif
3620#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003621 || ctx->ctx_res_w == RES_ESAC
3622#endif
3623 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003624 struct pipe *new_p;
3625 debug_printf_parse("done_pipe: adding new pipe: "
3626 "not_null:%d ctx->ctx_res_w:%d\n",
3627 not_null, ctx->ctx_res_w);
3628 new_p = new_pipe();
3629 ctx->pipe->next = new_p;
3630 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003631 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003632 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003633 * This is used to control execution.
3634 * RES_FOR and RES_IN are NOT sticky (needed to support
3635 * cases where variable or value happens to match a keyword):
3636 */
3637#if ENABLE_HUSH_LOOPS
3638 if (ctx->ctx_res_w == RES_FOR
3639 || ctx->ctx_res_w == RES_IN)
3640 ctx->ctx_res_w = RES_NONE;
3641#endif
3642#if ENABLE_HUSH_CASE
3643 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003644 ctx->ctx_res_w = RES_CASE_BODY;
3645 if (ctx->ctx_res_w == RES_CASE)
3646 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003647#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003648 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003649 /* Create the memory for command, roughly:
3650 * ctx->pipe->cmds = new struct command;
3651 * ctx->command = &ctx->pipe->cmds[0];
3652 */
3653 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003654 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003655 }
3656 debug_printf_parse("done_pipe return\n");
3657}
3658
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003659static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003660{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003661 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003662 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003663 /* Create the memory for command, roughly:
3664 * ctx->pipe->cmds = new struct command;
3665 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003666 */
3667 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003668}
3669
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003670/* If a reserved word is found and processed, parse context is modified
3671 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003672 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003673#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003674struct reserved_combo {
3675 char literal[6];
3676 unsigned char res;
3677 unsigned char assignment_flag;
3678 int flag;
3679};
3680enum {
3681 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003682# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003683 FLAG_IF = (1 << RES_IF ),
3684 FLAG_THEN = (1 << RES_THEN ),
3685 FLAG_ELIF = (1 << RES_ELIF ),
3686 FLAG_ELSE = (1 << RES_ELSE ),
3687 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003688# endif
3689# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003690 FLAG_FOR = (1 << RES_FOR ),
3691 FLAG_WHILE = (1 << RES_WHILE),
3692 FLAG_UNTIL = (1 << RES_UNTIL),
3693 FLAG_DO = (1 << RES_DO ),
3694 FLAG_DONE = (1 << RES_DONE ),
3695 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003696# endif
3697# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003698 FLAG_MATCH = (1 << RES_MATCH),
3699 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003700# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003701 FLAG_START = (1 << RES_XXXX ),
3702};
3703
3704static const struct reserved_combo* match_reserved_word(o_string *word)
3705{
Eric Andersen25f27032001-04-26 23:22:31 +00003706 /* Mostly a list of accepted follow-up reserved words.
3707 * FLAG_END means we are done with the sequence, and are ready
3708 * to turn the compound list into a command.
3709 * FLAG_START means the word must start a new compound list.
3710 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003711 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003712# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003713 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3714 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3715 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3716 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3717 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3718 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003719# endif
3720# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003721 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3722 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3723 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3724 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3725 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3726 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003727# endif
3728# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003729 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3730 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003731# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003732 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003733 const struct reserved_combo *r;
3734
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003735 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003736 if (strcmp(word->data, r->literal) == 0)
3737 return r;
3738 }
3739 return NULL;
3740}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003741/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003742 */
Denys Vlasenko5807e182018-02-08 19:19:04 +01003743static const struct reserved_combo* reserved_word(o_string *word, struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003744{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003745# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003746 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003747 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003748 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003749# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003750 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003751
Denys Vlasenko38292b62010-09-05 14:49:40 +02003752 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003753 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003754 r = match_reserved_word(word);
3755 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003756 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003757
3758 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003759# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003760 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3761 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003762 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003763 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003764# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003765 if (r->flag == 0) { /* '!' */
3766 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003767 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003768 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003769 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003770 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003771 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003772 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003773 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003774 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003775
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003776 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003777 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003778 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003779 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003780 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003781 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003782 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003783 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003784 } else {
3785 /* "{...} fi" is ok. "{...} if" is not
3786 * Example:
3787 * if { echo foo; } then { echo bar; } fi */
3788 if (ctx->command->group)
3789 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003790 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003791
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003792 ctx->ctx_res_w = r->res;
3793 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003794 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003795 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003796
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003797 if (ctx->old_flag & FLAG_END) {
3798 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003799
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003800 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003801 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003802 old = ctx->stack;
3803 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003804 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003805# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003806 /* At this point, the compound command's string is in
3807 * ctx->as_string... except for the leading keyword!
3808 * Consider this example: "echo a | if true; then echo a; fi"
3809 * ctx->as_string will contain "true; then echo a; fi",
3810 * with "if " remaining in old->as_string!
3811 */
3812 {
3813 char *str;
3814 int len = old->as_string.length;
3815 /* Concatenate halves */
3816 o_addstr(&old->as_string, ctx->as_string.data);
3817 o_free_unsafe(&ctx->as_string);
3818 /* Find where leading keyword starts in first half */
3819 str = old->as_string.data + len;
3820 if (str > old->as_string.data)
3821 str--; /* skip whitespace after keyword */
3822 while (str > old->as_string.data && isalpha(str[-1]))
3823 str--;
3824 /* Ugh, we're done with this horrid hack */
3825 old->command->group_as_string = xstrdup(str);
3826 debug_printf_parse("pop, remembering as:'%s'\n",
3827 old->command->group_as_string);
3828 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003829# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003830 *ctx = *old; /* physical copy */
3831 free(old);
3832 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003833 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003834}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003835#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003836
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003837/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003838 * Normal return is 0. Syntax errors return 1.
3839 * Note: on return, word is reset, but not o_free'd!
3840 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003841static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003842{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003843 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003844
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003845 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003846 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003847 debug_printf_parse("done_word return 0: true null, ignored\n");
3848 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003849 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003850
Eric Andersen25f27032001-04-26 23:22:31 +00003851 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003852 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3853 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003854 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3855 * "2.7 Redirection
3856 * ...the word that follows the redirection operator
3857 * shall be subjected to tilde expansion, parameter expansion,
3858 * command substitution, arithmetic expansion, and quote
3859 * removal. Pathname expansion shall not be performed
3860 * on the word by a non-interactive shell; an interactive
3861 * shell may perform it, but shall do so only when
3862 * the expansion would result in one word."
3863 */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02003864//bash does not do parameter/command substitution or arithmetic expansion
3865//for _heredoc_ redirection word: these constructs look for exact eof marker
3866// as written:
3867// <<EOF$t
3868// <<EOF$((1))
3869// <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF"]
3870//This contradicts the above docs.
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003871 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003872 /* Cater for >\file case:
3873 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3874 * Same with heredocs:
3875 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3876 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003877 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3878 unbackslash(ctx->pending_redirect->rd_filename);
3879 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003880 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003881 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3882 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003883 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003884 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003885 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003886 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003887#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003888# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003889 if (ctx->ctx_dsemicolon
3890 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3891 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003892 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003893 /* ctx->ctx_res_w = RES_MATCH; */
3894 ctx->ctx_dsemicolon = 0;
3895 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003896# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003897 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003898# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003899 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3900 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003901# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003902# if ENABLE_HUSH_CASE
3903 && ctx->ctx_res_w != RES_CASE
3904# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003905 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003906 const struct reserved_combo *reserved;
3907 reserved = reserved_word(word, ctx);
3908 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003909 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003910# if ENABLE_HUSH_LINENO_VAR
3911/* Case:
3912 * "while ...; do
3913 * cmd ..."
3914 * If we don't close the pipe _now_, immediately after "do", lineno logic
3915 * sees "cmd" as starting at "do" - i.e., at the previous line.
3916 */
3917 if (0
3918 IF_HUSH_IF(|| reserved->res == RES_THEN)
3919 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3920 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3921 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3922 ) {
3923 done_pipe(ctx, PIPE_SEQ);
3924 }
3925# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003926 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003927 debug_printf_parse("done_word return %d\n",
3928 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003929 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003930 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01003931# if BASH_TEST2
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003932 if (strcmp(word->data, "[[") == 0) {
3933 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3934 }
3935 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003936# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003937 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003938#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003939 if (command->group) {
3940 /* "{ echo foo; } echo bar" - bad */
3941 syntax_error_at(word->data);
3942 debug_printf_parse("done_word return 1: syntax error, "
3943 "groups and arglists don't mix\n");
3944 return 1;
3945 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003946
3947 /* If this word wasn't an assignment, next ones definitely
3948 * can't be assignments. Even if they look like ones. */
3949 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3950 && word->o_assignment != WORD_IS_KEYWORD
3951 ) {
3952 word->o_assignment = NOT_ASSIGNMENT;
3953 } else {
3954 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3955 command->assignment_cnt++;
3956 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3957 }
3958 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3959 word->o_assignment = MAYBE_ASSIGNMENT;
3960 }
3961 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003962 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003963 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003964 }
Eric Andersen25f27032001-04-26 23:22:31 +00003965
Denis Vlasenko06810332007-05-21 23:30:54 +00003966#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003967 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003968 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003969 || !is_well_formed_var_name(command->argv[0], '\0')
3970 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003971 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003972 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003973 return 1;
3974 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003975 /* Force FOR to have just one word (variable name) */
3976 /* NB: basically, this makes hush see "for v in ..."
3977 * syntax as if it is "for v; in ...". FOR and IN become
3978 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003979 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003980 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003981#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003982#if ENABLE_HUSH_CASE
3983 /* Force CASE to have just one word */
3984 if (ctx->ctx_res_w == RES_CASE) {
3985 done_pipe(ctx, PIPE_SEQ);
3986 }
3987#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003988
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003989 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003990
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003991 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003992 return 0;
3993}
3994
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003995
3996/* Peek ahead in the input to find out if we have a "&n" construct,
3997 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003998 * Return:
3999 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4000 * REDIRFD_SYNTAX_ERR if syntax error,
4001 * REDIRFD_TO_FILE if no & was seen,
4002 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004003 */
4004#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004005#define parse_redir_right_fd(as_string, input) \
4006 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004007#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004008static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004009{
4010 int ch, d, ok;
4011
4012 ch = i_peek(input);
4013 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004014 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004015
4016 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004017 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004018 ch = i_peek(input);
4019 if (ch == '-') {
4020 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004021 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004022 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004023 }
4024 d = 0;
4025 ok = 0;
4026 while (ch != EOF && isdigit(ch)) {
4027 d = d*10 + (ch-'0');
4028 ok = 1;
4029 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004030 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004031 ch = i_peek(input);
4032 }
4033 if (ok) return d;
4034
4035//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4036
4037 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004038 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004039}
4040
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004041/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004042 */
4043static int parse_redirect(struct parse_context *ctx,
4044 int fd,
4045 redir_type style,
4046 struct in_str *input)
4047{
4048 struct command *command = ctx->command;
4049 struct redir_struct *redir;
4050 struct redir_struct **redirp;
4051 int dup_num;
4052
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004053 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004054 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004055 /* Check for a '>&1' type redirect */
4056 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4057 if (dup_num == REDIRFD_SYNTAX_ERR)
4058 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004059 } else {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004060 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004061 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004062 if (dup_num) { /* <<-... */
4063 ch = i_getch(input);
4064 nommu_addchr(&ctx->as_string, ch);
4065 ch = i_peek(input);
4066 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004067 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004068
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004069 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02004070 int ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004071 if (ch == '|') {
4072 /* >|FILE redirect ("clobbering" >).
4073 * Since we do not support "set -o noclobber" yet,
4074 * >| and > are the same for now. Just eat |.
4075 */
4076 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004077 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004078 }
4079 }
4080
4081 /* Create a new redir_struct and append it to the linked list */
4082 redirp = &command->redirects;
4083 while ((redir = *redirp) != NULL) {
4084 redirp = &(redir->next);
4085 }
4086 *redirp = redir = xzalloc(sizeof(*redir));
4087 /* redir->next = NULL; */
4088 /* redir->rd_filename = NULL; */
4089 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004090 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004091
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004092 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4093 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004094
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004095 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004096 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004097 /* Erik had a check here that the file descriptor in question
4098 * is legit; I postpone that to "run time"
4099 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004100 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4101 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004102 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004103#if 0 /* Instead we emit error message at run time */
4104 if (ctx->pending_redirect) {
4105 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004106 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004107 }
4108#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004109 /* Set ctx->pending_redirect, so we know what to do at the
4110 * end of the next parsed word. */
4111 ctx->pending_redirect = redir;
4112 }
4113 return 0;
4114}
4115
Eric Andersen25f27032001-04-26 23:22:31 +00004116/* If a redirect is immediately preceded by a number, that number is
4117 * supposed to tell which file descriptor to redirect. This routine
4118 * looks for such preceding numbers. In an ideal world this routine
4119 * needs to handle all the following classes of redirects...
4120 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4121 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4122 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4123 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004124 *
4125 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4126 * "2.7 Redirection
4127 * ... If n is quoted, the number shall not be recognized as part of
4128 * the redirection expression. For example:
4129 * echo \2>a
4130 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004131 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004132 *
4133 * A -1 return means no valid number was found,
4134 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004135 */
4136static int redirect_opt_num(o_string *o)
4137{
4138 int num;
4139
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004140 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004141 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004142 num = bb_strtou(o->data, NULL, 10);
4143 if (errno || num < 0)
4144 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004145 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004146 return num;
4147}
4148
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004149#if BB_MMU
4150#define fetch_till_str(as_string, input, word, skip_tabs) \
4151 fetch_till_str(input, word, skip_tabs)
4152#endif
4153static char *fetch_till_str(o_string *as_string,
4154 struct in_str *input,
4155 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004156 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004157{
4158 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004159 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004160 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004161 int ch;
4162
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004163 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004164
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004165 while (1) {
4166 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004167 if (ch != EOF)
4168 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004169 if (ch == '\n' || ch == EOF) {
4170 check_heredoc_end:
4171 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4172 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4173 heredoc.data[past_EOL] = '\0';
4174 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4175 return heredoc.data;
4176 }
4177 if (ch == '\n') {
4178 /* This is a new line.
4179 * Remember position and backslash-escaping status.
4180 */
4181 o_addchr(&heredoc, ch);
4182 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004183 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004184 past_EOL = heredoc.length;
4185 /* Get 1st char of next line, possibly skipping leading tabs */
4186 do {
4187 ch = i_getch(input);
4188 if (ch != EOF)
4189 nommu_addchr(as_string, ch);
4190 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4191 /* If this immediately ended the line,
4192 * go back to end-of-line checks.
4193 */
4194 if (ch == '\n')
4195 goto check_heredoc_end;
4196 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004197 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004198 }
4199 if (ch == EOF) {
4200 o_free_unsafe(&heredoc);
4201 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004202 }
4203 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004204 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004205 if (prev == '\\' && ch == '\\')
4206 /* Correctly handle foo\\<eol> (not a line cont.) */
4207 prev = 0; /* not \ */
4208 else
4209 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004210 }
4211}
4212
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004213/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4214 * and load them all. There should be exactly heredoc_cnt of them.
4215 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004216static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4217{
4218 struct pipe *pi = ctx->list_head;
4219
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004220 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004221 int i;
4222 struct command *cmd = pi->cmds;
4223
4224 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4225 pi->num_cmds,
4226 cmd->argv ? cmd->argv[0] : "NONE");
4227 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004228 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004229
4230 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4231 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004232 while (redir) {
4233 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004234 char *p;
4235
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004236 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004237 /* redir->rd_dup is (ab)used to indicate <<- */
Denys Vlasenkobb6f5732018-04-01 18:55:00 +02004238bb_error_msg("redir->rd_filename:'%s'", redir->rd_filename);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004239 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004240 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004241 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004242 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004243 return 1;
4244 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004245 free(redir->rd_filename);
4246 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004247 heredoc_cnt--;
4248 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004249 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004250 }
4251 cmd++;
4252 }
4253 pi = pi->next;
4254 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004255#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004256 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004257 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004258 bb_error_msg_and_die("heredoc BUG 2");
4259#endif
4260 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004261}
4262
4263
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004264static int run_list(struct pipe *pi);
4265#if BB_MMU
4266#define parse_stream(pstring, input, end_trigger) \
4267 parse_stream(input, end_trigger)
4268#endif
4269static struct pipe *parse_stream(char **pstring,
4270 struct in_str *input,
4271 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004272
Eric Andersen25f27032001-04-26 23:22:31 +00004273
Denys Vlasenkoc2704542009-11-20 19:14:19 +01004274#if !ENABLE_HUSH_FUNCTIONS
4275#define parse_group(dest, ctx, input, ch) \
4276 parse_group(ctx, input, ch)
4277#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004278static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004279 struct in_str *input, int ch)
4280{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004281 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004282 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004283 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004284 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004285 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004286 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004287
4288 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004289#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02004290 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004291 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004292 if (done_word(dest, ctx))
4293 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004294 if (!command->argv)
4295 goto skip; /* (... */
4296 if (command->argv[1]) { /* word word ... (... */
4297 syntax_error_unexpected_ch('(');
4298 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004299 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004300 /* it is "word(..." or "word (..." */
4301 do
4302 ch = i_getch(input);
4303 while (ch == ' ' || ch == '\t');
4304 if (ch != ')') {
4305 syntax_error_unexpected_ch(ch);
4306 return 1;
4307 }
4308 nommu_addchr(&ctx->as_string, ch);
4309 do
4310 ch = i_getch(input);
4311 while (ch == ' ' || ch == '\t' || ch == '\n');
4312 if (ch != '{') {
4313 syntax_error_unexpected_ch(ch);
4314 return 1;
4315 }
4316 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004317 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004318 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004319 }
4320#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004321
4322#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004323 if (command->argv /* word [word]{... */
4324 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004325 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004326 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004327 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004328 debug_printf_parse("parse_group return 1: "
4329 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004330 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004331 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004332#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004333
4334#if ENABLE_HUSH_FUNCTIONS
4335 skip:
4336#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004337 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004338 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004339 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004340 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004341 } else {
4342 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004343 ch = i_peek(input);
4344 if (ch != ' ' && ch != '\t' && ch != '\n'
4345 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4346 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004347 syntax_error_unexpected_ch(ch);
4348 return 1;
4349 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004350 if (ch != '(') {
4351 ch = i_getch(input);
4352 nommu_addchr(&ctx->as_string, ch);
4353 }
Eric Andersen25f27032001-04-26 23:22:31 +00004354 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004355
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004356 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004357#if BB_MMU
4358# define as_string NULL
4359#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004360 char *as_string = NULL;
4361#endif
4362 pipe_list = parse_stream(&as_string, input, endch);
4363#if !BB_MMU
4364 if (as_string)
4365 o_addstr(&ctx->as_string, as_string);
4366#endif
4367 /* empty ()/{} or parse error? */
4368 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00004369 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004370 if (!BB_MMU)
4371 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004372 debug_printf_parse("parse_group return 1: "
4373 "parse_stream returned %p\n", pipe_list);
4374 return 1;
4375 }
4376 command->group = pipe_list;
4377#if !BB_MMU
4378 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4379 command->group_as_string = as_string;
4380 debug_printf_parse("end of group, remembering as:'%s'\n",
4381 command->group_as_string);
4382#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004383#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004384 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004385 debug_printf_parse("parse_group return 0\n");
4386 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004387 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004388}
4389
Denys Vlasenko0b883582016-12-23 16:49:07 +01004390#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004391/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004392static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004393/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004394static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004395{
4396 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004397 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004398 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004399 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004400 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004401 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004402 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004403 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004404 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004405 }
4406}
4407/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004408static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004409{
4410 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004411 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004412 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004413 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004414 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004415 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004416 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004417 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004418 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004419 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004420 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004421 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004422 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004423 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004424 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4425 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004426 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004427 continue;
4428 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004429 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004430 }
4431}
4432/* Process `cmd` - copy contents until "`" is seen. Complicated by
4433 * \` quoting.
4434 * "Within the backquoted style of command substitution, backslash
4435 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4436 * The search for the matching backquote shall be satisfied by the first
4437 * backquote found without a preceding backslash; during this search,
4438 * if a non-escaped backquote is encountered within a shell comment,
4439 * a here-document, an embedded command substitution of the $(command)
4440 * form, or a quoted string, undefined results occur. A single-quoted
4441 * or double-quoted string that begins, but does not end, within the
4442 * "`...`" sequence produces undefined results."
4443 * Example Output
4444 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4445 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004446static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004447{
4448 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004449 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004450 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004451 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004452 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004453 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4454 ch = i_getch(input);
4455 if (ch != '`'
4456 && ch != '$'
4457 && ch != '\\'
4458 && (!in_dquote || ch != '"')
4459 ) {
4460 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004461 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004462 }
4463 if (ch == EOF) {
4464 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004465 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004466 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004467 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004468 }
4469}
4470/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4471 * quoting and nested ()s.
4472 * "With the $(command) style of command substitution, all characters
4473 * following the open parenthesis to the matching closing parenthesis
4474 * constitute the command. Any valid shell script can be used for command,
4475 * except a script consisting solely of redirections which produces
4476 * unspecified results."
4477 * Example Output
4478 * echo $(echo '(TEST)' BEST) (TEST) BEST
4479 * echo $(echo 'TEST)' BEST) TEST) BEST
4480 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004481 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004482 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004483 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004484 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4485 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004486 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004487#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004488static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004489{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004490 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004491 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004492# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004493 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004494# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004495 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4496
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004497 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004498 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004499 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004500 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004501 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004502 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004503 if (ch == end_ch
4504# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004505 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004506# endif
4507 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004508 if (!dbl)
4509 break;
4510 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004511 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004512 i_getch(input); /* eat second ')' */
4513 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004514 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004515 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004516 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004517 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004518 if (ch == '(' || ch == '{') {
4519 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004520 if (!add_till_closing_bracket(dest, input, ch))
4521 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004522 o_addchr(dest, ch);
4523 continue;
4524 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004525 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004526 if (!add_till_single_quote(dest, input))
4527 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004528 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004529 continue;
4530 }
4531 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004532 if (!add_till_double_quote(dest, input))
4533 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004534 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004535 continue;
4536 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004537 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004538 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4539 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004540 o_addchr(dest, ch);
4541 continue;
4542 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004543 if (ch == '\\') {
4544 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004545 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004546 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004547 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004548 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004549 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004550#if 0
4551 if (ch == '\n') {
4552 /* "backslash+newline", ignore both */
4553 o_delchr(dest); /* undo insertion of '\' */
4554 continue;
4555 }
4556#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004557 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004558 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004559 continue;
4560 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004561 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004562 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004563}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004564#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004565
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004566/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004567#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004568#define parse_dollar(as_string, dest, input, quote_mask) \
4569 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004570#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004571#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004572static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004573 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004574 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004575{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004576 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004577
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004578 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004579 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004580 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004581 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004582 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004583 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004584 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004585 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004586 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004587 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004588 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004589 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004590 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004591 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004592 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004593 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004594 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004595 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004596 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004597 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004598 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004599 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004600 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004601 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004602 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004603 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004604 o_addchr(dest, ch | quote_mask);
4605 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004606 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004607 case '$': /* pid */
4608 case '!': /* last bg pid */
4609 case '?': /* last exit code */
4610 case '#': /* number of args */
4611 case '*': /* args */
4612 case '@': /* args */
4613 goto make_one_char_var;
4614 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004615 char len_single_ch;
4616
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004617 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4618
Denys Vlasenko74369502010-05-21 19:52:01 +02004619 ch = i_getch(input); /* eat '{' */
4620 nommu_addchr(as_string, ch);
4621
Denys Vlasenko46e64982016-09-29 19:50:55 +02004622 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004623 /* It should be ${?}, or ${#var},
4624 * or even ${?+subst} - operator acting on a special variable,
4625 * or the beginning of variable name.
4626 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004627 if (ch == EOF
4628 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4629 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004630 bad_dollar_syntax:
4631 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004632 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4633 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004634 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004635 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004636 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004637 ch |= quote_mask;
4638
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004639 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004640 * However, this regresses some of our testsuite cases
4641 * which check invalid constructs like ${%}.
4642 * Oh well... let's check that the var name part is fine... */
4643
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004644 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004645 unsigned pos;
4646
Denys Vlasenko74369502010-05-21 19:52:01 +02004647 o_addchr(dest, ch);
4648 debug_printf_parse(": '%c'\n", ch);
4649
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004650 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004651 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004652 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004653 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004654
Denys Vlasenko74369502010-05-21 19:52:01 +02004655 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004656 unsigned end_ch;
4657 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004658 /* handle parameter expansions
4659 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4660 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004661 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4662 if (len_single_ch != '#'
4663 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4664 || i_peek(input) != '}'
4665 ) {
4666 goto bad_dollar_syntax;
4667 }
4668 /* else: it's "length of C" ${#C} op,
4669 * where C is a single char
4670 * special var name, e.g. ${#!}.
4671 */
4672 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004673 /* Eat everything until closing '}' (or ':') */
4674 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004675 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004676 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004677 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004678 ) {
4679 /* It's ${var:N[:M]} thing */
4680 end_ch = '}' * 0x100 + ':';
4681 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004682 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004683 && ch == '/'
4684 ) {
4685 /* It's ${var/[/]pattern[/repl]} thing */
4686 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4687 i_getch(input);
4688 nommu_addchr(as_string, '/');
4689 ch = '\\';
4690 }
4691 end_ch = '}' * 0x100 + '/';
4692 }
4693 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004694 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004695 if (!BB_MMU)
4696 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004697#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004698 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004699 if (last_ch == 0) /* error? */
4700 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004701#else
4702#error Simple code to only allow ${var} is not implemented
4703#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004704 if (as_string) {
4705 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004706 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004707 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004708
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004709 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4710 && (end_ch & 0xff00)
4711 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004712 /* close the first block: */
4713 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004714 /* while parsing N from ${var:N[:M]}
4715 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004716 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004717 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004718 end_ch = '}';
4719 goto again;
4720 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004721 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004722 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004723 /* it's ${var:N} - emulate :999999999 */
4724 o_addstr(dest, "999999999");
4725 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004726 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004727 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004728 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004729 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004730 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004731 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4732 break;
4733 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004734#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004735 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004736 unsigned pos;
4737
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004738 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004739 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004740# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004741 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004742 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004743 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004744 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4745 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004746 if (!BB_MMU)
4747 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004748 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4749 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004750 if (as_string) {
4751 o_addstr(as_string, dest->data + pos);
4752 o_addchr(as_string, ')');
4753 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004754 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004755 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004756 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004757 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004758# endif
4759# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004760 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4761 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004762 if (!BB_MMU)
4763 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004764 if (!add_till_closing_bracket(dest, input, ')'))
4765 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004766 if (as_string) {
4767 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004768 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004769 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004770 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004771# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004772 break;
4773 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004774#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004775 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004776 goto make_var;
4777#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004778 /* TODO: $_ and $-: */
4779 /* $_ Shell or shell script name; or last argument of last command
4780 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4781 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004782 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004783 ch = i_getch(input);
4784 nommu_addchr(as_string, ch);
4785 ch = i_peek_and_eat_bkslash_nl(input);
4786 if (isalnum(ch)) { /* it's $_name or $_123 */
4787 ch = '_';
4788 goto make_var1;
4789 }
4790 /* else: it's $_ */
4791#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004792 default:
4793 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004794 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004795 debug_printf_parse("parse_dollar return 1 (ok)\n");
4796 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004797#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004798}
4799
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004800#if BB_MMU
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004801# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004802#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4803 encode_string(dest, input, dquote_end, process_bkslash)
4804# else
4805/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4806#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4807 encode_string(dest, input, dquote_end)
4808# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004809#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004810
4811#else /* !MMU */
4812
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004813# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004814/* all parameters are needed, no macro tricks */
4815# else
4816#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4817 encode_string(as_string, dest, input, dquote_end)
4818# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004819#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004820static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004821 o_string *dest,
4822 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004823 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004824 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004825{
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004826#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004827 const int process_bkslash = 1;
4828#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004829 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004830 int next;
4831
4832 again:
4833 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004834 if (ch != EOF)
4835 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004836 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004837 debug_printf_parse("encode_string return 1 (ok)\n");
4838 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004839 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004840 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004841 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004842 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004843 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004844 }
4845 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004846 if (ch != '\n') {
4847 next = i_peek(input);
4848 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004849 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004850 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004851 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004852 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004853 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004854 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004855 }
4856 /* bash:
4857 * "The backslash retains its special meaning [in "..."]
4858 * only when followed by one of the following characters:
4859 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004860 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004861 * NB: in (unquoted) heredoc, above does not apply to ",
4862 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004863 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004864 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004865 ch = i_getch(input); /* eat next */
4866 if (ch == '\n')
4867 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004868 } /* else: ch remains == '\\', and we double it below: */
4869 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004870 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004871 goto again;
4872 }
4873 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004874 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4875 debug_printf_parse("encode_string return 0: "
4876 "parse_dollar returned 0 (error)\n");
4877 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004878 }
4879 goto again;
4880 }
4881#if ENABLE_HUSH_TICK
4882 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004883 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004884 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4885 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004886 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4887 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004888 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4889 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004890 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004891 }
4892#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004893 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004894 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004895#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004896}
4897
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004898/*
4899 * Scan input until EOF or end_trigger char.
4900 * Return a list of pipes to execute, or NULL on EOF
4901 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004902 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004903 * reset parsing machinery and start parsing anew,
4904 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004905 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004906static struct pipe *parse_stream(char **pstring,
4907 struct in_str *input,
4908 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004909{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004910 struct parse_context ctx;
4911 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004912 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004913
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004914 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004915 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004916 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004917 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004918 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004919 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004920
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004921 /* If very first arg is "" or '', dest.data may end up NULL.
4922 * Preventing this: */
4923 o_addchr(&dest, '\0');
4924 dest.length = 0;
4925
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004926 /* We used to separate words on $IFS here. This was wrong.
4927 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004928 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004929 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004930
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004931 if (MAYBE_ASSIGNMENT != 0)
4932 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004933 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004934 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004935 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004936 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004937 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004938 int ch;
4939 int next;
4940 int redir_fd;
4941 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004942
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004943 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004944 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004945 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004946 if (ch == EOF) {
4947 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004948
4949 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004950 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004951 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004952 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004953 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004954 syntax_error_unterm_ch('(');
4955 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004956 }
Denys Vlasenko42246472016-11-07 16:22:35 +01004957 if (end_trigger == '}') {
4958 syntax_error_unterm_ch('{');
4959 goto parse_error;
4960 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004961
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004962 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004963 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004964 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004965 o_free(&dest);
4966 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004967 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004968 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004969 /* (this makes bare "&" cmd a no-op.
4970 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004971 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004972 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004973 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004974 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004975 pi = NULL;
4976 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004977#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004978 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004979 if (pstring)
4980 *pstring = ctx.as_string.data;
4981 else
4982 o_free_unsafe(&ctx.as_string);
4983#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004984 debug_leave();
4985 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004986 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004987 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004988 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004989
4990 next = '\0';
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02004991 if (ch != '\n') {
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004992 next = i_peek(input);
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02004993 /* Can't use i_peek_and_eat_bkslash_nl(input) here:
4994 * echo '\
4995 * '
4996 * will break.
4997 */
4998 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004999
5000 is_special = "{}<>;&|()#'" /* special outside of "str" */
Denys Vlasenko932b9972018-01-11 12:39:48 +01005001 "\\$\"" IF_HUSH_TICK("`") /* always special */
5002 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005003 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005004 if (ctx.command->argv /* word [word]{... - non-special */
5005 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005006 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005007 || (next != ';' /* }; - special */
5008 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005009 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005010 && next != '&' /* }& and }&& ... - special */
5011 && next != '|' /* }|| ... - special */
5012 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02005013 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005014 ) {
5015 /* They are not special, skip "{}" */
5016 is_special += 2;
5017 }
5018 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005019 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005020
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005021 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005022 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005023 o_addQchr(&dest, ch);
5024 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5025 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005026 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005027 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005028 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005029 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005030 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005031 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005032 continue;
5033 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005034
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005035 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005036#if ENABLE_HUSH_LINENO_VAR
5037/* Case:
5038 * "while ...; do<whitespace><newline>
5039 * cmd ..."
5040 * would think that "cmd" starts in <whitespace> -
5041 * i.e., at the previous line.
5042 * We need to skip all whitespace before newlines.
5043 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005044 while (ch != '\n') {
5045 next = i_peek(input);
5046 if (next != ' ' && next != '\t' && next != '\n')
5047 break; /* next char is not ws */
5048 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005049 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005050 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005051#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005052 if (done_word(&dest, &ctx)) {
5053 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005054 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005055 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005056 /* Is this a case when newline is simply ignored?
5057 * Some examples:
5058 * "cmd | <newline> cmd ..."
5059 * "case ... in <newline> word) ..."
5060 */
5061 if (IS_NULL_CMD(ctx.command)
5062 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005063 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005064 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005065 * Without check #1, interactive shell
5066 * ignores even bare <newline>,
5067 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005068 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005069 * ps2> _ <=== wrong, should be ps1
5070 * Without check #2, "cmd & <newline>"
5071 * is similarly mistreated.
5072 * (BTW, this makes "cmd & cmd"
5073 * and "cmd && cmd" non-orthogonal.
5074 * Really, ask yourself, why
5075 * "cmd && <newline>" doesn't start
5076 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005077 * The only reason is that it might be
5078 * a "cmd1 && <nl> cmd2 &" construct,
5079 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005080 */
5081 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005082 if (pi->num_cmds != 0 /* check #1 */
5083 && pi->followup != PIPE_BG /* check #2 */
5084 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005085 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005086 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005087 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005088 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005089 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005090 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5091 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005092 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005093 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005094 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005095 heredoc_cnt = 0;
5096 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005097 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005098 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005099 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005100 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005101 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005102 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005103 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005104
5105 /* "cmd}" or "cmd }..." without semicolon or &:
5106 * } is an ordinary char in this case, even inside { cmd; }
5107 * Pathological example: { ""}; } should exec "}" cmd
5108 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005109 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005110 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005111 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005112 ) {
5113 goto ordinary_char;
5114 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005115 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5116 /* Generally, there should be semicolon: "cmd; }"
5117 * However, bash allows to omit it if "cmd" is
5118 * a group. Examples:
5119 * { { echo 1; } }
5120 * {(echo 1)}
5121 * { echo 0 >&2 | { echo 1; } }
5122 * { while false; do :; done }
5123 * { case a in b) ;; esac }
5124 */
5125 if (ctx.command->group)
5126 goto term_group;
5127 goto ordinary_char;
5128 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005129 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005130 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005131 goto skip_end_trigger;
5132 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005133 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005134 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005135 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005136 && (ch != ';' || heredoc_cnt == 0)
5137#if ENABLE_HUSH_CASE
5138 && (ch != ')'
5139 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02005140 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005141 )
5142#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005143 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005144 if (heredoc_cnt) {
5145 /* This is technically valid:
5146 * { cat <<HERE; }; echo Ok
5147 * heredoc
5148 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005149 * HERE
5150 * but we don't support this.
5151 * We require heredoc to be in enclosing {}/(),
5152 * if any.
5153 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005154 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005155 goto parse_error;
5156 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005157 if (done_word(&dest, &ctx)) {
5158 goto parse_error;
5159 }
5160 done_pipe(&ctx, PIPE_SEQ);
5161 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005162 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005163 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005164 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005165 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005166 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005167 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005168#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005169 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005170 if (pstring)
5171 *pstring = ctx.as_string.data;
5172 else
5173 o_free_unsafe(&ctx.as_string);
5174#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005175 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5176 /* Example: bare "{ }", "()" */
5177 G.last_exitcode = 2; /* bash compat */
5178 syntax_error_unexpected_ch(ch);
5179 goto parse_error2;
5180 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005181 debug_printf_parse("parse_stream return %p: "
5182 "end_trigger char found\n",
5183 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005184 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005185 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005186 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005187 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005188 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005189 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005190 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005191
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005192 /* Catch <, > before deciding whether this word is
5193 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5194 switch (ch) {
5195 case '>':
5196 redir_fd = redirect_opt_num(&dest);
5197 if (done_word(&dest, &ctx)) {
5198 goto parse_error;
5199 }
5200 redir_style = REDIRECT_OVERWRITE;
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02005201 if (next == '\\')
5202 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005203 if (next == '>') {
5204 redir_style = REDIRECT_APPEND;
5205 ch = i_getch(input);
5206 nommu_addchr(&ctx.as_string, ch);
5207 }
5208#if 0
5209 else if (next == '(') {
5210 syntax_error(">(process) not supported");
5211 goto parse_error;
5212 }
5213#endif
5214 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5215 goto parse_error;
5216 continue; /* back to top of while (1) */
5217 case '<':
5218 redir_fd = redirect_opt_num(&dest);
5219 if (done_word(&dest, &ctx)) {
5220 goto parse_error;
5221 }
5222 redir_style = REDIRECT_INPUT;
Denys Vlasenkoa94eeb02018-03-31 20:16:31 +02005223 if (next == '\\')
5224 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005225 if (next == '<') {
5226 redir_style = REDIRECT_HEREDOC;
5227 heredoc_cnt++;
5228 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5229 ch = i_getch(input);
5230 nommu_addchr(&ctx.as_string, ch);
5231 } else if (next == '>') {
5232 redir_style = REDIRECT_IO;
5233 ch = i_getch(input);
5234 nommu_addchr(&ctx.as_string, ch);
5235 }
5236#if 0
5237 else if (next == '(') {
5238 syntax_error("<(process) not supported");
5239 goto parse_error;
5240 }
5241#endif
5242 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5243 goto parse_error;
5244 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005245 case '#':
5246 if (dest.length == 0 && !dest.has_quoted_part) {
5247 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005248 /* note: we do not add it to &ctx.as_string */
5249/* TODO: in bash:
5250 * comment inside $() goes to the next \n, even inside quoted string (!):
5251 * cmd "$(cmd2 #comment)" - syntax error
5252 * cmd "`cmd2 #comment`" - ok
5253 * We accept both (comment ends where command subst ends, in both cases).
5254 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005255 while (1) {
5256 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005257 if (ch == '\n') {
5258 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005259 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005260 }
5261 ch = i_getch(input);
5262 if (ch == EOF)
5263 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005264 }
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005265 continue; /* back to top of while (1) */
5266 }
5267 break;
5268 case '\\':
5269 if (next == '\n') {
5270 /* It's "\<newline>" */
5271#if !BB_MMU
5272 /* Remove trailing '\' from ctx.as_string */
5273 ctx.as_string.data[--ctx.as_string.length] = '\0';
5274#endif
5275 ch = i_getch(input); /* eat it */
5276 continue; /* back to top of while (1) */
5277 }
5278 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005279 }
5280
5281 if (dest.o_assignment == MAYBE_ASSIGNMENT
5282 /* check that we are not in word in "a=1 2>word b=1": */
5283 && !ctx.pending_redirect
5284 ) {
5285 /* ch is a special char and thus this word
5286 * cannot be an assignment */
5287 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005288 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005289 }
5290
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005291 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5292
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005293 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005294 case SPECIAL_VAR_SYMBOL:
5295 /* Convert raw ^C to corresponding special variable reference */
5296 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5297 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5298 /* fall through */
5299 case '#':
5300 /* non-comment #: "echo a#b" etc */
5301 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005302 break;
5303 case '\\':
5304 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005305 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005306 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005307 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005308 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005309 /* note: ch != '\n' (that case does not reach this place) */
5310 o_addchr(&dest, '\\');
5311 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5312 o_addchr(&dest, ch);
5313 nommu_addchr(&ctx.as_string, ch);
5314 /* Example: echo Hello \2>file
5315 * we need to know that word 2 is quoted */
5316 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005317 break;
5318 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005319 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005320 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005321 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005322 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005323 }
Eric Andersen25f27032001-04-26 23:22:31 +00005324 break;
5325 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005326 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005327 if (next == '\'' && !ctx.pending_redirect) {
5328 insert_empty_quoted_str_marker:
5329 nommu_addchr(&ctx.as_string, next);
5330 i_getch(input); /* eat second ' */
5331 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5332 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5333 } else {
5334 while (1) {
5335 ch = i_getch(input);
5336 if (ch == EOF) {
5337 syntax_error_unterm_ch('\'');
5338 goto parse_error;
5339 }
5340 nommu_addchr(&ctx.as_string, ch);
5341 if (ch == '\'')
5342 break;
Denys Vlasenko9809a822018-01-13 19:14:27 +01005343 if (ch == SPECIAL_VAR_SYMBOL) {
5344 /* Convert raw ^C to corresponding special variable reference */
5345 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5346 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5347 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005348 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005349 }
Eric Andersen25f27032001-04-26 23:22:31 +00005350 }
Eric Andersen25f27032001-04-26 23:22:31 +00005351 break;
5352 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005353 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005354 if (next == '"' && !ctx.pending_redirect)
5355 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005356 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005357 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005358 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005359 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005360 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00005361 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005362#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005363 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005364 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005365
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005366 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5367 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02005368 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005369 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5370 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005371# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005372 o_addstr(&ctx.as_string, dest.data + pos);
5373 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005374# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005375 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5376 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005377 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005378 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005379#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005380 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005381#if ENABLE_HUSH_CASE
5382 case_semi:
5383#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005384 if (done_word(&dest, &ctx)) {
5385 goto parse_error;
5386 }
5387 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005388#if ENABLE_HUSH_CASE
5389 /* Eat multiple semicolons, detect
5390 * whether it means something special */
5391 while (1) {
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005392 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005393 if (ch != ';')
5394 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005395 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005396 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005397 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005398 ctx.ctx_dsemicolon = 1;
5399 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005400 break;
5401 }
5402 }
5403#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005404 new_cmd:
5405 /* We just finished a cmd. New one may start
5406 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005407 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005408 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00005409 break;
5410 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005411 if (done_word(&dest, &ctx)) {
5412 goto parse_error;
5413 }
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005414 if (next == '\\')
5415 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005416 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005417 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005418 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005419 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005420 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005421 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005422 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005423 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005424 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005425 if (done_word(&dest, &ctx)) {
5426 goto parse_error;
5427 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005428#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005429 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005430 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005431#endif
Denys Vlasenko1e5111b2018-04-01 03:04:55 +02005432 if (next == '\\')
5433 next = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005434 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005435 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005436 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005437 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005438 } else {
5439 /* we could pick up a file descriptor choice here
5440 * with redirect_opt_num(), but bash doesn't do it.
5441 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005442 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005443 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005444 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005445 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005446#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005447 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005448 if (ctx.ctx_res_w == RES_MATCH
5449 && ctx.command->argv == NULL /* not (word|(... */
5450 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005451 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005452 ) {
5453 continue;
5454 }
5455#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005456 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005457 if (parse_group(&dest, &ctx, input, ch) != 0) {
5458 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005459 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005460 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005461 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005462#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005463 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005464 goto case_semi;
5465#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005466 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005467 /* proper use of this character is caught by end_trigger:
5468 * if we see {, we call parse_group(..., end_trigger='}')
5469 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005470 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005471 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005472 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005473 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005474 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005475 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005476 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005477 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005478
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005479 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005480 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005481 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005482 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005483 struct parse_context *pctx;
5484 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005485
5486 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005487 * Sample for finding leaks on syntax error recovery path.
5488 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005489 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005490 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005491 * while if (true | { true;}); then echo ok; fi; do break; done
5492 * 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 +00005493 */
5494 pctx = &ctx;
5495 do {
5496 /* Update pipe/command counts,
5497 * otherwise freeing may miss some */
5498 done_pipe(pctx, PIPE_SEQ);
5499 debug_printf_clean("freeing list %p from ctx %p\n",
5500 pctx->list_head, pctx);
5501 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005502 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005503 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005504#if !BB_MMU
5505 o_free_unsafe(&pctx->as_string);
5506#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005507 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005508 if (pctx != &ctx) {
5509 free(pctx);
5510 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005511 IF_HAS_KEYWORDS(pctx = p2;)
5512 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005513
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005514 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005515#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005516 if (pstring)
5517 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005518#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005519 debug_leave();
5520 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005521 }
Eric Andersen25f27032001-04-26 23:22:31 +00005522}
5523
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005524
5525/*** Execution routines ***/
5526
5527/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005528#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005529/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5530#define expand_string_to_string(str, do_unbackslash) \
5531 expand_string_to_string(str)
5532#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005533static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005534#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005535static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005536#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005537
5538/* expand_strvec_to_strvec() takes a list of strings, expands
5539 * all variable references within and returns a pointer to
5540 * a list of expanded strings, possibly with larger number
5541 * of strings. (Think VAR="a b"; echo $VAR).
5542 * This new list is allocated as a single malloc block.
5543 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005544 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005545 * Caller can deallocate entire list by single free(list). */
5546
Denys Vlasenko238081f2010-10-03 14:26:26 +02005547/* A horde of its helpers come first: */
5548
5549static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5550{
5551 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005552 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005553
Denys Vlasenko9e800222010-10-03 14:28:04 +02005554#if ENABLE_HUSH_BRACE_EXPANSION
5555 if (c == '{' || c == '}') {
5556 /* { -> \{, } -> \} */
5557 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005558 /* And now we want to add { or } and continue:
5559 * o_addchr(o, c);
5560 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005561 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005562 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005563 }
5564#endif
5565 o_addchr(o, c);
5566 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005567 /* \z -> \\\z; \<eol> -> \\<eol> */
5568 o_addchr(o, '\\');
5569 if (len) {
5570 len--;
5571 o_addchr(o, '\\');
5572 o_addchr(o, *str++);
5573 }
5574 }
5575 }
5576}
5577
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005578/* Store given string, finalizing the word and starting new one whenever
5579 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005580 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5581 * Return in *ended_with_ifs:
5582 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5583 */
5584static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005585{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005586 int last_is_ifs = 0;
5587
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005588 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005589 int word_len;
5590
5591 if (!*str) /* EOL - do not finalize word */
5592 break;
5593 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005594 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005595 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005596 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005597 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005598 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005599 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005600 * Example: "v='\*'; echo b$v" prints "b\*"
5601 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005602 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005603 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005604 /*/ Why can't we do it easier? */
5605 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5606 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5607 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005608 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005609 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005610 if (!*str) /* EOL - do not finalize word */
5611 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005612 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005613
5614 /* We know str here points to at least one IFS char */
5615 last_is_ifs = 1;
5616 str += strspn(str, G.ifs); /* skip IFS chars */
5617 if (!*str) /* EOL - do not finalize word */
5618 break;
5619
5620 /* Start new word... but not always! */
5621 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005622 if (output->has_quoted_part
5623 /* Case "v=' a'; echo $v":
5624 * here nothing precedes the space in $v expansion,
5625 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005626 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005627 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005628 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005629 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005630 o_addchr(output, '\0');
5631 debug_print_list("expand_on_ifs", output, n);
5632 n = o_save_ptr(output, n);
5633 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005634 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005635
5636 if (ended_with_ifs)
5637 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005638 debug_print_list("expand_on_ifs[1]", output, n);
5639 return n;
5640}
5641
5642/* Helper to expand $((...)) and heredoc body. These act as if
5643 * they are in double quotes, with the exception that they are not :).
5644 * Just the rules are similar: "expand only $var and `cmd`"
5645 *
5646 * Returns malloced string.
5647 * As an optimization, we return NULL if expansion is not needed.
5648 */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005649#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005650/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5651#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5652 encode_then_expand_string(str)
5653#endif
5654static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005655{
Denys Vlasenko637982f2017-07-06 01:52:23 +02005656#if !BASH_PATTERN_SUBST
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01005657 enum { do_unbackslash = 1 };
Denys Vlasenko637982f2017-07-06 01:52:23 +02005658#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005659 char *exp_str;
5660 struct in_str input;
5661 o_string dest = NULL_O_STRING;
5662
5663 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005664 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005665#if ENABLE_HUSH_TICK
5666 && !strchr(str, '`')
5667#endif
5668 ) {
5669 return NULL;
5670 }
5671
5672 /* We need to expand. Example:
5673 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5674 */
5675 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005676 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005677//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005678 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005679 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005680 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5681 o_free_unsafe(&dest);
5682 return exp_str;
5683}
5684
Denys Vlasenko0b883582016-12-23 16:49:07 +01005685#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005686static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005687{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005688 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005689 arith_t res;
5690 char *exp_str;
5691
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005692 math_state.lookupvar = get_local_var_value;
5693 math_state.setvar = set_local_var_from_halves;
5694 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005695 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005696 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005697 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005698 if (errmsg_p)
5699 *errmsg_p = math_state.errmsg;
5700 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005701 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005702 return res;
5703}
5704#endif
5705
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005706#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005707/* ${var/[/]pattern[/repl]} helpers */
5708static char *strstr_pattern(char *val, const char *pattern, int *size)
5709{
5710 while (1) {
5711 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5712 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5713 if (end) {
5714 *size = end - val;
5715 return val;
5716 }
5717 if (*val == '\0')
5718 return NULL;
5719 /* Optimization: if "*pat" did not match the start of "string",
5720 * we know that "tring", "ring" etc will not match too:
5721 */
5722 if (pattern[0] == '*')
5723 return NULL;
5724 val++;
5725 }
5726}
5727static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5728{
5729 char *result = NULL;
5730 unsigned res_len = 0;
5731 unsigned repl_len = strlen(repl);
5732
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005733 /* Null pattern never matches, including if "var" is empty */
5734 if (!pattern[0])
5735 return result; /* NULL, no replaces happened */
5736
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005737 while (1) {
5738 int size;
5739 char *s = strstr_pattern(val, pattern, &size);
5740 if (!s)
5741 break;
5742
5743 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005744 strcpy(mempcpy(result + res_len, val, s - val), repl);
5745 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005746 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5747
5748 val = s + size;
5749 if (exp_op == '/')
5750 break;
5751 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005752 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005753 result = xrealloc(result, res_len + strlen(val) + 1);
5754 strcpy(result + res_len, val);
5755 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5756 }
5757 debug_printf_varexp("result:'%s'\n", result);
5758 return result;
5759}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005760#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005761
5762/* Helper:
5763 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5764 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005765static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005766{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005767 const char *val;
5768 char *to_be_freed;
5769 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005770 char *var;
5771 char first_char;
5772 char exp_op;
5773 char exp_save = exp_save; /* for compiler */
5774 char *exp_saveptr; /* points to expansion operator */
5775 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005776 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005777
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005778 val = NULL;
5779 to_be_freed = NULL;
5780 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005781 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005782 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005783 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005784 arg0 = arg[0];
5785 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005786 exp_op = 0;
5787
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005788 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5789 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5790 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5791 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005792 ) {
5793 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005794 var++;
5795 exp_op = 'L';
5796 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005797 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005798 if (exp_saveptr /* if 2nd char is one of expansion operators */
5799 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5800 ) {
5801 /* ${?:0}, ${#[:]%0} etc */
5802 exp_saveptr = var + 1;
5803 } else {
5804 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5805 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5806 }
5807 exp_op = exp_save = *exp_saveptr;
5808 if (exp_op) {
5809 exp_word = exp_saveptr + 1;
5810 if (exp_op == ':') {
5811 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005812//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005813 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005814 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005815 ) {
5816 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5817 exp_op = ':';
5818 exp_word--;
5819 }
5820 }
5821 *exp_saveptr = '\0';
5822 } /* else: it's not an expansion op, but bare ${var} */
5823 }
5824
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005825 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005826 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005827 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005828 int n = xatoi_positive(var);
5829 if (n < G.global_argc)
5830 val = G.global_argv[n];
5831 /* else val remains NULL: $N with too big N */
5832 } else {
5833 switch (var[0]) {
5834 case '$': /* pid */
5835 val = utoa(G.root_pid);
5836 break;
5837 case '!': /* bg pid */
5838 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5839 break;
5840 case '?': /* exitcode */
5841 val = utoa(G.last_exitcode);
5842 break;
5843 case '#': /* argc */
5844 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5845 break;
5846 default:
5847 val = get_local_var_value(var);
5848 }
5849 }
5850
5851 /* Handle any expansions */
5852 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005853 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005854 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005855 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005856 debug_printf_expand("%s\n", val);
5857 } else if (exp_op) {
5858 if (exp_op == '%' || exp_op == '#') {
5859 /* Standard-mandated substring removal ops:
5860 * ${parameter%word} - remove smallest suffix pattern
5861 * ${parameter%%word} - remove largest suffix pattern
5862 * ${parameter#word} - remove smallest prefix pattern
5863 * ${parameter##word} - remove largest prefix pattern
5864 *
5865 * Word is expanded to produce a glob pattern.
5866 * Then var's value is matched to it and matching part removed.
5867 */
5868 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005869 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005870 char *exp_exp_word;
5871 char *loc;
5872 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005873 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005874 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005875 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01005876 /*
5877 * process_bkslash:1 unbackslash:1 breaks this:
5878 * a='a\\'; echo ${a%\\\\} # correct output is: a
5879 * process_bkslash:1 unbackslash:0 breaks this:
5880 * a='a}'; echo ${a%\}} # correct output is: a
5881 */
5882 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005883 if (exp_exp_word)
5884 exp_word = exp_exp_word;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005885 debug_printf_expand("expand: exp_exp_word:'%s'\n", exp_word);
Denys Vlasenko4f870492010-09-10 11:06:01 +02005886 /* HACK ALERT. We depend here on the fact that
5887 * G.global_argv and results of utoa and get_local_var_value
5888 * are actually in writable memory:
5889 * scan_and_match momentarily stores NULs there. */
5890 t = (char*)val;
5891 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01005892 debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005893 free(exp_exp_word);
5894 if (loc) { /* match was found */
5895 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005896 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005897 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005898 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005899 }
5900 }
5901 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005902#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005903 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005904 /* It's ${var/[/]pattern[/repl]} thing.
5905 * Note that in encoded form it has TWO parts:
5906 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005907 * and if // is used, it is encoded as \:
5908 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005909 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005910 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005911 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005912 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005913 * by the usual expansion rules:
5914 * >az; >bz;
5915 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5916 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5917 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5918 * v='a bz'; echo ${v/a*z/\z} prints "z"
5919 * (note that a*z _pattern_ is never globbed!)
5920 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005921 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005922 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005923 if (!pattern)
5924 pattern = xstrdup(exp_word);
5925 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5926 *p++ = SPECIAL_VAR_SYMBOL;
5927 exp_word = p;
5928 p = strchr(p, SPECIAL_VAR_SYMBOL);
5929 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005930 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005931 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5932 /* HACK ALERT. We depend here on the fact that
5933 * G.global_argv and results of utoa and get_local_var_value
5934 * are actually in writable memory:
5935 * replace_pattern momentarily stores NULs there. */
5936 t = (char*)val;
5937 to_be_freed = replace_pattern(t,
5938 pattern,
5939 (repl ? repl : exp_word),
5940 exp_op);
5941 if (to_be_freed) /* at least one replace happened */
5942 val = to_be_freed;
5943 free(pattern);
5944 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005945 } else {
5946 /* Empty variable always gives nothing */
5947 // "v=''; echo ${v/*/w}" prints "", not "w"
5948 /* Just skip "replace" part */
5949 *p++ = SPECIAL_VAR_SYMBOL;
5950 p = strchr(p, SPECIAL_VAR_SYMBOL);
5951 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005952 }
5953 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005954#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005955 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005956#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005957 /* It's ${var:N[:M]} bashism.
5958 * Note that in encoded form it has TWO parts:
5959 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5960 */
5961 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005962 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005963
Denys Vlasenko063847d2010-09-15 13:33:02 +02005964 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5965 if (errmsg)
5966 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005967 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5968 *p++ = SPECIAL_VAR_SYMBOL;
5969 exp_word = p;
5970 p = strchr(p, SPECIAL_VAR_SYMBOL);
5971 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005972 len = expand_and_evaluate_arith(exp_word, &errmsg);
5973 if (errmsg)
5974 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005975 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005976 if (beg < 0) {
5977 /* negative beg counts from the end */
5978 beg = (arith_t)strlen(val) + beg;
5979 if (beg < 0) /* ${v: -999999} is "" */
5980 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005981 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005982 debug_printf_varexp("from val:'%s'\n", val);
5983 if (len < 0) {
5984 /* in bash, len=-n means strlen()-n */
5985 len = (arith_t)strlen(val) - beg + len;
5986 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02005987 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005988 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02005989 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005990 arith_err:
5991 val = NULL;
5992 } else {
5993 /* Paranoia. What if user entered 9999999999999
5994 * which fits in arith_t but not int? */
5995 if (len >= INT_MAX)
5996 len = INT_MAX;
5997 val = to_be_freed = xstrndup(val + beg, len);
5998 }
5999 debug_printf_varexp("val:'%s'\n", val);
6000#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02006001 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02006002 val = NULL;
6003#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006004 } else { /* one of "-=+?" */
6005 /* Standard-mandated substitution ops:
6006 * ${var?word} - indicate error if unset
6007 * If var is unset, word (or a message indicating it is unset
6008 * if word is null) is written to standard error
6009 * and the shell exits with a non-zero exit status.
6010 * Otherwise, the value of var is substituted.
6011 * ${var-word} - use default value
6012 * If var is unset, word is substituted.
6013 * ${var=word} - assign and use default value
6014 * If var is unset, word is assigned to var.
6015 * In all cases, final value of var is substituted.
6016 * ${var+word} - use alternative value
6017 * If var is unset, null is substituted.
6018 * Otherwise, word is substituted.
6019 *
6020 * Word is subjected to tilde expansion, parameter expansion,
6021 * command substitution, and arithmetic expansion.
6022 * If word is not needed, it is not expanded.
6023 *
6024 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
6025 * but also treat null var as if it is unset.
6026 */
6027 int use_word = (!val || ((exp_save == ':') && !val[0]));
6028 if (exp_op == '+')
6029 use_word = !use_word;
6030 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6031 (exp_save == ':') ? "true" : "false", use_word);
6032 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006033 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006034 if (to_be_freed)
6035 exp_word = to_be_freed;
6036 if (exp_op == '?') {
6037 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006038 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006039 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02006040 exp_word[0]
6041 ? exp_word
6042 : "parameter null or not set"
6043 /* ash has more specific messages, a-la: */
6044 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006045 );
6046//TODO: how interactive bash aborts expansion mid-command?
6047 } else {
6048 val = exp_word;
6049 }
6050
6051 if (exp_op == '=') {
6052 /* ${var=[word]} or ${var:=[word]} */
6053 if (isdigit(var[0]) || var[0] == '#') {
6054 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006055 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006056 val = NULL;
6057 } else {
6058 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02006059 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006060 }
6061 }
6062 }
6063 } /* one of "-=+?" */
6064
6065 *exp_saveptr = exp_save;
6066 } /* if (exp_op) */
6067
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006068 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006069
6070 *pp = p;
6071 *to_be_freed_pp = to_be_freed;
6072 return val;
6073}
6074
6075/* Expand all variable references in given string, adding words to list[]
6076 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6077 * to be filled). This routine is extremely tricky: has to deal with
6078 * variables/parameters with whitespace, $* and $@, and constructs like
6079 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006080static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006081{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006082 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006083 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006084 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006085 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006086 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006087 char *p;
6088
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006089 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6090 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006091 debug_print_list("expand_vars_to_list", output, n);
6092 n = o_save_ptr(output, n);
6093 debug_print_list("expand_vars_to_list[0]", output, n);
6094
6095 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6096 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006097 char *to_be_freed = NULL;
6098 const char *val = NULL;
6099#if ENABLE_HUSH_TICK
6100 o_string subst_result = NULL_O_STRING;
6101#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006102#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006103 char arith_buf[sizeof(arith_t)*3 + 2];
6104#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006105
6106 if (ended_in_ifs) {
6107 o_addchr(output, '\0');
6108 n = o_save_ptr(output, n);
6109 ended_in_ifs = 0;
6110 }
6111
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006112 o_addblock(output, arg, p - arg);
6113 debug_print_list("expand_vars_to_list[1]", output, n);
6114 arg = ++p;
6115 p = strchr(p, SPECIAL_VAR_SYMBOL);
6116
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006117 /* Fetch special var name (if it is indeed one of them)
6118 * and quote bit, force the bit on if singleword expansion -
6119 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006120 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006121
6122 /* Is this variable quoted and thus expansion can't be null?
6123 * "$@" is special. Even if quoted, it can still
6124 * expand to nothing (not even an empty string),
6125 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006126 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006127 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006128
6129 switch (first_ch & 0x7f) {
6130 /* Highest bit in first_ch indicates that var is double-quoted */
6131 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006132 case '@': {
6133 int i;
6134 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006135 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006136 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006137 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006138 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006139 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006140 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006141 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6142 if (G.global_argv[i++][0] && G.global_argv[i]) {
6143 /* this argv[] is not empty and not last:
6144 * put terminating NUL, start new word */
6145 o_addchr(output, '\0');
6146 debug_print_list("expand_vars_to_list[2]", output, n);
6147 n = o_save_ptr(output, n);
6148 debug_print_list("expand_vars_to_list[3]", output, n);
6149 }
6150 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006151 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006152 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006153 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko6ffaa002018-03-31 00:46:07 +02006154 if (first_ch == (char)('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006155 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006156 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006157 while (1) {
6158 o_addQstr(output, G.global_argv[i]);
6159 if (++i >= G.global_argc)
6160 break;
6161 o_addchr(output, '\0');
6162 debug_print_list("expand_vars_to_list[4]", output, n);
6163 n = o_save_ptr(output, n);
6164 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006165 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006166 while (1) {
6167 o_addQstr(output, G.global_argv[i]);
6168 if (!G.global_argv[++i])
6169 break;
6170 if (G.ifs[0])
6171 o_addchr(output, G.ifs[0]);
6172 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006173 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006174 }
6175 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006176 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006177 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6178 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006179 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006180 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006181 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006182 break;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006183 case SPECIAL_VAR_QUOTED_SVS:
6184 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6185 arg++;
6186 val = SPECIAL_VAR_SYMBOL_STR;
6187 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006188#if ENABLE_HUSH_TICK
6189 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006190 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006191 arg++;
6192 /* Can't just stuff it into output o_string,
6193 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006194 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006195 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6196 G.last_exitcode = process_command_subs(&subst_result, arg);
6197 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6198 val = subst_result.data;
6199 goto store_val;
6200#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006201#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006202 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6203 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006204
6205 arg++; /* skip '+' */
6206 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6207 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006208 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006209 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6210 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006211 val = arith_buf;
6212 break;
6213 }
6214#endif
6215 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006216 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006217 IF_HUSH_TICK(store_val:)
6218 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006219 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6220 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006221 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006222 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006223 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006224 }
6225 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006226 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006227 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6228 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006229 }
6230 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006231 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6232
6233 if (val && val[0]) {
6234 o_addQstr(output, val);
6235 }
6236 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006237
6238 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6239 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006240 if (*p != SPECIAL_VAR_SYMBOL)
6241 *p = SPECIAL_VAR_SYMBOL;
6242
6243#if ENABLE_HUSH_TICK
6244 o_free(&subst_result);
6245#endif
6246 arg = ++p;
6247 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6248
6249 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006250 if (ended_in_ifs) {
6251 o_addchr(output, '\0');
6252 n = o_save_ptr(output, n);
6253 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006254 debug_print_list("expand_vars_to_list[a]", output, n);
6255 /* this part is literal, and it was already pre-quoted
6256 * if needed (much earlier), do not use o_addQstr here! */
6257 o_addstr_with_NUL(output, arg);
6258 debug_print_list("expand_vars_to_list[b]", output, n);
6259 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006260 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006261 ) {
6262 n--;
6263 /* allow to reuse list[n] later without re-growth */
6264 output->has_empty_slot = 1;
6265 } else {
6266 o_addchr(output, '\0');
6267 }
6268
6269 return n;
6270}
6271
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006272static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006273{
6274 int n;
6275 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006276 o_string output = NULL_O_STRING;
6277
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006278 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006279
6280 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006281 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006282 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006283 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006284 }
6285 debug_print_list("expand_variables", &output, n);
6286
6287 /* output.data (malloced in one block) gets returned in "list" */
6288 list = o_finalize_list(&output, n);
6289 debug_print_strings("expand_variables[1]", list);
6290 return list;
6291}
6292
6293static char **expand_strvec_to_strvec(char **argv)
6294{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006295 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006296}
6297
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006298#if BASH_TEST2
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006299static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6300{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006301 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006302}
6303#endif
6304
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006305/* Used for expansion of right hand of assignments,
6306 * $((...)), heredocs, variable espansion parts.
6307 *
6308 * NB: should NOT do globbing!
6309 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6310 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006311static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006312{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006313#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006314 const int do_unbackslash = 1;
6315#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006316 char *argv[2], **list;
6317
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006318 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006319 /* This is generally an optimization, but it also
6320 * handles "", which otherwise trips over !list[0] check below.
6321 * (is this ever happens that we actually get str="" here?)
6322 */
6323 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6324 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006325 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006326 return xstrdup(str);
6327 }
6328
6329 argv[0] = (char*)str;
6330 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006331 list = expand_variables(argv, do_unbackslash
6332 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6333 : EXP_FLAG_SINGLEWORD
6334 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006335 if (HUSH_DEBUG)
6336 if (!list[0] || list[1])
6337 bb_error_msg_and_die("BUG in varexp2");
6338 /* actually, just move string 2*sizeof(char*) bytes back */
6339 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006340 if (do_unbackslash)
6341 unbackslash((char*)list);
6342 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006343 return (char*)list;
6344}
6345
Denys Vlasenko1f191122018-01-11 13:17:30 +01006346#if ENABLE_HUSH_CASE
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006347static char* expand_strvec_to_string(char **argv)
6348{
6349 char **list;
6350
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006351 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006352 /* Convert all NULs to spaces */
6353 if (list[0]) {
6354 int n = 1;
6355 while (list[n]) {
6356 if (HUSH_DEBUG)
6357 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6358 bb_error_msg_and_die("BUG in varexp3");
6359 /* bash uses ' ' regardless of $IFS contents */
6360 list[n][-1] = ' ';
6361 n++;
6362 }
6363 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006364 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006365 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6366 return (char*)list;
6367}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006368#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006369
6370static char **expand_assignments(char **argv, int count)
6371{
6372 int i;
6373 char **p;
6374
6375 G.expanded_assignments = p = NULL;
6376 /* Expand assignments into one string each */
6377 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006378 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006379 }
6380 G.expanded_assignments = NULL;
6381 return p;
6382}
6383
6384
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006385static void switch_off_special_sigs(unsigned mask)
6386{
6387 unsigned sig = 0;
6388 while ((mask >>= 1) != 0) {
6389 sig++;
6390 if (!(mask & 1))
6391 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006392#if ENABLE_HUSH_TRAP
6393 if (G_traps) {
6394 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006395 /* trap is '', has to remain SIG_IGN */
6396 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006397 free(G_traps[sig]);
6398 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006399 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006400#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006401 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006402 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006403 }
6404}
6405
Denys Vlasenkob347df92011-08-09 22:49:15 +02006406#if BB_MMU
6407/* never called */
6408void re_execute_shell(char ***to_free, const char *s,
6409 char *g_argv0, char **g_argv,
6410 char **builtin_argv) NORETURN;
6411
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006412static void reset_traps_to_defaults(void)
6413{
6414 /* This function is always called in a child shell
6415 * after fork (not vfork, NOMMU doesn't use this function).
6416 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006417 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006418 unsigned mask;
6419
6420 /* Child shells are not interactive.
6421 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6422 * Testcase: (while :; do :; done) + ^Z should background.
6423 * Same goes for SIGTERM, SIGHUP, SIGINT.
6424 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006425 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006426 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006427 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006428
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006429 /* Switch off special sigs */
6430 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006431# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006432 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006433# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006434 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006435 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6436 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006437
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006438# if ENABLE_HUSH_TRAP
6439 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006440 return;
6441
6442 /* Reset all sigs to default except ones with empty traps */
6443 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006444 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006445 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006446 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006447 continue; /* empty trap: has to remain SIG_IGN */
6448 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006449 free(G_traps[sig]);
6450 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006451 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006452 if (sig == 0)
6453 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006454 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006455 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006456# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006457}
6458
6459#else /* !BB_MMU */
6460
6461static void re_execute_shell(char ***to_free, const char *s,
6462 char *g_argv0, char **g_argv,
6463 char **builtin_argv) NORETURN;
6464static void re_execute_shell(char ***to_free, const char *s,
6465 char *g_argv0, char **g_argv,
6466 char **builtin_argv)
6467{
6468# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6469 /* delims + 2 * (number of bytes in printed hex numbers) */
6470 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6471 char *heredoc_argv[4];
6472 struct variable *cur;
6473# if ENABLE_HUSH_FUNCTIONS
6474 struct function *funcp;
6475# endif
6476 char **argv, **pp;
6477 unsigned cnt;
6478 unsigned long long empty_trap_mask;
6479
6480 if (!g_argv0) { /* heredoc */
6481 argv = heredoc_argv;
6482 argv[0] = (char *) G.argv0_for_re_execing;
6483 argv[1] = (char *) "-<";
6484 argv[2] = (char *) s;
6485 argv[3] = NULL;
6486 pp = &argv[3]; /* used as pointer to empty environment */
6487 goto do_exec;
6488 }
6489
6490 cnt = 0;
6491 pp = builtin_argv;
6492 if (pp) while (*pp++)
6493 cnt++;
6494
6495 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006496 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006497 int sig;
6498 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006499 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006500 empty_trap_mask |= 1LL << sig;
6501 }
6502 }
6503
6504 sprintf(param_buf, NOMMU_HACK_FMT
6505 , (unsigned) G.root_pid
6506 , (unsigned) G.root_ppid
6507 , (unsigned) G.last_bg_pid
6508 , (unsigned) G.last_exitcode
6509 , cnt
6510 , empty_trap_mask
6511 IF_HUSH_LOOPS(, G.depth_of_loop)
6512 );
6513# undef NOMMU_HACK_FMT
6514 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6515 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6516 */
6517 cnt += 6;
6518 for (cur = G.top_var; cur; cur = cur->next) {
6519 if (!cur->flg_export || cur->flg_read_only)
6520 cnt += 2;
6521 }
6522# if ENABLE_HUSH_FUNCTIONS
6523 for (funcp = G.top_func; funcp; funcp = funcp->next)
6524 cnt += 3;
6525# endif
6526 pp = g_argv;
6527 while (*pp++)
6528 cnt++;
6529 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6530 *pp++ = (char *) G.argv0_for_re_execing;
6531 *pp++ = param_buf;
6532 for (cur = G.top_var; cur; cur = cur->next) {
6533 if (strcmp(cur->varstr, hush_version_str) == 0)
6534 continue;
6535 if (cur->flg_read_only) {
6536 *pp++ = (char *) "-R";
6537 *pp++ = cur->varstr;
6538 } else if (!cur->flg_export) {
6539 *pp++ = (char *) "-V";
6540 *pp++ = cur->varstr;
6541 }
6542 }
6543# if ENABLE_HUSH_FUNCTIONS
6544 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6545 *pp++ = (char *) "-F";
6546 *pp++ = funcp->name;
6547 *pp++ = funcp->body_as_string;
6548 }
6549# endif
6550 /* We can pass activated traps here. Say, -Tnn:trap_string
6551 *
6552 * However, POSIX says that subshells reset signals with traps
6553 * to SIG_DFL.
6554 * I tested bash-3.2 and it not only does that with true subshells
6555 * of the form ( list ), but with any forked children shells.
6556 * I set trap "echo W" WINCH; and then tried:
6557 *
6558 * { echo 1; sleep 20; echo 2; } &
6559 * while true; do echo 1; sleep 20; echo 2; break; done &
6560 * true | { echo 1; sleep 20; echo 2; } | cat
6561 *
6562 * In all these cases sending SIGWINCH to the child shell
6563 * did not run the trap. If I add trap "echo V" WINCH;
6564 * _inside_ group (just before echo 1), it works.
6565 *
6566 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006567 */
6568 *pp++ = (char *) "-c";
6569 *pp++ = (char *) s;
6570 if (builtin_argv) {
6571 while (*++builtin_argv)
6572 *pp++ = *builtin_argv;
6573 *pp++ = (char *) "";
6574 }
6575 *pp++ = g_argv0;
6576 while (*g_argv)
6577 *pp++ = *g_argv++;
6578 /* *pp = NULL; - is already there */
6579 pp = environ;
6580
6581 do_exec:
6582 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006583 /* Don't propagate SIG_IGN to the child */
6584 if (SPECIAL_JOBSTOP_SIGS != 0)
6585 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006586 execve(bb_busybox_exec_path, argv, pp);
6587 /* Fallback. Useful for init=/bin/hush usage etc */
6588 if (argv[0][0] == '/')
6589 execve(argv[0], argv, pp);
6590 xfunc_error_retval = 127;
6591 bb_error_msg_and_die("can't re-execute the shell");
6592}
6593#endif /* !BB_MMU */
6594
6595
6596static int run_and_free_list(struct pipe *pi);
6597
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006598/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006599 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6600 * end_trigger controls how often we stop parsing
6601 * NUL: parse all, execute, return
6602 * ';': parse till ';' or newline, execute, repeat till EOF
6603 */
6604static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006605{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006606 /* Why we need empty flag?
6607 * An obscure corner case "false; ``; echo $?":
6608 * empty command in `` should still set $? to 0.
6609 * But we can't just set $? to 0 at the start,
6610 * this breaks "false; echo `echo $?`" case.
6611 */
6612 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006613 while (1) {
6614 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006615
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006616#if ENABLE_HUSH_INTERACTIVE
6617 if (end_trigger == ';')
6618 inp->promptmode = 0; /* PS1 */
6619#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006620 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006621 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6622 /* If we are in "big" script
6623 * (not in `cmd` or something similar)...
6624 */
6625 if (pipe_list == ERR_PTR && end_trigger == ';') {
6626 /* Discard cached input (rest of line) */
6627 int ch = inp->last_char;
6628 while (ch != EOF && ch != '\n') {
6629 //bb_error_msg("Discarded:'%c'", ch);
6630 ch = i_getch(inp);
6631 }
6632 /* Force prompt */
6633 inp->p = NULL;
6634 /* This stream isn't empty */
6635 empty = 0;
6636 continue;
6637 }
6638 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006639 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006640 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006641 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006642 debug_print_tree(pipe_list, 0);
6643 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6644 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006645 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006646 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006647 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006648 }
Eric Andersen25f27032001-04-26 23:22:31 +00006649}
6650
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006651static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006652{
6653 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006654 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6655
Eric Andersen25f27032001-04-26 23:22:31 +00006656 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006657 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006658 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006659}
6660
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006661static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006662{
Eric Andersen25f27032001-04-26 23:22:31 +00006663 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006664 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01006665
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006666 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01006667 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006668 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006669 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006670}
6671
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006672#if ENABLE_HUSH_TICK
6673static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6674{
6675 pid_t pid;
6676 int channel[2];
6677# if !BB_MMU
6678 char **to_free = NULL;
6679# endif
6680
6681 xpipe(channel);
6682 pid = BB_MMU ? xfork() : xvfork();
6683 if (pid == 0) { /* child */
6684 disable_restore_tty_pgrp_on_exit();
6685 /* Process substitution is not considered to be usual
6686 * 'command execution'.
6687 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6688 */
6689 bb_signals(0
6690 + (1 << SIGTSTP)
6691 + (1 << SIGTTIN)
6692 + (1 << SIGTTOU)
6693 , SIG_IGN);
6694 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6695 close(channel[0]); /* NB: close _first_, then move fd! */
6696 xmove_fd(channel[1], 1);
6697 /* Prevent it from trying to handle ctrl-z etc */
6698 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006699# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006700 /* Awful hack for `trap` or $(trap).
6701 *
6702 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6703 * contains an example where "trap" is executed in a subshell:
6704 *
6705 * save_traps=$(trap)
6706 * ...
6707 * eval "$save_traps"
6708 *
6709 * Standard does not say that "trap" in subshell shall print
6710 * parent shell's traps. It only says that its output
6711 * must have suitable form, but then, in the above example
6712 * (which is not supposed to be normative), it implies that.
6713 *
6714 * bash (and probably other shell) does implement it
6715 * (traps are reset to defaults, but "trap" still shows them),
6716 * but as a result, "trap" logic is hopelessly messed up:
6717 *
6718 * # trap
6719 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6720 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6721 * # true | trap <--- trap is in subshell - no output (ditto)
6722 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6723 * trap -- 'echo Ho' SIGWINCH
6724 * # echo `(trap)` <--- in subshell in subshell - output
6725 * trap -- 'echo Ho' SIGWINCH
6726 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6727 * trap -- 'echo Ho' SIGWINCH
6728 *
6729 * The rules when to forget and when to not forget traps
6730 * get really complex and nonsensical.
6731 *
6732 * Our solution: ONLY bare $(trap) or `trap` is special.
6733 */
6734 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006735 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006736 && skip_whitespace(s + 4)[0] == '\0'
6737 ) {
6738 static const char *const argv[] = { NULL, NULL };
6739 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006740 fflush_all(); /* important */
6741 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006742 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006743# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006744# if BB_MMU
6745 reset_traps_to_defaults();
6746 parse_and_run_string(s);
6747 _exit(G.last_exitcode);
6748# else
6749 /* We re-execute after vfork on NOMMU. This makes this script safe:
6750 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6751 * huge=`cat BIG` # was blocking here forever
6752 * echo OK
6753 */
6754 re_execute_shell(&to_free,
6755 s,
6756 G.global_argv[0],
6757 G.global_argv + 1,
6758 NULL);
6759# endif
6760 }
6761
6762 /* parent */
6763 *pid_p = pid;
6764# if ENABLE_HUSH_FAST
6765 G.count_SIGCHLD++;
6766//bb_error_msg("[%d] fork in generate_stream_from_string:"
6767// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6768// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6769# endif
6770 enable_restore_tty_pgrp_on_exit();
6771# if !BB_MMU
6772 free(to_free);
6773# endif
6774 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006775 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006776}
6777
6778/* Return code is exit status of the process that is run. */
6779static int process_command_subs(o_string *dest, const char *s)
6780{
6781 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006782 pid_t pid;
6783 int status, ch, eol_cnt;
6784
6785 fp = generate_stream_from_string(s, &pid);
6786
6787 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006788 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006789 while ((ch = getc(fp)) != EOF) {
6790 if (ch == '\0')
6791 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006792 if (ch == '\n') {
6793 eol_cnt++;
6794 continue;
6795 }
6796 while (eol_cnt) {
6797 o_addchr(dest, '\n');
6798 eol_cnt--;
6799 }
6800 o_addQchr(dest, ch);
6801 }
6802
6803 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006804 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006805 /* We need to extract exitcode. Test case
6806 * "true; echo `sleep 1; false` $?"
6807 * should print 1 */
6808 safe_waitpid(pid, &status, 0);
6809 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6810 return WEXITSTATUS(status);
6811}
6812#endif /* ENABLE_HUSH_TICK */
6813
6814
6815static void setup_heredoc(struct redir_struct *redir)
6816{
6817 struct fd_pair pair;
6818 pid_t pid;
6819 int len, written;
6820 /* the _body_ of heredoc (misleading field name) */
6821 const char *heredoc = redir->rd_filename;
6822 char *expanded;
6823#if !BB_MMU
6824 char **to_free;
6825#endif
6826
6827 expanded = NULL;
6828 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006829 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006830 if (expanded)
6831 heredoc = expanded;
6832 }
6833 len = strlen(heredoc);
6834
6835 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6836 xpiped_pair(pair);
6837 xmove_fd(pair.rd, redir->rd_fd);
6838
6839 /* Try writing without forking. Newer kernels have
6840 * dynamically growing pipes. Must use non-blocking write! */
6841 ndelay_on(pair.wr);
6842 while (1) {
6843 written = write(pair.wr, heredoc, len);
6844 if (written <= 0)
6845 break;
6846 len -= written;
6847 if (len == 0) {
6848 close(pair.wr);
6849 free(expanded);
6850 return;
6851 }
6852 heredoc += written;
6853 }
6854 ndelay_off(pair.wr);
6855
6856 /* Okay, pipe buffer was not big enough */
6857 /* Note: we must not create a stray child (bastard? :)
6858 * for the unsuspecting parent process. Child creates a grandchild
6859 * and exits before parent execs the process which consumes heredoc
6860 * (that exec happens after we return from this function) */
6861#if !BB_MMU
6862 to_free = NULL;
6863#endif
6864 pid = xvfork();
6865 if (pid == 0) {
6866 /* child */
6867 disable_restore_tty_pgrp_on_exit();
6868 pid = BB_MMU ? xfork() : xvfork();
6869 if (pid != 0)
6870 _exit(0);
6871 /* grandchild */
6872 close(redir->rd_fd); /* read side of the pipe */
6873#if BB_MMU
6874 full_write(pair.wr, heredoc, len); /* may loop or block */
6875 _exit(0);
6876#else
6877 /* Delegate blocking writes to another process */
6878 xmove_fd(pair.wr, STDOUT_FILENO);
6879 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6880#endif
6881 }
6882 /* parent */
6883#if ENABLE_HUSH_FAST
6884 G.count_SIGCHLD++;
6885//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6886#endif
6887 enable_restore_tty_pgrp_on_exit();
6888#if !BB_MMU
6889 free(to_free);
6890#endif
6891 close(pair.wr);
6892 free(expanded);
6893 wait(NULL); /* wait till child has died */
6894}
6895
Denys Vlasenko2db74612017-07-07 22:07:28 +02006896struct squirrel {
6897 int orig_fd;
6898 int moved_to;
6899 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6900 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6901};
6902
Denys Vlasenko621fc502017-07-24 12:42:17 +02006903static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6904{
6905 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6906 sq[i].orig_fd = orig;
6907 sq[i].moved_to = moved;
6908 sq[i+1].orig_fd = -1; /* end marker */
6909 return sq;
6910}
6911
Denys Vlasenko2db74612017-07-07 22:07:28 +02006912static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6913{
Denys Vlasenko621fc502017-07-24 12:42:17 +02006914 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006915 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02006916
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006917 i = 0;
6918 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006919 /* If we collide with an already moved fd... */
6920 if (fd == sq[i].moved_to) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02006921 sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006922 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6923 if (sq[i].moved_to < 0) /* what? */
6924 xfunc_die();
6925 return sq;
6926 }
6927 if (fd == sq[i].orig_fd) {
6928 /* Example: echo Hello >/dev/null 1>&2 */
6929 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6930 return sq;
6931 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006932 }
6933
Denys Vlasenko2db74612017-07-07 22:07:28 +02006934 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02006935 moved_to = dup_CLOEXEC(fd, avoid_fd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02006936 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6937 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02006938 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02006939 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006940}
6941
Denys Vlasenko657e9002017-07-30 23:34:04 +02006942static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6943{
6944 int i;
6945
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006946 i = 0;
6947 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006948 /* If we collide with an already moved fd... */
6949 if (fd == sq[i].orig_fd) {
6950 /* Examples:
6951 * "echo 3>FILE 3>&- 3>FILE"
6952 * "echo 3>&- 3>FILE"
6953 * No need for last redirect to insert
6954 * another "need to close 3" indicator.
6955 */
6956 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6957 return sq;
6958 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006959 }
6960
6961 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6962 return append_squirrel(sq, i, fd, -1);
6963}
6964
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006965/* fd: redirect wants this fd to be used (e.g. 3>file).
6966 * Move all conflicting internally used fds,
6967 * and remember them so that we can restore them later.
6968 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006969static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006970{
Denys Vlasenko2db74612017-07-07 22:07:28 +02006971 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6972 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006973
6974#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006975 if (fd == G.interactive_fd) {
6976 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006977 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006978 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6979 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006980 }
6981#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006982 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6983 * (1) Redirect in a forked child. No need to save FILEs' fds,
6984 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02006985 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6986 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006987 * "fileno(fd) = new_fd" can't be done.
6988 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02006989 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006990 return 0;
6991
Denys Vlasenko2db74612017-07-07 22:07:28 +02006992 /* If this one of script's fds? */
6993 if (save_FILEs_on_redirect(fd, avoid_fd))
6994 return 1; /* yes. "we closed fd" */
6995
6996 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6997 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6998 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006999}
7000
Denys Vlasenko2db74612017-07-07 22:07:28 +02007001static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007002{
Denys Vlasenko2db74612017-07-07 22:07:28 +02007003 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007004 int i;
7005 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02007006 if (sq[i].moved_to >= 0) {
7007 /* We simply die on error */
7008 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
7009 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
7010 } else {
7011 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
7012 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
7013 close(sq[i].orig_fd);
7014 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007015 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02007016 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007017 }
7018
Denys Vlasenko2db74612017-07-07 22:07:28 +02007019 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02007020
7021 restore_redirected_FILEs();
7022}
7023
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007024#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007025static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007026{
7027 if (G_interactive_fd)
7028 close(G_interactive_fd);
7029 close_all_FILE_list();
7030}
7031#endif
7032
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007033static int internally_opened_fd(int fd, struct squirrel *sq)
7034{
7035 int i;
7036
7037#if ENABLE_HUSH_INTERACTIVE
7038 if (fd == G.interactive_fd)
7039 return 1;
7040#endif
7041 /* If this one of script's fds? */
7042 if (fd_in_FILEs(fd))
7043 return 1;
7044
7045 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7046 if (fd == sq[i].moved_to)
7047 return 1;
7048 }
7049 return 0;
7050}
7051
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007052/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7053 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007054static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007055{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007056 struct redir_struct *redir;
7057
7058 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007059 int newfd;
7060 int closed;
7061
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007062 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007063 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007064 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007065 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7066 * of the heredoc */
7067 debug_printf_parse("set heredoc '%s'\n",
7068 redir->rd_filename);
7069 setup_heredoc(redir);
7070 continue;
7071 }
7072
7073 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007074 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007075 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007076 int mode;
7077
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007078 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007079 /*
7080 * Examples:
7081 * "cmd >" (no filename)
7082 * "cmd > <file" (2nd redirect starts too early)
7083 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007084 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007085 continue;
7086 }
7087 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007088 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007089 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007090 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007091 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007092 /* Error message from open_or_warn can be lost
7093 * if stderr has been redirected, but bash
7094 * and ash both lose it as well
7095 * (though zsh doesn't!)
7096 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007097 return 1;
7098 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007099 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007100 /* open() gave us precisely the fd we wanted.
7101 * This means that this fd was not busy
7102 * (not opened to anywhere).
7103 * Remember to close it on restore:
7104 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007105 *sqp = add_squirrel_closed(*sqp, newfd);
7106 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007107 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007108 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007109 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7110 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007111 }
7112
Denys Vlasenko657e9002017-07-30 23:34:04 +02007113 if (newfd == redir->rd_fd)
7114 continue;
7115
7116 /* if "N>FILE": move newfd to redir->rd_fd */
7117 /* if "N>&M": dup newfd to redir->rd_fd */
7118 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7119
7120 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7121 if (newfd == REDIRFD_CLOSE) {
7122 /* "N>&-" means "close me" */
7123 if (!closed) {
7124 /* ^^^ optimization: saving may already
7125 * have closed it. If not... */
7126 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007127 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007128 /* Sometimes we do another close on restore, getting EBADF.
7129 * Consider "echo 3>FILE 3>&-"
7130 * first redirect remembers "need to close 3",
7131 * and second redirect closes 3! Restore code then closes 3 again.
7132 */
7133 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007134 /* if newfd is a script fd or saved fd, simulate EBADF */
7135 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7136 //errno = EBADF;
7137 //bb_perror_msg_and_die("can't duplicate file descriptor");
7138 newfd = -1; /* same effect as code above */
7139 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007140 xdup2(newfd, redir->rd_fd);
7141 if (redir->rd_dup == REDIRFD_TO_FILE)
7142 /* "rd_fd > FILE" */
7143 close(newfd);
7144 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007145 }
7146 }
7147 return 0;
7148}
7149
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007150static char *find_in_path(const char *arg)
7151{
7152 char *ret = NULL;
7153 const char *PATH = get_local_var_value("PATH");
7154
7155 if (!PATH)
7156 return NULL;
7157
7158 while (1) {
7159 const char *end = strchrnul(PATH, ':');
7160 int sz = end - PATH; /* must be int! */
7161
7162 free(ret);
7163 if (sz != 0) {
7164 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7165 } else {
7166 /* We have xxx::yyyy in $PATH,
7167 * it means "use current dir" */
7168 ret = xstrdup(arg);
7169 }
7170 if (access(ret, F_OK) == 0)
7171 break;
7172
7173 if (*end == '\0') {
7174 free(ret);
7175 return NULL;
7176 }
7177 PATH = end + 1;
7178 }
7179
7180 return ret;
7181}
7182
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007183static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007184 const struct built_in_command *x,
7185 const struct built_in_command *end)
7186{
7187 while (x != end) {
7188 if (strcmp(name, x->b_cmd) != 0) {
7189 x++;
7190 continue;
7191 }
7192 debug_printf_exec("found builtin '%s'\n", name);
7193 return x;
7194 }
7195 return NULL;
7196}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007197static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007198{
7199 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7200}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007201static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007202{
7203 const struct built_in_command *x = find_builtin1(name);
7204 if (x)
7205 return x;
7206 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7207}
7208
7209#if ENABLE_HUSH_FUNCTIONS
7210static struct function **find_function_slot(const char *name)
7211{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007212 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007213 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007214
7215 while ((funcp = *funcpp) != NULL) {
7216 if (strcmp(name, funcp->name) == 0) {
7217 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007218 break;
7219 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007220 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007221 }
7222 return funcpp;
7223}
7224
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007225static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007226{
7227 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007228 return funcp;
7229}
7230
7231/* Note: takes ownership on name ptr */
7232static struct function *new_function(char *name)
7233{
7234 struct function **funcpp = find_function_slot(name);
7235 struct function *funcp = *funcpp;
7236
7237 if (funcp != NULL) {
7238 struct command *cmd = funcp->parent_cmd;
7239 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7240 if (!cmd) {
7241 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7242 free(funcp->name);
7243 /* Note: if !funcp->body, do not free body_as_string!
7244 * This is a special case of "-F name body" function:
7245 * body_as_string was not malloced! */
7246 if (funcp->body) {
7247 free_pipe_list(funcp->body);
7248# if !BB_MMU
7249 free(funcp->body_as_string);
7250# endif
7251 }
7252 } else {
7253 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7254 cmd->argv[0] = funcp->name;
7255 cmd->group = funcp->body;
7256# if !BB_MMU
7257 cmd->group_as_string = funcp->body_as_string;
7258# endif
7259 }
7260 } else {
7261 debug_printf_exec("remembering new function '%s'\n", name);
7262 funcp = *funcpp = xzalloc(sizeof(*funcp));
7263 /*funcp->next = NULL;*/
7264 }
7265
7266 funcp->name = name;
7267 return funcp;
7268}
7269
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007270# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007271static void unset_func(const char *name)
7272{
7273 struct function **funcpp = find_function_slot(name);
7274 struct function *funcp = *funcpp;
7275
7276 if (funcp != NULL) {
7277 debug_printf_exec("freeing function '%s'\n", funcp->name);
7278 *funcpp = funcp->next;
7279 /* funcp is unlinked now, deleting it.
7280 * Note: if !funcp->body, the function was created by
7281 * "-F name body", do not free ->body_as_string
7282 * and ->name as they were not malloced. */
7283 if (funcp->body) {
7284 free_pipe_list(funcp->body);
7285 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007286# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007287 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007288# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007289 }
7290 free(funcp);
7291 }
7292}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007293# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007294
7295# if BB_MMU
7296#define exec_function(to_free, funcp, argv) \
7297 exec_function(funcp, argv)
7298# endif
7299static void exec_function(char ***to_free,
7300 const struct function *funcp,
7301 char **argv) NORETURN;
7302static void exec_function(char ***to_free,
7303 const struct function *funcp,
7304 char **argv)
7305{
7306# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007307 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007308
7309 argv[0] = G.global_argv[0];
7310 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007311 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007312
7313// Example when we are here: "cmd | func"
7314// func will run with saved-redirect fds open.
7315// $ f() { echo /proc/self/fd/*; }
7316// $ true | f
7317// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7318// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7319// Same in script:
7320// $ . ./SCRIPT
7321// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7322// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7323// They are CLOEXEC so external programs won't see them, but
7324// for "more correctness" we might want to close those extra fds here:
7325//? close_saved_fds_and_FILE_fds();
7326
7327 /* "we are in function, ok to use return" */
7328 G_flag_return_in_progress = -1;
7329 IF_HUSH_LOCAL(G.func_nest_level++;)
7330
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007331 /* On MMU, funcp->body is always non-NULL */
7332 n = run_list(funcp->body);
7333 fflush_all();
7334 _exit(n);
7335# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007336//? close_saved_fds_and_FILE_fds();
7337
7338//TODO: check whether "true | func_with_return" works
7339
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007340 re_execute_shell(to_free,
7341 funcp->body_as_string,
7342 G.global_argv[0],
7343 argv + 1,
7344 NULL);
7345# endif
7346}
7347
7348static int run_function(const struct function *funcp, char **argv)
7349{
7350 int rc;
7351 save_arg_t sv;
7352 smallint sv_flg;
7353
7354 save_and_replace_G_args(&sv, argv);
7355
7356 /* "we are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007357 sv_flg = G_flag_return_in_progress;
7358 G_flag_return_in_progress = -1;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007359 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007360
7361 /* On MMU, funcp->body is always non-NULL */
7362# if !BB_MMU
7363 if (!funcp->body) {
7364 /* Function defined by -F */
7365 parse_and_run_string(funcp->body_as_string);
7366 rc = G.last_exitcode;
7367 } else
7368# endif
7369 {
7370 rc = run_list(funcp->body);
7371 }
7372
7373# if ENABLE_HUSH_LOCAL
7374 {
7375 struct variable *var;
7376 struct variable **var_pp;
7377
7378 var_pp = &G.top_var;
7379 while ((var = *var_pp) != NULL) {
7380 if (var->func_nest_level < G.func_nest_level) {
7381 var_pp = &var->next;
7382 continue;
7383 }
7384 /* Unexport */
7385 if (var->flg_export)
7386 bb_unsetenv(var->varstr);
7387 /* Remove from global list */
7388 *var_pp = var->next;
7389 /* Free */
7390 if (!var->max_len)
7391 free(var->varstr);
7392 free(var);
7393 }
7394 G.func_nest_level--;
7395 }
7396# endif
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007397 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007398
7399 restore_G_args(&sv, argv);
7400
7401 return rc;
7402}
7403#endif /* ENABLE_HUSH_FUNCTIONS */
7404
7405
7406#if BB_MMU
7407#define exec_builtin(to_free, x, argv) \
7408 exec_builtin(x, argv)
7409#else
7410#define exec_builtin(to_free, x, argv) \
7411 exec_builtin(to_free, argv)
7412#endif
7413static void exec_builtin(char ***to_free,
7414 const struct built_in_command *x,
7415 char **argv) NORETURN;
7416static void exec_builtin(char ***to_free,
7417 const struct built_in_command *x,
7418 char **argv)
7419{
7420#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007421 int rcode;
7422 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007423//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007424 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007425 fflush_all();
7426 _exit(rcode);
7427#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007428 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007429 /* On NOMMU, we must never block!
7430 * Example: { sleep 99 | read line; } & echo Ok
7431 */
7432 re_execute_shell(to_free,
7433 argv[0],
7434 G.global_argv[0],
7435 G.global_argv + 1,
7436 argv);
7437#endif
7438}
7439
7440
7441static void execvp_or_die(char **argv) NORETURN;
7442static void execvp_or_die(char **argv)
7443{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007444 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007445 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007446 /* Don't propagate SIG_IGN to the child */
7447 if (SPECIAL_JOBSTOP_SIGS != 0)
7448 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007449 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007450 e = 2;
7451 if (errno == EACCES) e = 126;
7452 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007453 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007454 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007455}
7456
7457#if ENABLE_HUSH_MODE_X
7458static void dump_cmd_in_x_mode(char **argv)
7459{
7460 if (G_x_mode && argv) {
7461 /* We want to output the line in one write op */
7462 char *buf, *p;
7463 int len;
7464 int n;
7465
7466 len = 3;
7467 n = 0;
7468 while (argv[n])
7469 len += strlen(argv[n++]) + 1;
7470 buf = xmalloc(len);
7471 buf[0] = '+';
7472 p = buf + 1;
7473 n = 0;
7474 while (argv[n])
7475 p += sprintf(p, " %s", argv[n++]);
7476 *p++ = '\n';
7477 *p = '\0';
7478 fputs(buf, stderr);
7479 free(buf);
7480 }
7481}
7482#else
7483# define dump_cmd_in_x_mode(argv) ((void)0)
7484#endif
7485
Denys Vlasenko57000292018-01-12 14:41:45 +01007486#if ENABLE_HUSH_COMMAND
7487static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7488{
7489 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007490
Denys Vlasenko57000292018-01-12 14:41:45 +01007491 if (!opt_vV)
7492 return;
7493
7494 to_free = NULL;
7495 if (!explanation) {
7496 char *path = getenv("PATH");
7497 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007498 if (!explanation)
7499 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007500 if (opt_vV != 'V')
7501 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7502 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007503 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007504 free(to_free);
7505 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007506 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007507}
7508#else
7509# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7510#endif
7511
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007512#if BB_MMU
7513#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7514 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7515#define pseudo_exec(nommu_save, command, argv_expanded) \
7516 pseudo_exec(command, argv_expanded)
7517#endif
7518
7519/* Called after [v]fork() in run_pipe, or from builtin_exec.
7520 * Never returns.
7521 * Don't exit() here. If you don't exec, use _exit instead.
7522 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007523 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007524 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007525static void pseudo_exec_argv(nommu_save_t *nommu_save,
7526 char **argv, int assignment_cnt,
7527 char **argv_expanded) NORETURN;
7528static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7529 char **argv, int assignment_cnt,
7530 char **argv_expanded)
7531{
Denys Vlasenko57000292018-01-12 14:41:45 +01007532 const struct built_in_command *x;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007533 char **new_env;
Denys Vlasenko57000292018-01-12 14:41:45 +01007534#if ENABLE_HUSH_COMMAND
7535 char opt_vV = 0;
7536#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007537
7538 new_env = expand_assignments(argv, assignment_cnt);
7539 dump_cmd_in_x_mode(new_env);
7540
7541 if (!argv[assignment_cnt]) {
7542 /* Case when we are here: ... | var=val | ...
7543 * (note that we do not exit early, i.e., do not optimize out
7544 * expand_assignments(): think about ... | var=`sleep 1` | ...
7545 */
7546 free_strings(new_env);
7547 _exit(EXIT_SUCCESS);
7548 }
7549
7550#if BB_MMU
7551 set_vars_and_save_old(new_env);
7552 free(new_env); /* optional */
7553 /* we can also destroy set_vars_and_save_old's return value,
7554 * to save memory */
7555#else
7556 nommu_save->new_env = new_env;
7557 nommu_save->old_vars = set_vars_and_save_old(new_env);
7558#endif
7559
7560 if (argv_expanded) {
7561 argv = argv_expanded;
7562 } else {
7563 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7564#if !BB_MMU
7565 nommu_save->argv = argv;
7566#endif
7567 }
7568 dump_cmd_in_x_mode(argv);
7569
7570#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7571 if (strchr(argv[0], '/') != NULL)
7572 goto skip;
7573#endif
7574
Denys Vlasenko75481d32017-07-31 05:27:09 +02007575#if ENABLE_HUSH_FUNCTIONS
7576 /* Check if the command matches any functions (this goes before bltins) */
7577 {
7578 const struct function *funcp = find_function(argv[0]);
7579 if (funcp) {
7580 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7581 }
7582 }
7583#endif
7584
Denys Vlasenko57000292018-01-12 14:41:45 +01007585#if ENABLE_HUSH_COMMAND
7586 /* "command BAR": run BAR without looking it up among functions
7587 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7588 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7589 */
7590 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7591 char *p;
7592
7593 argv++;
7594 p = *argv;
7595 if (p[0] != '-' || !p[1])
7596 continue; /* bash allows "command command command [-OPT] BAR" */
7597
7598 for (;;) {
7599 p++;
7600 switch (*p) {
7601 case '\0':
7602 argv++;
7603 p = *argv;
7604 if (p[0] != '-' || !p[1])
7605 goto after_opts;
7606 continue; /* next arg is also -opts, process it too */
7607 case 'v':
7608 case 'V':
7609 opt_vV = *p;
7610 continue;
7611 default:
7612 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7613 }
7614 }
7615 }
7616 after_opts:
7617# if ENABLE_HUSH_FUNCTIONS
7618 if (opt_vV && find_function(argv[0]))
7619 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7620# endif
7621#endif
7622
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007623 /* Check if the command matches any of the builtins.
7624 * Depending on context, this might be redundant. But it's
7625 * easier to waste a few CPU cycles than it is to figure out
7626 * if this is one of those cases.
7627 */
Denys Vlasenko57000292018-01-12 14:41:45 +01007628 /* Why "BB_MMU ? :" difference in logic? -
7629 * On NOMMU, it is more expensive to re-execute shell
7630 * just in order to run echo or test builtin.
7631 * It's better to skip it here and run corresponding
7632 * non-builtin later. */
7633 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7634 if (x) {
7635 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7636 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007637 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007638
7639#if ENABLE_FEATURE_SH_STANDALONE
7640 /* Check if the command matches any busybox applets */
7641 {
7642 int a = find_applet_by_name(argv[0]);
7643 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01007644 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007645# if BB_MMU /* see above why on NOMMU it is not allowed */
7646 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007647 /* Do not leak open fds from opened script files etc.
7648 * Testcase: interactive "ls -l /proc/self/fd"
7649 * should not show tty fd open.
7650 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007651 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007652//FIXME: should also close saved redir fds
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02007653//This casuses test failures in
7654//redir_children_should_not_see_saved_fd_2.tests
7655//redir_children_should_not_see_saved_fd_3.tests
7656//if you replace "busybox find" with just "find" in them
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007657 /* Without this, "rm -i FILE" can't be ^C'ed: */
7658 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007659 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007660 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007661 }
7662# endif
7663 /* Re-exec ourselves */
7664 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007665 /* Don't propagate SIG_IGN to the child */
7666 if (SPECIAL_JOBSTOP_SIGS != 0)
7667 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007668 execv(bb_busybox_exec_path, argv);
7669 /* If they called chroot or otherwise made the binary no longer
7670 * executable, fall through */
7671 }
7672 }
7673#endif
7674
7675#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7676 skip:
7677#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01007678 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007679 execvp_or_die(argv);
7680}
7681
7682/* Called after [v]fork() in run_pipe
7683 */
7684static void pseudo_exec(nommu_save_t *nommu_save,
7685 struct command *command,
7686 char **argv_expanded) NORETURN;
7687static void pseudo_exec(nommu_save_t *nommu_save,
7688 struct command *command,
7689 char **argv_expanded)
7690{
7691 if (command->argv) {
7692 pseudo_exec_argv(nommu_save, command->argv,
7693 command->assignment_cnt, argv_expanded);
7694 }
7695
7696 if (command->group) {
7697 /* Cases when we are here:
7698 * ( list )
7699 * { list } &
7700 * ... | ( list ) | ...
7701 * ... | { list } | ...
7702 */
7703#if BB_MMU
7704 int rcode;
7705 debug_printf_exec("pseudo_exec: run_list\n");
7706 reset_traps_to_defaults();
7707 rcode = run_list(command->group);
7708 /* OK to leak memory by not calling free_pipe_list,
7709 * since this process is about to exit */
7710 _exit(rcode);
7711#else
7712 re_execute_shell(&nommu_save->argv_from_re_execing,
7713 command->group_as_string,
7714 G.global_argv[0],
7715 G.global_argv + 1,
7716 NULL);
7717#endif
7718 }
7719
7720 /* Case when we are here: ... | >file */
7721 debug_printf_exec("pseudo_exec'ed null command\n");
7722 _exit(EXIT_SUCCESS);
7723}
7724
7725#if ENABLE_HUSH_JOB
7726static const char *get_cmdtext(struct pipe *pi)
7727{
7728 char **argv;
7729 char *p;
7730 int len;
7731
7732 /* This is subtle. ->cmdtext is created only on first backgrounding.
7733 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7734 * On subsequent bg argv is trashed, but we won't use it */
7735 if (pi->cmdtext)
7736 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007737
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007738 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007739 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007740 pi->cmdtext = xzalloc(1);
7741 return pi->cmdtext;
7742 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007743 len = 0;
7744 do {
7745 len += strlen(*argv) + 1;
7746 } while (*++argv);
7747 p = xmalloc(len);
7748 pi->cmdtext = p;
7749 argv = pi->cmds[0].argv;
7750 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007751 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007752 *p++ = ' ';
7753 } while (*++argv);
7754 p[-1] = '\0';
7755 return pi->cmdtext;
7756}
7757
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007758static void remove_job_from_table(struct pipe *pi)
7759{
7760 struct pipe *prev_pipe;
7761
7762 if (pi == G.job_list) {
7763 G.job_list = pi->next;
7764 } else {
7765 prev_pipe = G.job_list;
7766 while (prev_pipe->next != pi)
7767 prev_pipe = prev_pipe->next;
7768 prev_pipe->next = pi->next;
7769 }
7770 G.last_jobid = 0;
7771 if (G.job_list)
7772 G.last_jobid = G.job_list->jobid;
7773}
7774
7775static void delete_finished_job(struct pipe *pi)
7776{
7777 remove_job_from_table(pi);
7778 free_pipe(pi);
7779}
7780
7781static void clean_up_last_dead_job(void)
7782{
7783 if (G.job_list && !G.job_list->alive_cmds)
7784 delete_finished_job(G.job_list);
7785}
7786
Denys Vlasenko16096292017-07-10 10:00:28 +02007787static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007788{
7789 struct pipe *job, **jobp;
7790 int i;
7791
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007792 clean_up_last_dead_job();
7793
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007794 /* Find the end of the list, and find next job ID to use */
7795 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007796 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007797 while ((job = *jobp) != NULL) {
7798 if (job->jobid > i)
7799 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007800 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007801 }
7802 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007803
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007804 /* Create a new job struct at the end */
7805 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007806 job->next = NULL;
7807 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7808 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7809 for (i = 0; i < pi->num_cmds; i++) {
7810 job->cmds[i].pid = pi->cmds[i].pid;
7811 /* all other fields are not used and stay zero */
7812 }
7813 job->cmdtext = xstrdup(get_cmdtext(pi));
7814
7815 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007816 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007817 G.last_jobid = job->jobid;
7818}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007819#endif /* JOB */
7820
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007821static int job_exited_or_stopped(struct pipe *pi)
7822{
7823 int rcode, i;
7824
7825 if (pi->alive_cmds != pi->stopped_cmds)
7826 return -1;
7827
7828 /* All processes in fg pipe have exited or stopped */
7829 rcode = 0;
7830 i = pi->num_cmds;
7831 while (--i >= 0) {
7832 rcode = pi->cmds[i].cmd_exitcode;
7833 /* usually last process gives overall exitstatus,
7834 * but with "set -o pipefail", last *failed* process does */
7835 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7836 break;
7837 }
7838 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7839 return rcode;
7840}
7841
Denys Vlasenko7e675362016-10-28 21:57:31 +02007842static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007843{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007844#if ENABLE_HUSH_JOB
7845 struct pipe *pi;
7846#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007847 int i, dead;
7848
7849 dead = WIFEXITED(status) || WIFSIGNALED(status);
7850
7851#if DEBUG_JOBS
7852 if (WIFSTOPPED(status))
7853 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7854 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7855 if (WIFSIGNALED(status))
7856 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7857 childpid, WTERMSIG(status), WEXITSTATUS(status));
7858 if (WIFEXITED(status))
7859 debug_printf_jobs("pid %d exited, exitcode %d\n",
7860 childpid, WEXITSTATUS(status));
7861#endif
7862 /* Were we asked to wait for a fg pipe? */
7863 if (fg_pipe) {
7864 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007865
Denys Vlasenko7e675362016-10-28 21:57:31 +02007866 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007867 int rcode;
7868
Denys Vlasenko7e675362016-10-28 21:57:31 +02007869 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7870 if (fg_pipe->cmds[i].pid != childpid)
7871 continue;
7872 if (dead) {
7873 int ex;
7874 fg_pipe->cmds[i].pid = 0;
7875 fg_pipe->alive_cmds--;
7876 ex = WEXITSTATUS(status);
7877 /* bash prints killer signal's name for *last*
7878 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7879 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7880 */
7881 if (WIFSIGNALED(status)) {
7882 int sig = WTERMSIG(status);
7883 if (i == fg_pipe->num_cmds-1)
7884 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7885 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7886 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7887 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7888 * Maybe we need to use sig | 128? */
7889 ex = sig + 128;
7890 }
7891 fg_pipe->cmds[i].cmd_exitcode = ex;
7892 } else {
7893 fg_pipe->stopped_cmds++;
7894 }
7895 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7896 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007897 rcode = job_exited_or_stopped(fg_pipe);
7898 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007899/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7900 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7901 * and "killall -STOP cat" */
7902 if (G_interactive_fd) {
7903#if ENABLE_HUSH_JOB
7904 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02007905 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007906#endif
7907 return rcode;
7908 }
7909 if (fg_pipe->alive_cmds == 0)
7910 return rcode;
7911 }
7912 /* There are still running processes in the fg_pipe */
7913 return -1;
7914 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02007915 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02007916 }
7917
7918#if ENABLE_HUSH_JOB
7919 /* We were asked to wait for bg or orphaned children */
7920 /* No need to remember exitcode in this case */
7921 for (pi = G.job_list; pi; pi = pi->next) {
7922 for (i = 0; i < pi->num_cmds; i++) {
7923 if (pi->cmds[i].pid == childpid)
7924 goto found_pi_and_prognum;
7925 }
7926 }
7927 /* Happens when shell is used as init process (init=/bin/sh) */
7928 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7929 return -1; /* this wasn't a process from fg_pipe */
7930
7931 found_pi_and_prognum:
7932 if (dead) {
7933 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02007934 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007935 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02007936 rcode = 128 + WTERMSIG(status);
7937 pi->cmds[i].cmd_exitcode = rcode;
7938 if (G.last_bg_pid == pi->cmds[i].pid)
7939 G.last_bg_pid_exitcode = rcode;
7940 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007941 pi->alive_cmds--;
7942 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007943 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007944 printf(JOB_STATUS_FORMAT, pi->jobid,
7945 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007946 delete_finished_job(pi);
7947 } else {
7948/*
7949 * bash deletes finished jobs from job table only in interactive mode,
7950 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7951 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7952 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7953 * We only retain one "dead" job, if it's the single job on the list.
7954 * This covers most of real-world scenarios where this is useful.
7955 */
7956 if (pi != G.job_list)
7957 delete_finished_job(pi);
7958 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007959 }
7960 } else {
7961 /* child stopped */
7962 pi->stopped_cmds++;
7963 }
7964#endif
7965 return -1; /* this wasn't a process from fg_pipe */
7966}
7967
7968/* Check to see if any processes have exited -- if they have,
7969 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007970 *
7971 * If non-NULL fg_pipe: wait for its completion or stop.
7972 * Return its exitcode or zero if stopped.
7973 *
7974 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7975 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7976 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7977 * or 0 if no children changed status.
7978 *
7979 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7980 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7981 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02007982 */
7983static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7984{
7985 int attributes;
7986 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007987 int rcode = 0;
7988
7989 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7990
7991 attributes = WUNTRACED;
7992 if (fg_pipe == NULL)
7993 attributes |= WNOHANG;
7994
7995 errno = 0;
7996#if ENABLE_HUSH_FAST
7997 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7998//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7999//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
8000 /* There was neither fork nor SIGCHLD since last waitpid */
8001 /* Avoid doing waitpid syscall if possible */
8002 if (!G.we_have_children) {
8003 errno = ECHILD;
8004 return -1;
8005 }
8006 if (fg_pipe == NULL) { /* is WNOHANG set? */
8007 /* We have children, but they did not exit
8008 * or stop yet (we saw no SIGCHLD) */
8009 return 0;
8010 }
8011 /* else: !WNOHANG, waitpid will block, can't short-circuit */
8012 }
8013#endif
8014
8015/* Do we do this right?
8016 * bash-3.00# sleep 20 | false
8017 * <ctrl-Z pressed>
8018 * [3]+ Stopped sleep 20 | false
8019 * bash-3.00# echo $?
8020 * 1 <========== bg pipe is not fully done, but exitcode is already known!
8021 * [hush 1.14.0: yes we do it right]
8022 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008023 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008024 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008025#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02008026 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008027 i = G.count_SIGCHLD;
8028#endif
8029 childpid = waitpid(-1, &status, attributes);
8030 if (childpid <= 0) {
8031 if (childpid && errno != ECHILD)
8032 bb_perror_msg("waitpid");
8033#if ENABLE_HUSH_FAST
8034 else { /* Until next SIGCHLD, waitpid's are useless */
8035 G.we_have_children = (childpid == 0);
8036 G.handled_SIGCHLD = i;
8037//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8038 }
8039#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008040 /* ECHILD (no children), or 0 (no change in children status) */
8041 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008042 break;
8043 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008044 rcode = process_wait_result(fg_pipe, childpid, status);
8045 if (rcode >= 0) {
8046 /* fg_pipe exited or stopped */
8047 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008048 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008049 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008050 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008051 rcode = WEXITSTATUS(status);
8052 if (WIFSIGNALED(status))
8053 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008054 if (WIFSTOPPED(status))
8055 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8056 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008057 rcode++;
8058 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008059 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008060 /* This wasn't one of our processes, or */
8061 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008062 } /* while (waitpid succeeds)... */
8063
8064 return rcode;
8065}
8066
8067#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008068static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008069{
8070 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008071 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008072 if (G_saved_tty_pgrp) {
8073 /* Job finished, move the shell to the foreground */
8074 p = getpgrp(); /* our process group id */
8075 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8076 tcsetpgrp(G_interactive_fd, p);
8077 }
8078 return rcode;
8079}
8080#endif
8081
8082/* Start all the jobs, but don't wait for anything to finish.
8083 * See checkjobs().
8084 *
8085 * Return code is normally -1, when the caller has to wait for children
8086 * to finish to determine the exit status of the pipe. If the pipe
8087 * is a simple builtin command, however, the action is done by the
8088 * time run_pipe returns, and the exit code is provided as the
8089 * return value.
8090 *
8091 * Returns -1 only if started some children. IOW: we have to
8092 * mask out retvals of builtins etc with 0xff!
8093 *
8094 * The only case when we do not need to [v]fork is when the pipe
8095 * is single, non-backgrounded, non-subshell command. Examples:
8096 * cmd ; ... { list } ; ...
8097 * cmd && ... { list } && ...
8098 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008099 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008100 * or (if SH_STANDALONE) an applet, and we can run the { list }
8101 * with run_list. If it isn't one of these, we fork and exec cmd.
8102 *
8103 * Cases when we must fork:
8104 * non-single: cmd | cmd
8105 * backgrounded: cmd & { list } &
8106 * subshell: ( list ) [&]
8107 */
8108#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01008109#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008110 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
8111#endif
8112static int redirect_and_varexp_helper(char ***new_env_p,
8113 struct variable **old_vars_p,
8114 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008115 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008116 char **argv_expanded)
8117{
8118 /* setup_redirects acts on file descriptors, not FILEs.
8119 * This is perfect for work that comes after exec().
8120 * Is it really safe for inline use? Experimentally,
8121 * things seem to work. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008122 int rcode = setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008123 if (rcode == 0) {
8124 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8125 *new_env_p = new_env;
8126 dump_cmd_in_x_mode(new_env);
8127 dump_cmd_in_x_mode(argv_expanded);
8128 if (old_vars_p)
8129 *old_vars_p = set_vars_and_save_old(new_env);
8130 }
8131 return rcode;
8132}
8133static NOINLINE int run_pipe(struct pipe *pi)
8134{
8135 static const char *const null_ptr = NULL;
8136
8137 int cmd_no;
8138 int next_infd;
8139 struct command *command;
8140 char **argv_expanded;
8141 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008142 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008143 int rcode;
8144
8145 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8146 debug_enter();
8147
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008148 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8149 * Result should be 3 lines: q w e, qwe, q w e
8150 */
8151 G.ifs = get_local_var_value("IFS");
8152 if (!G.ifs)
8153 G.ifs = defifs;
8154
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008155 IF_HUSH_JOB(pi->pgrp = -1;)
8156 pi->stopped_cmds = 0;
8157 command = &pi->cmds[0];
8158 argv_expanded = NULL;
8159
8160 if (pi->num_cmds != 1
8161 || pi->followup == PIPE_BG
8162 || command->cmd_type == CMD_SUBSHELL
8163 ) {
8164 goto must_fork;
8165 }
8166
8167 pi->alive_cmds = 1;
8168
8169 debug_printf_exec(": group:%p argv:'%s'\n",
8170 command->group, command->argv ? command->argv[0] : "NONE");
8171
8172 if (command->group) {
8173#if ENABLE_HUSH_FUNCTIONS
8174 if (command->cmd_type == CMD_FUNCDEF) {
8175 /* "executing" func () { list } */
8176 struct function *funcp;
8177
8178 funcp = new_function(command->argv[0]);
8179 /* funcp->name is already set to argv[0] */
8180 funcp->body = command->group;
8181# if !BB_MMU
8182 funcp->body_as_string = command->group_as_string;
8183 command->group_as_string = NULL;
8184# endif
8185 command->group = NULL;
8186 command->argv[0] = NULL;
8187 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8188 funcp->parent_cmd = command;
8189 command->child_func = funcp;
8190
8191 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8192 debug_leave();
8193 return EXIT_SUCCESS;
8194 }
8195#endif
8196 /* { list } */
8197 debug_printf("non-subshell group\n");
8198 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008199 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008200 debug_printf_exec(": run_list\n");
Denys Vlasenkod1b84572018-03-28 18:42:54 +02008201//FIXME: we need to pass squirrel down into run_list()
8202//for SH_STANDALONE case, or else this construct:
8203// { find /proc/self/fd; true; } >FILE; cmd2
8204//has no way of closing saved fd#1 for "find",
8205//and in SH_STANDALONE mode, "find" is not execed,
8206//therefore CLOEXEC on saved fd does not help.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008207 rcode = run_list(command->group) & 0xff;
8208 }
8209 restore_redirects(squirrel);
8210 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8211 debug_leave();
8212 debug_printf_exec("run_pipe: return %d\n", rcode);
8213 return rcode;
8214 }
8215
8216 argv = command->argv ? command->argv : (char **) &null_ptr;
8217 {
8218 const struct built_in_command *x;
8219#if ENABLE_HUSH_FUNCTIONS
8220 const struct function *funcp;
8221#else
8222 enum { funcp = 0 };
8223#endif
8224 char **new_env = NULL;
8225 struct variable *old_vars = NULL;
8226
Denys Vlasenko5807e182018-02-08 19:19:04 +01008227#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008228 if (G.lineno_var)
8229 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8230#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008231
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008232 if (argv[command->assignment_cnt] == NULL) {
8233 /* Assignments, but no command */
8234 /* Ensure redirects take effect (that is, create files).
8235 * Try "a=t >file" */
8236#if 0 /* A few cases in testsuite fail with this code. FIXME */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008237 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008238 /* Set shell variables */
8239 if (new_env) {
8240 argv = new_env;
8241 while (*argv) {
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008242 if (set_local_var(*argv, /*flag:*/ 0)) {
8243 /* assignment to readonly var / putenv error? */
8244 rcode = 1;
8245 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008246 argv++;
8247 }
8248 }
8249 /* Redirect error sets $? to 1. Otherwise,
8250 * if evaluating assignment value set $?, retain it.
8251 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8252 if (rcode == 0)
8253 rcode = G.last_exitcode;
8254 /* Exit, _skipping_ variable restoring code: */
8255 goto clean_up_and_ret0;
8256
8257#else /* Older, bigger, but more correct code */
8258
Denys Vlasenko2db74612017-07-07 22:07:28 +02008259 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008260 restore_redirects(squirrel);
8261 /* Set shell variables */
8262 if (G_x_mode)
8263 bb_putchar_stderr('+');
8264 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02008265 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008266 if (G_x_mode)
8267 fprintf(stderr, " %s", p);
8268 debug_printf_exec("set shell var:'%s'->'%s'\n",
8269 *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008270 if (set_local_var(p, /*flag:*/ 0)) {
8271 /* assignment to readonly var / putenv error? */
8272 rcode = 1;
8273 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008274 argv++;
8275 }
8276 if (G_x_mode)
8277 bb_putchar_stderr('\n');
8278 /* Redirect error sets $? to 1. Otherwise,
8279 * if evaluating assignment value set $?, retain it.
8280 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8281 if (rcode == 0)
8282 rcode = G.last_exitcode;
8283 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8284 debug_leave();
8285 debug_printf_exec("run_pipe: return %d\n", rcode);
8286 return rcode;
8287#endif
8288 }
8289
8290 /* Expand the rest into (possibly) many strings each */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01008291#if BASH_TEST2
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008292 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008293 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008294 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008295#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008296 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008297 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8298 }
8299
8300 /* if someone gives us an empty string: `cmd with empty output` */
8301 if (!argv_expanded[0]) {
8302 free(argv_expanded);
8303 debug_leave();
8304 return G.last_exitcode;
8305 }
8306
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008307#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko75481d32017-07-31 05:27:09 +02008308 /* Check if argv[0] matches any functions (this goes before bltins) */
8309 funcp = find_function(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008310#endif
Denys Vlasenko75481d32017-07-31 05:27:09 +02008311 x = NULL;
8312 if (!funcp)
8313 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008314 if (x || funcp) {
8315 if (!funcp) {
8316 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8317 debug_printf("exec with redirects only\n");
8318 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008319 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008320 goto clean_up_and_ret1;
8321 }
8322 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02008323 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008324 if (rcode == 0) {
8325 if (!funcp) {
8326 debug_printf_exec(": builtin '%s' '%s'...\n",
8327 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008328 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008329 rcode = x->b_function(argv_expanded) & 0xff;
8330 fflush_all();
8331 }
8332#if ENABLE_HUSH_FUNCTIONS
8333 else {
8334# if ENABLE_HUSH_LOCAL
8335 struct variable **sv;
8336 sv = G.shadowed_vars_pp;
8337 G.shadowed_vars_pp = &old_vars;
8338# endif
8339 debug_printf_exec(": function '%s' '%s'...\n",
8340 funcp->name, argv_expanded[1]);
8341 rcode = run_function(funcp, argv_expanded) & 0xff;
8342# if ENABLE_HUSH_LOCAL
8343 G.shadowed_vars_pp = sv;
8344# endif
8345 }
8346#endif
8347 }
8348 clean_up_and_ret:
8349 unset_vars(new_env);
8350 add_vars(old_vars);
8351/* clean_up_and_ret0: */
8352 restore_redirects(squirrel);
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008353 /*
8354 * Try "usleep 99999999" + ^C + "echo $?"
8355 * with FEATURE_SH_NOFORK=y.
8356 */
8357 if (!funcp) {
8358 /* It was builtin or nofork.
8359 * if this would be a real fork/execed program,
8360 * it should have died if a fatal sig was received.
8361 * But OTOH, there was no separate process,
8362 * the sig was sent to _shell_, not to non-existing
8363 * child.
8364 * Let's just handle ^C only, this one is obvious:
8365 * we aren't ok with exitcode 0 when ^C was pressed
8366 * during builtin/nofork.
8367 */
8368 if (sigismember(&G.pending_set, SIGINT))
8369 rcode = 128 + SIGINT;
8370 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008371 clean_up_and_ret1:
8372 free(argv_expanded);
8373 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8374 debug_leave();
8375 debug_printf_exec("run_pipe return %d\n", rcode);
8376 return rcode;
8377 }
8378
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008379 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008380 int n = find_applet_by_name(argv_expanded[0]);
8381 if (n >= 0 && APPLET_IS_NOFORK(n)) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02008382 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008383 if (rcode == 0) {
8384 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8385 argv_expanded[0], argv_expanded[1]);
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008386 /*
8387 * Note: signals (^C) can't interrupt here.
8388 * We remember them and they will be acted upon
8389 * after applet returns.
8390 * This makes applets which can run for a long time
8391 * and/or wait for user input ineligible for NOFORK:
8392 * for example, "yes" or "rm" (rm -i waits for input).
8393 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008394 rcode = run_nofork_applet(n, argv_expanded);
8395 }
8396 goto clean_up_and_ret;
8397 }
8398 }
8399 /* It is neither builtin nor applet. We must fork. */
8400 }
8401
8402 must_fork:
8403 /* NB: argv_expanded may already be created, and that
8404 * might include `cmd` runs! Do not rerun it! We *must*
8405 * use argv_expanded if it's non-NULL */
8406
8407 /* Going to fork a child per each pipe member */
8408 pi->alive_cmds = 0;
8409 next_infd = 0;
8410
8411 cmd_no = 0;
8412 while (cmd_no < pi->num_cmds) {
8413 struct fd_pair pipefds;
8414#if !BB_MMU
8415 volatile nommu_save_t nommu_save;
8416 nommu_save.new_env = NULL;
8417 nommu_save.old_vars = NULL;
8418 nommu_save.argv = NULL;
8419 nommu_save.argv_from_re_execing = NULL;
8420#endif
8421 command = &pi->cmds[cmd_no];
8422 cmd_no++;
8423 if (command->argv) {
8424 debug_printf_exec(": pipe member '%s' '%s'...\n",
8425 command->argv[0], command->argv[1]);
8426 } else {
8427 debug_printf_exec(": pipe member with no argv\n");
8428 }
8429
8430 /* pipes are inserted between pairs of commands */
8431 pipefds.rd = 0;
8432 pipefds.wr = 1;
8433 if (cmd_no < pi->num_cmds)
8434 xpiped_pair(pipefds);
8435
Denys Vlasenko5807e182018-02-08 19:19:04 +01008436#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008437 if (G.lineno_var)
8438 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8439#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008440
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008441 command->pid = BB_MMU ? fork() : vfork();
8442 if (!command->pid) { /* child */
8443#if ENABLE_HUSH_JOB
8444 disable_restore_tty_pgrp_on_exit();
8445 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8446
8447 /* Every child adds itself to new process group
8448 * with pgid == pid_of_first_child_in_pipe */
8449 if (G.run_list_level == 1 && G_interactive_fd) {
8450 pid_t pgrp;
8451 pgrp = pi->pgrp;
8452 if (pgrp < 0) /* true for 1st process only */
8453 pgrp = getpid();
8454 if (setpgid(0, pgrp) == 0
8455 && pi->followup != PIPE_BG
8456 && G_saved_tty_pgrp /* we have ctty */
8457 ) {
8458 /* We do it in *every* child, not just first,
8459 * to avoid races */
8460 tcsetpgrp(G_interactive_fd, pgrp);
8461 }
8462 }
8463#endif
8464 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8465 /* 1st cmd in backgrounded pipe
8466 * should have its stdin /dev/null'ed */
8467 close(0);
8468 if (open(bb_dev_null, O_RDONLY))
8469 xopen("/", O_RDONLY);
8470 } else {
8471 xmove_fd(next_infd, 0);
8472 }
8473 xmove_fd(pipefds.wr, 1);
8474 if (pipefds.rd > 1)
8475 close(pipefds.rd);
8476 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008477 * and the pipe fd (fd#1) is available for dup'ing:
8478 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8479 * of cmd1 goes into pipe.
8480 */
8481 if (setup_redirects(command, NULL)) {
8482 /* Happens when redir file can't be opened:
8483 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8484 * FOO
8485 * hush: can't open '/qwe/rty': No such file or directory
8486 * BAZ
8487 * (echo BAR is not executed, it hits _exit(1) below)
8488 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008489 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008490 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008491
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008492 /* Stores to nommu_save list of env vars putenv'ed
8493 * (NOMMU, on MMU we don't need that) */
8494 /* cast away volatility... */
8495 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8496 /* pseudo_exec() does not return */
8497 }
8498
8499 /* parent or error */
8500#if ENABLE_HUSH_FAST
8501 G.count_SIGCHLD++;
8502//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8503#endif
8504 enable_restore_tty_pgrp_on_exit();
8505#if !BB_MMU
8506 /* Clean up after vforked child */
8507 free(nommu_save.argv);
8508 free(nommu_save.argv_from_re_execing);
8509 unset_vars(nommu_save.new_env);
8510 add_vars(nommu_save.old_vars);
8511#endif
8512 free(argv_expanded);
8513 argv_expanded = NULL;
8514 if (command->pid < 0) { /* [v]fork failed */
8515 /* Clearly indicate, was it fork or vfork */
8516 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8517 } else {
8518 pi->alive_cmds++;
8519#if ENABLE_HUSH_JOB
8520 /* Second and next children need to know pid of first one */
8521 if (pi->pgrp < 0)
8522 pi->pgrp = command->pid;
8523#endif
8524 }
8525
8526 if (cmd_no > 1)
8527 close(next_infd);
8528 if (cmd_no < pi->num_cmds)
8529 close(pipefds.wr);
8530 /* Pass read (output) pipe end to next iteration */
8531 next_infd = pipefds.rd;
8532 }
8533
8534 if (!pi->alive_cmds) {
8535 debug_leave();
8536 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8537 return 1;
8538 }
8539
8540 debug_leave();
8541 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8542 return -1;
8543}
8544
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008545/* NB: called by pseudo_exec, and therefore must not modify any
8546 * global data until exec/_exit (we can be a child after vfork!) */
8547static int run_list(struct pipe *pi)
8548{
8549#if ENABLE_HUSH_CASE
8550 char *case_word = NULL;
8551#endif
8552#if ENABLE_HUSH_LOOPS
8553 struct pipe *loop_top = NULL;
8554 char **for_lcur = NULL;
8555 char **for_list = NULL;
8556#endif
8557 smallint last_followup;
8558 smalluint rcode;
8559#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8560 smalluint cond_code = 0;
8561#else
8562 enum { cond_code = 0 };
8563#endif
8564#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008565 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008566 smallint last_rword; /* ditto */
8567#endif
8568
8569 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8570 debug_enter();
8571
8572#if ENABLE_HUSH_LOOPS
8573 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008574 {
8575 struct pipe *cpipe;
8576 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8577 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8578 continue;
8579 /* current word is FOR or IN (BOLD in comments below) */
8580 if (cpipe->next == NULL) {
8581 syntax_error("malformed for");
8582 debug_leave();
8583 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8584 return 1;
8585 }
8586 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8587 if (cpipe->next->res_word == RES_DO)
8588 continue;
8589 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8590 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8591 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8592 ) {
8593 syntax_error("malformed for");
8594 debug_leave();
8595 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8596 return 1;
8597 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008598 }
8599 }
8600#endif
8601
8602 /* Past this point, all code paths should jump to ret: label
8603 * in order to return, no direct "return" statements please.
8604 * This helps to ensure that no memory is leaked. */
8605
8606#if ENABLE_HUSH_JOB
8607 G.run_list_level++;
8608#endif
8609
8610#if HAS_KEYWORDS
8611 rword = RES_NONE;
8612 last_rword = RES_XXXX;
8613#endif
8614 last_followup = PIPE_SEQ;
8615 rcode = G.last_exitcode;
8616
8617 /* Go through list of pipes, (maybe) executing them. */
8618 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008619 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008620 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008621
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008622 if (G.flag_SIGINT)
8623 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008624 if (G_flag_return_in_progress == 1)
8625 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008626
8627 IF_HAS_KEYWORDS(rword = pi->res_word;)
8628 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8629 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008630
8631 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008632 if (
8633#if ENABLE_HUSH_IF
8634 rword == RES_IF || rword == RES_ELIF ||
8635#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008636 pi->followup != PIPE_SEQ
8637 ) {
8638 G.errexit_depth++;
8639 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008640#if ENABLE_HUSH_LOOPS
8641 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8642 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8643 ) {
8644 /* start of a loop: remember where loop starts */
8645 loop_top = pi;
8646 G.depth_of_loop++;
8647 }
8648#endif
8649 /* Still in the same "if...", "then..." or "do..." branch? */
8650 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8651 if ((rcode == 0 && last_followup == PIPE_OR)
8652 || (rcode != 0 && last_followup == PIPE_AND)
8653 ) {
8654 /* It is "<true> || CMD" or "<false> && CMD"
8655 * and we should not execute CMD */
8656 debug_printf_exec("skipped cmd because of || or &&\n");
8657 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008658 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008659 }
8660 }
8661 last_followup = pi->followup;
8662 IF_HAS_KEYWORDS(last_rword = rword;)
8663#if ENABLE_HUSH_IF
8664 if (cond_code) {
8665 if (rword == RES_THEN) {
8666 /* if false; then ... fi has exitcode 0! */
8667 G.last_exitcode = rcode = EXIT_SUCCESS;
8668 /* "if <false> THEN cmd": skip cmd */
8669 continue;
8670 }
8671 } else {
8672 if (rword == RES_ELSE || rword == RES_ELIF) {
8673 /* "if <true> then ... ELSE/ELIF cmd":
8674 * skip cmd and all following ones */
8675 break;
8676 }
8677 }
8678#endif
8679#if ENABLE_HUSH_LOOPS
8680 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8681 if (!for_lcur) {
8682 /* first loop through for */
8683
8684 static const char encoded_dollar_at[] ALIGN1 = {
8685 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8686 }; /* encoded representation of "$@" */
8687 static const char *const encoded_dollar_at_argv[] = {
8688 encoded_dollar_at, NULL
8689 }; /* argv list with one element: "$@" */
8690 char **vals;
8691
8692 vals = (char**)encoded_dollar_at_argv;
8693 if (pi->next->res_word == RES_IN) {
8694 /* if no variable values after "in" we skip "for" */
8695 if (!pi->next->cmds[0].argv) {
8696 G.last_exitcode = rcode = EXIT_SUCCESS;
8697 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8698 break;
8699 }
8700 vals = pi->next->cmds[0].argv;
8701 } /* else: "for var; do..." -> assume "$@" list */
8702 /* create list of variable values */
8703 debug_print_strings("for_list made from", vals);
8704 for_list = expand_strvec_to_strvec(vals);
8705 for_lcur = for_list;
8706 debug_print_strings("for_list", for_list);
8707 }
8708 if (!*for_lcur) {
8709 /* "for" loop is over, clean up */
8710 free(for_list);
8711 for_list = NULL;
8712 for_lcur = NULL;
8713 break;
8714 }
8715 /* Insert next value from for_lcur */
8716 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008717 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008718 continue;
8719 }
8720 if (rword == RES_IN) {
8721 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8722 }
8723 if (rword == RES_DONE) {
8724 continue; /* "done" has no cmds too */
8725 }
8726#endif
8727#if ENABLE_HUSH_CASE
8728 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008729 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008730 case_word = expand_strvec_to_string(pi->cmds->argv);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008731 unbackslash(case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008732 continue;
8733 }
8734 if (rword == RES_MATCH) {
8735 char **argv;
8736
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008737 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008738 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8739 break;
8740 /* all prev words didn't match, does this one match? */
8741 argv = pi->cmds->argv;
8742 while (*argv) {
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008743 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008744 /* TODO: which FNM_xxx flags to use? */
8745 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008746 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008747 free(pattern);
8748 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008749 free(case_word);
8750 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008751 break;
8752 }
8753 argv++;
8754 }
8755 continue;
8756 }
8757 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008758 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008759 if (cond_code != 0)
8760 continue; /* not matched yet, skip this pipe */
8761 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008762 if (rword == RES_ESAC) {
8763 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8764 if (case_word) {
8765 /* "case" did not match anything: still set $? (to 0) */
8766 G.last_exitcode = rcode = EXIT_SUCCESS;
8767 }
8768 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008769#endif
8770 /* Just pressing <enter> in shell should check for jobs.
8771 * OTOH, in non-interactive shell this is useless
8772 * and only leads to extra job checks */
8773 if (pi->num_cmds == 0) {
8774 if (G_interactive_fd)
8775 goto check_jobs_and_continue;
8776 continue;
8777 }
8778
8779 /* After analyzing all keywords and conditions, we decided
8780 * to execute this pipe. NB: have to do checkjobs(NULL)
8781 * after run_pipe to collect any background children,
8782 * even if list execution is to be stopped. */
8783 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008784#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008785 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008786#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008787 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8788 if (r != -1) {
8789 /* We ran a builtin, function, or group.
8790 * rcode is already known
8791 * and we don't need to wait for anything. */
8792 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8793 G.last_exitcode = rcode;
8794 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008795#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008796 /* Was it "break" or "continue"? */
8797 if (G.flag_break_continue) {
8798 smallint fbc = G.flag_break_continue;
8799 /* We might fall into outer *loop*,
8800 * don't want to break it too */
8801 if (loop_top) {
8802 G.depth_break_continue--;
8803 if (G.depth_break_continue == 0)
8804 G.flag_break_continue = 0;
8805 /* else: e.g. "continue 2" should *break* once, *then* continue */
8806 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8807 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008808 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008809 break;
8810 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008811 /* "continue": simulate end of loop */
8812 rword = RES_DONE;
8813 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008814 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008815#endif
8816 if (G_flag_return_in_progress == 1) {
8817 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8818 break;
8819 }
8820 } else if (pi->followup == PIPE_BG) {
8821 /* What does bash do with attempts to background builtins? */
8822 /* even bash 3.2 doesn't do that well with nested bg:
8823 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8824 * I'm NOT treating inner &'s as jobs */
8825#if ENABLE_HUSH_JOB
8826 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02008827 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008828#endif
8829 /* Last command's pid goes to $! */
8830 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02008831 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008832 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008833/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008834 rcode = EXIT_SUCCESS;
8835 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008836 } else {
8837#if ENABLE_HUSH_JOB
8838 if (G.run_list_level == 1 && G_interactive_fd) {
8839 /* Waits for completion, then fg's main shell */
8840 rcode = checkjobs_and_fg_shell(pi);
8841 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008842 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008843 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008844#endif
8845 /* This one just waits for completion */
8846 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8847 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8848 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008849 G.last_exitcode = rcode;
8850 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008851 }
8852
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008853 /* Handle "set -e" */
8854 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8855 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8856 if (G.errexit_depth == 0)
8857 hush_exit(rcode);
8858 }
8859 G.errexit_depth = sv_errexit_depth;
8860
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008861 /* Analyze how result affects subsequent commands */
8862#if ENABLE_HUSH_IF
8863 if (rword == RES_IF || rword == RES_ELIF)
8864 cond_code = rcode;
8865#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008866 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008867 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008868 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008869#if ENABLE_HUSH_LOOPS
8870 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008871 if (pi->next
8872 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008873 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008874 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008875 if (rword == RES_WHILE) {
8876 if (rcode) {
8877 /* "while false; do...done" - exitcode 0 */
8878 G.last_exitcode = rcode = EXIT_SUCCESS;
8879 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008880 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008881 }
8882 }
8883 if (rword == RES_UNTIL) {
8884 if (!rcode) {
8885 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008886 break;
8887 }
8888 }
8889 }
8890#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008891 } /* for (pi) */
8892
8893#if ENABLE_HUSH_JOB
8894 G.run_list_level--;
8895#endif
8896#if ENABLE_HUSH_LOOPS
8897 if (loop_top)
8898 G.depth_of_loop--;
8899 free(for_list);
8900#endif
8901#if ENABLE_HUSH_CASE
8902 free(case_word);
8903#endif
8904 debug_leave();
8905 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8906 return rcode;
8907}
8908
8909/* Select which version we will use */
8910static int run_and_free_list(struct pipe *pi)
8911{
8912 int rcode = 0;
8913 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08008914 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008915 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8916 rcode = run_list(pi);
8917 }
8918 /* free_pipe_list has the side effect of clearing memory.
8919 * In the long run that function can be merged with run_list,
8920 * but doing that now would hobble the debugging effort. */
8921 free_pipe_list(pi);
8922 debug_printf_exec("run_and_free_list return %d\n", rcode);
8923 return rcode;
8924}
8925
8926
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008927static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00008928{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008929 sighandler_t old_handler;
8930 unsigned sig = 0;
8931 while ((mask >>= 1) != 0) {
8932 sig++;
8933 if (!(mask & 1))
8934 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02008935 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008936 /* POSIX allows shell to re-enable SIGCHLD
8937 * even if it was SIG_IGN on entry.
8938 * Therefore we skip IGN check for it:
8939 */
8940 if (sig == SIGCHLD)
8941 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02008942 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8943 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8944 */
8945 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008946 if (old_handler == SIG_IGN) {
8947 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008948 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008949#if ENABLE_HUSH_TRAP
8950 if (!G_traps)
8951 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8952 free(G_traps[sig]);
8953 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8954#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008955 }
8956 }
8957}
8958
8959/* Called a few times only (or even once if "sh -c") */
8960static void install_special_sighandlers(void)
8961{
Denis Vlasenkof9375282009-04-05 19:13:39 +00008962 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008963
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008964 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008965 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008966 if (G_interactive_fd) {
8967 mask |= SPECIAL_INTERACTIVE_SIGS;
8968 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008969 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008970 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008971 /* Careful, do not re-install handlers we already installed */
8972 if (G.special_sig_mask != mask) {
8973 unsigned diff = mask & ~G.special_sig_mask;
8974 G.special_sig_mask = mask;
8975 install_sighandlers(diff);
8976 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008977}
8978
8979#if ENABLE_HUSH_JOB
8980/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008981/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008982static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00008983{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008984 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008985
8986 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008987 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01008988 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8989 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008990 + (1 << SIGBUS ) * HUSH_DEBUG
8991 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01008992 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008993 + (1 << SIGABRT)
8994 /* bash 3.2 seems to handle these just like 'fatal' ones */
8995 + (1 << SIGPIPE)
8996 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008997 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008998 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008999 * we never want to restore pgrp on exit, and this fn is not called
9000 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009001 /*+ (1 << SIGHUP )*/
9002 /*+ (1 << SIGTERM)*/
9003 /*+ (1 << SIGINT )*/
9004 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009005 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02009006
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009007 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009008}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00009009#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00009010
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009011static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00009012{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009013 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009014 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009015 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08009016 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009017 break;
9018 case 'x':
9019 IF_HUSH_MODE_X(G_x_mode = state;)
9020 break;
9021 case 'o':
9022 if (!o_opt) {
9023 /* "set -+o" without parameter.
9024 * in bash, set -o produces this output:
9025 * pipefail off
9026 * and set +o:
9027 * set +o pipefail
9028 * We always use the second form.
9029 */
9030 const char *p = o_opt_strings;
9031 idx = 0;
9032 while (*p) {
9033 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
9034 idx++;
9035 p += strlen(p) + 1;
9036 }
9037 break;
9038 }
9039 idx = index_in_strings(o_opt_strings, o_opt);
9040 if (idx >= 0) {
9041 G.o_opt[idx] = state;
9042 break;
9043 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009044 case 'e':
9045 G.o_opt[OPT_O_ERREXIT] = state;
9046 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009047 default:
9048 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009049 }
9050 return EXIT_SUCCESS;
9051}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009052
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009053int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009054int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009055{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009056 enum {
9057 OPT_login = (1 << 0),
9058 };
9059 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00009060 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009061 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009062 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009063 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009064 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009065
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009066 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009067 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009068 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009069
Denys Vlasenko10c01312011-05-11 11:49:21 +02009070#if ENABLE_HUSH_FAST
9071 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9072#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009073#if !BB_MMU
9074 G.argv0_for_re_execing = argv[0];
9075#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009076
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009077 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009078 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9079 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009080 shell_ver = xzalloc(sizeof(*shell_ver));
9081 shell_ver->flg_export = 1;
9082 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009083 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009084 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009085 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009086
Denys Vlasenko605067b2010-09-06 12:10:51 +02009087 /* Create shell local variables from the values
9088 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009089 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009090 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009091 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009092 if (e) while (*e) {
9093 char *value = strchr(*e, '=');
9094 if (value) { /* paranoia */
9095 cur_var->next = xzalloc(sizeof(*cur_var));
9096 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009097 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009098 cur_var->max_len = strlen(*e);
9099 cur_var->flg_export = 1;
9100 }
9101 e++;
9102 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009103 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009104 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9105 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009106
9107 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009108 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009109
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009110#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009111 /* Set (but not export) HOSTNAME unless already set */
9112 if (!get_local_var_value("HOSTNAME")) {
9113 struct utsname uts;
9114 uname(&uts);
9115 set_local_var_from_halves("HOSTNAME", uts.nodename);
9116 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009117 /* bash also exports SHLVL and _,
9118 * and sets (but doesn't export) the following variables:
9119 * BASH=/bin/bash
9120 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9121 * BASH_VERSION='3.2.0(1)-release'
9122 * HOSTTYPE=i386
9123 * MACHTYPE=i386-pc-linux-gnu
9124 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009125 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009126 * EUID=<NNNNN>
9127 * UID=<NNNNN>
9128 * GROUPS=()
9129 * LINES=<NNN>
9130 * COLUMNS=<NNN>
9131 * BASH_ARGC=()
9132 * BASH_ARGV=()
9133 * BASH_LINENO=()
9134 * BASH_SOURCE=()
9135 * DIRSTACK=()
9136 * PIPESTATUS=([0]="0")
9137 * HISTFILE=/<xxx>/.bash_history
9138 * HISTFILESIZE=500
9139 * HISTSIZE=500
9140 * MAILCHECK=60
9141 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9142 * SHELL=/bin/bash
9143 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9144 * TERM=dumb
9145 * OPTERR=1
9146 * OPTIND=1
9147 * IFS=$' \t\n'
9148 * PS1='\s-\v\$ '
9149 * PS2='> '
9150 * PS4='+ '
9151 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009152#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009153
Denys Vlasenko5807e182018-02-08 19:19:04 +01009154#if ENABLE_HUSH_LINENO_VAR
9155 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009156 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9157 set_local_var(p, /*flags*/ 0);
9158 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9159 }
9160#endif
9161
Denis Vlasenko38f63192007-01-22 09:03:07 +00009162#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009163 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009164#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009165
Eric Andersen94ac2442001-05-22 19:05:18 +00009166 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009167 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009168
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009169 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009170
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009171 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009172 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009173 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009174 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009175 * in order to intercept (more) signals.
9176 */
9177
9178 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009179 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009180 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009181 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009182 while (1) {
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009183 opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009184#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009185 "<:$:R:V:"
9186# if ENABLE_HUSH_FUNCTIONS
9187 "F:"
9188# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009189#endif
9190 );
9191 if (opt <= 0)
9192 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009193 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009194 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009195 /* Possibilities:
9196 * sh ... -c 'script'
9197 * sh ... -c 'script' ARG0 [ARG1...]
9198 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009199 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009200 * "" needs to be replaced with NULL
9201 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009202 * Note: the form without ARG0 never happens:
9203 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009204 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009205 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009206 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009207 G.root_ppid = getppid();
9208 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009209 G.global_argv = argv + optind;
9210 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009211 if (builtin_argc) {
9212 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9213 const struct built_in_command *x;
9214
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009215 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009216 x = find_builtin(optarg);
9217 if (x) { /* paranoia */
9218 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9219 G.global_argv += builtin_argc;
9220 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009221 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009222 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009223 }
9224 goto final_return;
9225 }
9226 if (!G.global_argv[0]) {
9227 /* -c 'script' (no params): prevent empty $0 */
9228 G.global_argv--; /* points to argv[i] of 'script' */
9229 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009230 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009231 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009232 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009233 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009234 goto final_return;
9235 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009236 /* Well, we cannot just declare interactiveness,
9237 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009238 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009239 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009240 case 's':
9241 /* "-s" means "read from stdin", but this is how we always
9242 * operate, so simply do nothing here. */
9243 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009244 case 'l':
9245 flags |= OPT_login;
9246 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009247#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009248 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009249 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009250 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009251 case '$': {
9252 unsigned long long empty_trap_mask;
9253
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009254 G.root_pid = bb_strtou(optarg, &optarg, 16);
9255 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009256 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9257 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009258 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9259 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009260 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009261 optarg++;
9262 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009263 optarg++;
9264 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9265 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009266 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009267 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009268# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009269 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009270 for (sig = 1; sig < NSIG; sig++) {
9271 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009272 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009273 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009274 }
9275 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009276# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009277 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009278# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009279 optarg++;
9280 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009281# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009282 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009283 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009284 case 'R':
9285 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009286 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009287 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009288# if ENABLE_HUSH_FUNCTIONS
9289 case 'F': {
9290 struct function *funcp = new_function(optarg);
9291 /* funcp->name is already set to optarg */
9292 /* funcp->body is set to NULL. It's a special case. */
9293 funcp->body_as_string = argv[optind];
9294 optind++;
9295 break;
9296 }
9297# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009298#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009299 case 'n':
9300 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009301 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009302 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009303 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009304 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009305#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009306 fprintf(stderr, "Usage: sh [FILE]...\n"
9307 " or: sh -c command [args]...\n\n");
9308 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009309#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009310 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009311#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009312 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009313 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009314
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009315 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9316 G.global_argc = argc - (optind - 1);
9317 G.global_argv = argv + (optind - 1);
9318 G.global_argv[0] = argv[0];
9319
Denys Vlasenkodea47882009-10-09 15:40:49 +02009320 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009321 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009322 G.root_ppid = getppid();
9323 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009324
9325 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009326 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009327 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009328 debug_printf("sourcing /etc/profile\n");
9329 input = fopen_for_read("/etc/profile");
9330 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009331 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009332 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009333 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009334 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009335 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009336 /* bash: after sourcing /etc/profile,
9337 * tries to source (in the given order):
9338 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009339 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009340 * bash also sources ~/.bash_logout on exit.
9341 * If called as sh, skips .bash_XXX files.
9342 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009343 }
9344
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009345 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009346 FILE *input;
9347 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009348 * "bash <script>" (which is never interactive (unless -i?))
9349 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009350 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009351 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009352 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009353 G.global_argc--;
9354 G.global_argv++;
9355 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009356 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009357 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009358 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009359 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009360 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009361 parse_and_run_file(input);
9362#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009363 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009364#endif
9365 goto final_return;
9366 }
9367
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009368 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009369 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009370 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009371
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009372 /* A shell is interactive if the '-i' flag was given,
9373 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009374 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009375 * no arguments remaining or the -s flag given
9376 * standard input is a terminal
9377 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009378 * Refer to Posix.2, the description of the 'sh' utility.
9379 */
9380#if ENABLE_HUSH_JOB
9381 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009382 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9383 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9384 if (G_saved_tty_pgrp < 0)
9385 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009386
9387 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009388 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009389 if (G_interactive_fd < 0) {
9390 /* try to dup to any fd */
9391 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009392 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009393 /* give up */
9394 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009395 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009396 }
9397 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009398// TODO: track & disallow any attempts of user
9399// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009400 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009401 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009402 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009403 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009404
Mike Frysinger38478a62009-05-20 04:48:06 -04009405 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009406 /* If we were run as 'hush &', sleep until we are
9407 * in the foreground (tty pgrp == our pgrp).
9408 * If we get started under a job aware app (like bash),
9409 * make sure we are now in charge so we don't fight over
9410 * who gets the foreground */
9411 while (1) {
9412 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009413 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9414 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009415 break;
9416 /* send TTIN to ourself (should stop us) */
9417 kill(- shell_pgrp, SIGTTIN);
9418 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009419 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009420
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009421 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009422 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009423
Mike Frysinger38478a62009-05-20 04:48:06 -04009424 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009425 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009426 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009427 /* Put ourselves in our own process group
9428 * (bash, too, does this only if ctty is available) */
9429 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9430 /* Grab control of the terminal */
9431 tcsetpgrp(G_interactive_fd, getpid());
9432 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009433 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009434
9435# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9436 {
9437 const char *hp = get_local_var_value("HISTFILE");
9438 if (!hp) {
9439 hp = get_local_var_value("HOME");
9440 if (hp)
9441 hp = concat_path_file(hp, ".hush_history");
9442 } else {
9443 hp = xstrdup(hp);
9444 }
9445 if (hp) {
9446 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009447 //set_local_var(xasprintf("HISTFILE=%s", ...));
9448 }
9449# if ENABLE_FEATURE_SH_HISTFILESIZE
9450 hp = get_local_var_value("HISTFILESIZE");
9451 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9452# endif
9453 }
9454# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009455 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009456 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009457 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009458#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009459 /* No job control compiled in, only prompt/line editing */
9460 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009461 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009462 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009463 /* try to dup to any fd */
Denys Vlasenko9acd63c2018-03-28 18:35:07 +02009464 G_interactive_fd = dup_CLOEXEC(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009465 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009466 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009467 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009468 }
9469 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009470 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009471 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009472 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009473 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009474#else
9475 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009476 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009477#endif
9478 /* bash:
9479 * if interactive but not a login shell, sources ~/.bashrc
9480 * (--norc turns this off, --rcfile <file> overrides)
9481 */
9482
9483 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009484 /* note: ash and hush share this string */
9485 printf("\n\n%s %s\n"
9486 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9487 "\n",
9488 bb_banner,
9489 "hush - the humble shell"
9490 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009491 }
9492
Denis Vlasenkof9375282009-04-05 19:13:39 +00009493 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009494
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009495 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009496 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009497}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009498
9499
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009500/*
9501 * Built-ins
9502 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009503static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009504{
9505 return 0;
9506}
9507
Denys Vlasenko265062d2017-01-10 15:13:30 +01009508#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009509static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009510{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009511 int argc = string_array_len(argv);
9512 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009513}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009514#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009515#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009516static int FAST_FUNC builtin_test(char **argv)
9517{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009518 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009519}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009520#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009521#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009522static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009523{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009524 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009525}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009526#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009527#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009528static int FAST_FUNC builtin_printf(char **argv)
9529{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009530 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009531}
9532#endif
9533
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009534#if ENABLE_HUSH_HELP
9535static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9536{
9537 const struct built_in_command *x;
9538
9539 printf(
9540 "Built-in commands:\n"
9541 "------------------\n");
9542 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9543 if (x->b_descr)
9544 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9545 }
9546 return EXIT_SUCCESS;
9547}
9548#endif
9549
9550#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9551static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9552{
9553 show_history(G.line_input_state);
9554 return EXIT_SUCCESS;
9555}
9556#endif
9557
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009558static char **skip_dash_dash(char **argv)
9559{
9560 argv++;
9561 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9562 argv++;
9563 return argv;
9564}
9565
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009566static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009567{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009568 const char *newdir;
9569
9570 argv = skip_dash_dash(argv);
9571 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009572 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009573 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009574 * bash says "bash: cd: HOME not set" and does nothing
9575 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009576 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009577 const char *home = get_local_var_value("HOME");
9578 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009579 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009580 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009581 /* Mimic bash message exactly */
9582 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009583 return EXIT_FAILURE;
9584 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009585 /* Read current dir (get_cwd(1) is inside) and set PWD.
9586 * Note: do not enforce exporting. If PWD was unset or unexported,
9587 * set it again, but do not export. bash does the same.
9588 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009589 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009590 return EXIT_SUCCESS;
9591}
9592
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009593static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9594{
9595 puts(get_cwd(0));
9596 return EXIT_SUCCESS;
9597}
9598
9599static int FAST_FUNC builtin_eval(char **argv)
9600{
9601 int rcode = EXIT_SUCCESS;
9602
9603 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009604 if (argv[0]) {
9605 char *str = NULL;
9606
9607 if (argv[1]) {
9608 /* "The eval utility shall construct a command by
9609 * concatenating arguments together, separating
9610 * each with a <space> character."
9611 */
9612 char *p;
9613 unsigned len = 0;
9614 char **pp = argv;
9615 do
9616 len += strlen(*pp) + 1;
9617 while (*++pp);
9618 str = p = xmalloc(len);
9619 pp = argv;
9620 do {
9621 p = stpcpy(p, *pp);
9622 *p++ = ' ';
9623 } while (*++pp);
9624 p[-1] = '\0';
9625 }
9626
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009627 /* bash:
9628 * eval "echo Hi; done" ("done" is syntax error):
9629 * "echo Hi" will not execute too.
9630 */
Denys Vlasenko1f191122018-01-11 13:17:30 +01009631 parse_and_run_string(str ? str : argv[0]);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009632 free(str);
9633 rcode = G.last_exitcode;
9634 }
9635 return rcode;
9636}
9637
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009638static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009639{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009640 argv = skip_dash_dash(argv);
9641 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009642 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009643
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009644 /* Careful: we can end up here after [v]fork. Do not restore
9645 * tty pgrp then, only top-level shell process does that */
9646 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9647 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9648
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009649 /* Saved-redirect fds, script fds and G_interactive_fd are still
9650 * open here. However, they are all CLOEXEC, and execv below
9651 * closes them. Try interactive "exec ls -l /proc/self/fd",
9652 * it should show no extra open fds in the "ls" process.
9653 * If we'd try to run builtins/NOEXECs, this would need improving.
9654 */
9655 //close_saved_fds_and_FILE_fds();
9656
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009657 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009658 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009659 * and tcsetpgrp, and this is inherently racy.
9660 */
9661 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009662}
9663
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009664static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009665{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009666 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009667
9668 /* interactive bash:
9669 * # trap "echo EEE" EXIT
9670 * # exit
9671 * exit
9672 * There are stopped jobs.
9673 * (if there are _stopped_ jobs, running ones don't count)
9674 * # exit
9675 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009676 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009677 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009678 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009679 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009680
9681 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009682 argv = skip_dash_dash(argv);
9683 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009684 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009685 /* mimic bash: exit 123abc == exit 255 + error msg */
9686 xfunc_error_retval = 255;
9687 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009688 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009689}
9690
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009691#if ENABLE_HUSH_TYPE
9692/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9693static int FAST_FUNC builtin_type(char **argv)
9694{
9695 int ret = EXIT_SUCCESS;
9696
9697 while (*++argv) {
9698 const char *type;
9699 char *path = NULL;
9700
9701 if (0) {} /* make conditional compile easier below */
9702 /*else if (find_alias(*argv))
9703 type = "an alias";*/
9704#if ENABLE_HUSH_FUNCTIONS
9705 else if (find_function(*argv))
9706 type = "a function";
9707#endif
9708 else if (find_builtin(*argv))
9709 type = "a shell builtin";
9710 else if ((path = find_in_path(*argv)) != NULL)
9711 type = path;
9712 else {
9713 bb_error_msg("type: %s: not found", *argv);
9714 ret = EXIT_FAILURE;
9715 continue;
9716 }
9717
9718 printf("%s is %s\n", *argv, type);
9719 free(path);
9720 }
9721
9722 return ret;
9723}
9724#endif
9725
9726#if ENABLE_HUSH_READ
9727/* Interruptibility of read builtin in bash
9728 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9729 *
9730 * Empty trap makes read ignore corresponding signal, for any signal.
9731 *
9732 * SIGINT:
9733 * - terminates non-interactive shell;
9734 * - interrupts read in interactive shell;
9735 * if it has non-empty trap:
9736 * - executes trap and returns to command prompt in interactive shell;
9737 * - executes trap and returns to read in non-interactive shell;
9738 * SIGTERM:
9739 * - is ignored (does not interrupt) read in interactive shell;
9740 * - terminates non-interactive shell;
9741 * if it has non-empty trap:
9742 * - executes trap and returns to read;
9743 * SIGHUP:
9744 * - terminates shell (regardless of interactivity);
9745 * if it has non-empty trap:
9746 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +02009747 * SIGCHLD from children:
9748 * - does not interrupt read regardless of interactivity:
9749 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009750 */
9751static int FAST_FUNC builtin_read(char **argv)
9752{
9753 const char *r;
9754 char *opt_n = NULL;
9755 char *opt_p = NULL;
9756 char *opt_t = NULL;
9757 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009758 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009759 const char *ifs;
9760 int read_flags;
9761
9762 /* "!": do not abort on errors.
9763 * Option string must start with "sr" to match BUILTIN_READ_xxx
9764 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009765 read_flags = getopt32(argv,
9766#if BASH_READ_D
9767 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9768#else
9769 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9770#endif
9771 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009772 if (read_flags == (uint32_t)-1)
9773 return EXIT_FAILURE;
9774 argv += optind;
9775 ifs = get_local_var_value("IFS"); /* can be NULL */
9776
9777 again:
9778 r = shell_builtin_read(set_local_var_from_halves,
9779 argv,
9780 ifs,
9781 read_flags,
9782 opt_n,
9783 opt_p,
9784 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009785 opt_u,
9786 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009787 );
9788
9789 if ((uintptr_t)r == 1 && errno == EINTR) {
9790 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +02009791 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009792 goto again;
9793 }
9794
9795 if ((uintptr_t)r > 1) {
9796 bb_error_msg("%s", r);
9797 r = (char*)(uintptr_t)1;
9798 }
9799
9800 return (uintptr_t)r;
9801}
9802#endif
9803
9804#if ENABLE_HUSH_UMASK
9805static int FAST_FUNC builtin_umask(char **argv)
9806{
9807 int rc;
9808 mode_t mask;
9809
9810 rc = 1;
9811 mask = umask(0);
9812 argv = skip_dash_dash(argv);
9813 if (argv[0]) {
9814 mode_t old_mask = mask;
9815
9816 /* numeric umasks are taken as-is */
9817 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9818 if (!isdigit(argv[0][0]))
9819 mask ^= 0777;
9820 mask = bb_parse_mode(argv[0], mask);
9821 if (!isdigit(argv[0][0]))
9822 mask ^= 0777;
9823 if ((unsigned)mask > 0777) {
9824 mask = old_mask;
9825 /* bash messages:
9826 * bash: umask: 'q': invalid symbolic mode operator
9827 * bash: umask: 999: octal number out of range
9828 */
9829 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9830 rc = 0;
9831 }
9832 } else {
9833 /* Mimic bash */
9834 printf("%04o\n", (unsigned) mask);
9835 /* fall through and restore mask which we set to 0 */
9836 }
9837 umask(mask);
9838
9839 return !rc; /* rc != 0 - success */
9840}
9841#endif
9842
Denys Vlasenko41ade052017-01-08 18:56:24 +01009843#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009844static void print_escaped(const char *s)
9845{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009846 if (*s == '\'')
9847 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009848 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009849 const char *p = strchrnul(s, '\'');
9850 /* print 'xxxx', possibly just '' */
9851 printf("'%.*s'", (int)(p - s), s);
9852 if (*p == '\0')
9853 break;
9854 s = p;
9855 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009856 /* s points to '; print "'''...'''" */
9857 putchar('"');
9858 do putchar('\''); while (*++s == '\'');
9859 putchar('"');
9860 } while (*s);
9861}
Denys Vlasenko41ade052017-01-08 18:56:24 +01009862#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009863
Denys Vlasenko1e660422017-07-17 21:10:50 +02009864#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009865static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009866{
9867 do {
9868 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009869 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02009870
9871 /* So far we do not check that name is valid (TODO?) */
9872
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009873 if (*name_end == '\0') {
9874 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009875
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009876 vpp = get_ptr_to_local_var(name, name_end - name);
9877 var = vpp ? *vpp : NULL;
9878
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009879 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009880 /* export -n NAME (without =VALUE) */
9881 if (var) {
9882 var->flg_export = 0;
9883 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9884 unsetenv(name);
9885 } /* else: export -n NOT_EXISTING_VAR: no-op */
9886 continue;
9887 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009888 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009889 /* export NAME (without =VALUE) */
9890 if (var) {
9891 var->flg_export = 1;
9892 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9893 putenv(var->varstr);
9894 continue;
9895 }
9896 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009897 if (flags & SETFLAG_MAKE_RO) {
9898 /* readonly NAME (without =VALUE) */
9899 if (var) {
9900 var->flg_read_only = 1;
9901 continue;
9902 }
9903 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009904# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +02009905 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009906 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9907 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
Denys Vlasenkob95ee962017-07-17 21:19:53 +02009908 if (var && var->func_nest_level == lvl) {
9909 /* "local x=abc; ...; local x" - ignore second local decl */
9910 continue;
9911 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02009912 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009913# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009914 /* Exporting non-existing variable.
9915 * bash does not put it in environment,
9916 * but remembers that it is exported,
9917 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +02009918 * We just set it to "" and export.
9919 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02009920 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +02009921 * bash sets the value to "".
9922 */
9923 /* Or, it's "readonly NAME" (without =VALUE).
9924 * bash remembers NAME and disallows its creation
9925 * in the future.
9926 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02009927 name = xasprintf("%s=", name);
9928 } else {
9929 /* (Un)exporting/making local NAME=VALUE */
9930 name = xstrdup(name);
9931 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009932 if (set_local_var(name, flags))
9933 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009934 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +02009935 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009936}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009937#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009938
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009939#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009940static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009941{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00009942 unsigned opt_unexport;
9943
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02009944#if ENABLE_HUSH_EXPORT_N
9945 /* "!": do not abort on errors */
9946 opt_unexport = getopt32(argv, "!n");
9947 if (opt_unexport == (uint32_t)-1)
9948 return EXIT_FAILURE;
9949 argv += optind;
9950#else
9951 opt_unexport = 0;
9952 argv++;
9953#endif
9954
9955 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009956 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009957 if (e) {
9958 while (*e) {
9959#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009960 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009961#else
9962 /* ash emits: export VAR='VAL'
9963 * bash: declare -x VAR="VAL"
9964 * we follow ash example */
9965 const char *s = *e++;
9966 const char *p = strchr(s, '=');
9967
9968 if (!p) /* wtf? take next variable */
9969 continue;
9970 /* export var= */
9971 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009972 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009973 putchar('\n');
9974#endif
9975 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009976 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009977 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009978 return EXIT_SUCCESS;
9979 }
9980
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009981 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009982}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009983#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009984
Denys Vlasenko295fef82009-06-03 12:47:26 +02009985#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009986static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009987{
9988 if (G.func_nest_level == 0) {
9989 bb_error_msg("%s: not in a function", argv[0]);
9990 return EXIT_FAILURE; /* bash compat */
9991 }
Denys Vlasenko1e660422017-07-17 21:10:50 +02009992 argv++;
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009993 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +02009994}
9995#endif
9996
Denys Vlasenko1e660422017-07-17 21:10:50 +02009997#if ENABLE_HUSH_READONLY
9998static int FAST_FUNC builtin_readonly(char **argv)
9999{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010000 argv++;
10001 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +020010002 /* bash: readonly [-p]: list all readonly VARs
10003 * (-p has no effect in bash)
10004 */
10005 struct variable *e;
10006 for (e = G.top_var; e; e = e->next) {
10007 if (e->flg_read_only) {
10008//TODO: quote value: readonly VAR='VAL'
10009 printf("readonly %s\n", e->varstr);
10010 }
10011 }
10012 return EXIT_SUCCESS;
10013 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +020010014 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +020010015}
10016#endif
10017
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010018#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010019/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
10020static int FAST_FUNC builtin_unset(char **argv)
10021{
10022 int ret;
10023 unsigned opts;
10024
10025 /* "!": do not abort on errors */
10026 /* "+": stop at 1st non-option */
10027 opts = getopt32(argv, "!+vf");
10028 if (opts == (unsigned)-1)
10029 return EXIT_FAILURE;
10030 if (opts == 3) {
10031 bb_error_msg("unset: -v and -f are exclusive");
10032 return EXIT_FAILURE;
10033 }
10034 argv += optind;
10035
10036 ret = EXIT_SUCCESS;
10037 while (*argv) {
10038 if (!(opts & 2)) { /* not -f */
10039 if (unset_local_var(*argv)) {
10040 /* unset <nonexistent_var> doesn't fail.
10041 * Error is when one tries to unset RO var.
10042 * Message was printed by unset_local_var. */
10043 ret = EXIT_FAILURE;
10044 }
10045 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010046# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010047 else {
10048 unset_func(*argv);
10049 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010050# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010051 argv++;
10052 }
10053 return ret;
10054}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010055#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010056
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010057#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010058/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10059 * built-in 'set' handler
10060 * SUSv3 says:
10061 * set [-abCefhmnuvx] [-o option] [argument...]
10062 * set [+abCefhmnuvx] [+o option] [argument...]
10063 * set -- [argument...]
10064 * set -o
10065 * set +o
10066 * Implementations shall support the options in both their hyphen and
10067 * plus-sign forms. These options can also be specified as options to sh.
10068 * Examples:
10069 * Write out all variables and their values: set
10070 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10071 * Turn on the -x and -v options: set -xv
10072 * Unset all positional parameters: set --
10073 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10074 * Set the positional parameters to the expansion of x, even if x expands
10075 * with a leading '-' or '+': set -- $x
10076 *
10077 * So far, we only support "set -- [argument...]" and some of the short names.
10078 */
10079static int FAST_FUNC builtin_set(char **argv)
10080{
10081 int n;
10082 char **pp, **g_argv;
10083 char *arg = *++argv;
10084
10085 if (arg == NULL) {
10086 struct variable *e;
10087 for (e = G.top_var; e; e = e->next)
10088 puts(e->varstr);
10089 return EXIT_SUCCESS;
10090 }
10091
10092 do {
10093 if (strcmp(arg, "--") == 0) {
10094 ++argv;
10095 goto set_argv;
10096 }
10097 if (arg[0] != '+' && arg[0] != '-')
10098 break;
10099 for (n = 1; arg[n]; ++n) {
10100 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10101 goto error;
10102 if (arg[n] == 'o' && argv[1])
10103 argv++;
10104 }
10105 } while ((arg = *++argv) != NULL);
10106 /* Now argv[0] is 1st argument */
10107
10108 if (arg == NULL)
10109 return EXIT_SUCCESS;
10110 set_argv:
10111
10112 /* NB: G.global_argv[0] ($0) is never freed/changed */
10113 g_argv = G.global_argv;
10114 if (G.global_args_malloced) {
10115 pp = g_argv;
10116 while (*++pp)
10117 free(*pp);
10118 g_argv[1] = NULL;
10119 } else {
10120 G.global_args_malloced = 1;
10121 pp = xzalloc(sizeof(pp[0]) * 2);
10122 pp[0] = g_argv[0]; /* retain $0 */
10123 g_argv = pp;
10124 }
10125 /* This realloc's G.global_argv */
10126 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10127
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010128 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010129
10130 return EXIT_SUCCESS;
10131
10132 /* Nothing known, so abort */
10133 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010134 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010135 return EXIT_FAILURE;
10136}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010137#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010138
10139static int FAST_FUNC builtin_shift(char **argv)
10140{
10141 int n = 1;
10142 argv = skip_dash_dash(argv);
10143 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010144 n = bb_strtou(argv[0], NULL, 10);
10145 if (errno || n < 0) {
10146 /* shared string with ash.c */
10147 bb_error_msg("Illegal number: %s", argv[0]);
10148 /*
10149 * ash aborts in this case.
10150 * bash prints error message and set $? to 1.
10151 * Interestingly, for "shift 99999" bash does not
10152 * print error message, but does set $? to 1
10153 * (and does no shifting at all).
10154 */
10155 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010156 }
10157 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010158 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010159 int m = 1;
10160 while (m <= n)
10161 free(G.global_argv[m++]);
10162 }
10163 G.global_argc -= n;
10164 memmove(&G.global_argv[1], &G.global_argv[n+1],
10165 G.global_argc * sizeof(G.global_argv[0]));
10166 return EXIT_SUCCESS;
10167 }
10168 return EXIT_FAILURE;
10169}
10170
Denys Vlasenko74d40582017-08-11 01:32:46 +020010171#if ENABLE_HUSH_GETOPTS
10172static int FAST_FUNC builtin_getopts(char **argv)
10173{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010174/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10175
Denys Vlasenko74d40582017-08-11 01:32:46 +020010176TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010177If a required argument is not found, and getopts is not silent,
10178a question mark (?) is placed in VAR, OPTARG is unset, and a
10179diagnostic message is printed. If getopts is silent, then a
10180colon (:) is placed in VAR and OPTARG is set to the option
10181character found.
10182
10183Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010184
10185"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010186*/
10187 char cbuf[2];
10188 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010189 int c, n, exitcode, my_opterr;
10190 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010191
10192 optstring = *++argv;
10193 if (!optstring || !(var = *++argv)) {
10194 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10195 return EXIT_FAILURE;
10196 }
10197
Denys Vlasenko238ff982017-08-29 13:38:30 +020010198 if (argv[1])
10199 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10200 else
10201 argv = G.global_argv;
10202 cbuf[1] = '\0';
10203
10204 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010205 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010206 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010207 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010208 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010209 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010210
10211 /* getopts stops on first non-option. Add "+" to force that */
10212 /*if (optstring[0] != '+')*/ {
10213 char *s = alloca(strlen(optstring) + 2);
10214 sprintf(s, "+%s", optstring);
10215 optstring = s;
10216 }
10217
Denys Vlasenko238ff982017-08-29 13:38:30 +020010218 /* Naively, now we should just
10219 * cp = get_local_var_value("OPTIND");
10220 * optind = cp ? atoi(cp) : 0;
10221 * optarg = NULL;
10222 * opterr = my_opterr;
10223 * c = getopt(string_array_len(argv), argv, optstring);
10224 * and be done? Not so fast...
10225 * Unlike normal getopt() usage in C programs, here
10226 * each successive call will (usually) have the same argv[] CONTENTS,
10227 * but not the ADDRESSES. Worse yet, it's possible that between
10228 * invocations of "getopts", there will be calls to shell builtins
10229 * which use getopt() internally. Example:
10230 * while getopts "abc" RES -a -bc -abc de; do
10231 * unset -ff func
10232 * done
10233 * This would not work correctly: getopt() call inside "unset"
10234 * modifies internal libc state which is tracking position in
10235 * multi-option strings ("-abc"). At best, it can skip options
10236 * or return the same option infinitely. With glibc implementation
10237 * of getopt(), it would use outright invalid pointers and return
10238 * garbage even _without_ "unset" mangling internal state.
10239 *
10240 * We resort to resetting getopt() state and calling it N times,
10241 * until we get Nth result (or failure).
10242 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10243 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010244 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010245 count = 0;
10246 n = string_array_len(argv);
10247 do {
10248 optarg = NULL;
10249 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10250 c = getopt(n, argv, optstring);
10251 if (c < 0)
10252 break;
10253 count++;
10254 } while (count <= G.getopt_count);
10255
10256 /* Set OPTIND. Prevent resetting of the magic counter! */
10257 set_local_var_from_halves("OPTIND", utoa(optind));
10258 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010259 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010260
10261 /* Set OPTARG */
10262 /* Always set or unset, never left as-is, even on exit/error:
10263 * "If no option was found, or if the option that was found
10264 * does not have an option-argument, OPTARG shall be unset."
10265 */
10266 cp = optarg;
10267 if (c == '?') {
10268 /* If ":optstring" and unknown option is seen,
10269 * it is stored to OPTARG.
10270 */
10271 if (optstring[1] == ':') {
10272 cbuf[0] = optopt;
10273 cp = cbuf;
10274 }
10275 }
10276 if (cp)
10277 set_local_var_from_halves("OPTARG", cp);
10278 else
10279 unset_local_var("OPTARG");
10280
10281 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010282 exitcode = EXIT_SUCCESS;
10283 if (c < 0) { /* -1: end of options */
10284 exitcode = EXIT_FAILURE;
10285 c = '?';
10286 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010287
Denys Vlasenko238ff982017-08-29 13:38:30 +020010288 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010289 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010290 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010291
Denys Vlasenko74d40582017-08-11 01:32:46 +020010292 return exitcode;
10293}
10294#endif
10295
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010296static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010297{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010298 char *arg_path, *filename;
10299 FILE *input;
10300 save_arg_t sv;
10301 char *args_need_save;
10302#if ENABLE_HUSH_FUNCTIONS
10303 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010304#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010305
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010306 argv = skip_dash_dash(argv);
10307 filename = argv[0];
10308 if (!filename) {
10309 /* bash says: "bash: .: filename argument required" */
10310 return 2; /* bash compat */
10311 }
10312 arg_path = NULL;
10313 if (!strchr(filename, '/')) {
10314 arg_path = find_in_path(filename);
10315 if (arg_path)
10316 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010317 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010318 errno = ENOENT;
10319 bb_simple_perror_msg(filename);
10320 return EXIT_FAILURE;
10321 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010322 }
10323 input = remember_FILE(fopen_or_warn(filename, "r"));
10324 free(arg_path);
10325 if (!input) {
10326 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10327 /* POSIX: non-interactive shell should abort here,
10328 * not merely fail. So far no one complained :)
10329 */
10330 return EXIT_FAILURE;
10331 }
10332
10333#if ENABLE_HUSH_FUNCTIONS
10334 sv_flg = G_flag_return_in_progress;
10335 /* "we are inside sourced file, ok to use return" */
10336 G_flag_return_in_progress = -1;
10337#endif
10338 args_need_save = argv[1]; /* used as a boolean variable */
10339 if (args_need_save)
10340 save_and_replace_G_args(&sv, argv);
10341
10342 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10343 G.last_exitcode = 0;
10344 parse_and_run_file(input);
10345 fclose_and_forget(input);
10346
10347 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10348 restore_G_args(&sv, argv);
10349#if ENABLE_HUSH_FUNCTIONS
10350 G_flag_return_in_progress = sv_flg;
10351#endif
10352
10353 return G.last_exitcode;
10354}
10355
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010356#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010357static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010358{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010359 int sig;
10360 char *new_cmd;
10361
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010362 if (!G_traps)
10363 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010364
10365 argv++;
10366 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010367 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010368 /* No args: print all trapped */
10369 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010370 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010371 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010372 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010373 /* note: bash adds "SIG", but only if invoked
10374 * as "bash". If called as "sh", or if set -o posix,
10375 * then it prints short signal names.
10376 * We are printing short names: */
10377 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010378 }
10379 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010380 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010381 return EXIT_SUCCESS;
10382 }
10383
10384 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010385 /* If first arg is a number: reset all specified signals */
10386 sig = bb_strtou(*argv, NULL, 10);
10387 if (errno == 0) {
10388 int ret;
10389 process_sig_list:
10390 ret = EXIT_SUCCESS;
10391 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010392 sighandler_t handler;
10393
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010394 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010395 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010396 ret = EXIT_FAILURE;
10397 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010398 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010399 continue;
10400 }
10401
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010402 free(G_traps[sig]);
10403 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010404
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010405 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010406 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010407
10408 /* There is no signal for 0 (EXIT) */
10409 if (sig == 0)
10410 continue;
10411
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010412 if (new_cmd)
10413 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10414 else
10415 /* We are removing trap handler */
10416 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010417 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010418 }
10419 return ret;
10420 }
10421
10422 if (!argv[1]) { /* no second arg */
10423 bb_error_msg("trap: invalid arguments");
10424 return EXIT_FAILURE;
10425 }
10426
10427 /* First arg is "-": reset all specified to default */
10428 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10429 /* Everything else: set arg as signal handler
10430 * (includes "" case, which ignores signal) */
10431 if (argv[0][0] == '-') {
10432 if (argv[0][1] == '\0') { /* "-" */
10433 /* new_cmd remains NULL: "reset these sigs" */
10434 goto reset_traps;
10435 }
10436 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10437 argv++;
10438 }
10439 /* else: "-something", no special meaning */
10440 }
10441 new_cmd = *argv;
10442 reset_traps:
10443 argv++;
10444 goto process_sig_list;
10445}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010446#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010447
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010448#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010449static struct pipe *parse_jobspec(const char *str)
10450{
10451 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010452 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010453
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010454 if (sscanf(str, "%%%u", &jobnum) != 1) {
10455 if (str[0] != '%'
10456 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10457 ) {
10458 bb_error_msg("bad argument '%s'", str);
10459 return NULL;
10460 }
10461 /* It is "%%", "%+" or "%" - current job */
10462 jobnum = G.last_jobid;
10463 if (jobnum == 0) {
10464 bb_error_msg("no current job");
10465 return NULL;
10466 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010467 }
10468 for (pi = G.job_list; pi; pi = pi->next) {
10469 if (pi->jobid == jobnum) {
10470 return pi;
10471 }
10472 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010473 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010474 return NULL;
10475}
10476
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010477static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10478{
10479 struct pipe *job;
10480 const char *status_string;
10481
10482 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10483 for (job = G.job_list; job; job = job->next) {
10484 if (job->alive_cmds == job->stopped_cmds)
10485 status_string = "Stopped";
10486 else
10487 status_string = "Running";
10488
10489 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10490 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010491
10492 clean_up_last_dead_job();
10493
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010494 return EXIT_SUCCESS;
10495}
10496
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010497/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010498static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010499{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010500 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010501 struct pipe *pi;
10502
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010503 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010504 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010505
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010506 /* If they gave us no args, assume they want the last backgrounded task */
10507 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010508 for (pi = G.job_list; pi; pi = pi->next) {
10509 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010510 goto found;
10511 }
10512 }
10513 bb_error_msg("%s: no current job", argv[0]);
10514 return EXIT_FAILURE;
10515 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010516
10517 pi = parse_jobspec(argv[1]);
10518 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010519 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010520 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010521 /* TODO: bash prints a string representation
10522 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010523 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010524 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010525 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010526 }
10527
10528 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010529 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10530 for (i = 0; i < pi->num_cmds; i++) {
10531 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010532 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010533 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010534
10535 i = kill(- pi->pgrp, SIGCONT);
10536 if (i < 0) {
10537 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010538 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010539 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010540 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010541 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010542 }
10543
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010544 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010545 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010546 return checkjobs_and_fg_shell(pi);
10547 }
10548 return EXIT_SUCCESS;
10549}
10550#endif
10551
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010552#if ENABLE_HUSH_KILL
10553static int FAST_FUNC builtin_kill(char **argv)
10554{
10555 int ret = 0;
10556
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010557# if ENABLE_HUSH_JOB
10558 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10559 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010560
10561 do {
10562 struct pipe *pi;
10563 char *dst;
10564 int j, n;
10565
10566 if (argv[i][0] != '%')
10567 continue;
10568 /*
10569 * "kill %N" - job kill
10570 * Converting to pgrp / pid kill
10571 */
10572 pi = parse_jobspec(argv[i]);
10573 if (!pi) {
10574 /* Eat bad jobspec */
10575 j = i;
10576 do {
10577 j++;
10578 argv[j - 1] = argv[j];
10579 } while (argv[j]);
10580 ret = 1;
10581 i--;
10582 continue;
10583 }
10584 /*
10585 * In jobs started under job control, we signal
10586 * entire process group by kill -PGRP_ID.
10587 * This happens, f.e., in interactive shell.
10588 *
10589 * Otherwise, we signal each child via
10590 * kill PID1 PID2 PID3.
10591 * Testcases:
10592 * sh -c 'sleep 1|sleep 1 & kill %1'
10593 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10594 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10595 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010596 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010597 dst = alloca(n * sizeof(int)*4);
10598 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010599 if (G_interactive_fd)
10600 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010601 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010602 struct command *cmd = &pi->cmds[j];
10603 /* Skip exited members of the job */
10604 if (cmd->pid == 0)
10605 continue;
10606 /*
10607 * kill_main has matching code to expect
10608 * leading space. Needed to not confuse
10609 * negative pids with "kill -SIGNAL_NO" syntax
10610 */
10611 dst += sprintf(dst, " %u", (int)cmd->pid);
10612 }
10613 *dst = '\0';
10614 } while (argv[++i]);
10615 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010616# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010617
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010618 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010619 ret = run_applet_main(argv, kill_main);
10620 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010621 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010622 return ret;
10623}
10624#endif
10625
10626#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010627/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010628#if !ENABLE_HUSH_JOB
10629# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10630#endif
10631static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010632{
10633 int ret = 0;
10634 for (;;) {
10635 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010636 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010637
Denys Vlasenko830ea352016-11-08 04:59:11 +010010638 if (!sigisemptyset(&G.pending_set))
10639 goto check_sig;
10640
Denys Vlasenko7e675362016-10-28 21:57:31 +020010641 /* waitpid is not interruptible by SA_RESTARTed
10642 * signals which we use. Thus, this ugly dance:
10643 */
10644
10645 /* Make sure possible SIGCHLD is stored in kernel's
10646 * pending signal mask before we call waitpid.
10647 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010648 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010649 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010650 sigfillset(&oldset); /* block all signals, remember old set */
10651 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010652
10653 if (!sigisemptyset(&G.pending_set)) {
10654 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010655 goto restore;
10656 }
10657
10658 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010659/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010660 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010661 debug_printf_exec("checkjobs:%d\n", ret);
10662#if ENABLE_HUSH_JOB
10663 if (waitfor_pipe) {
10664 int rcode = job_exited_or_stopped(waitfor_pipe);
10665 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10666 if (rcode >= 0) {
10667 ret = rcode;
10668 sigprocmask(SIG_SETMASK, &oldset, NULL);
10669 break;
10670 }
10671 }
10672#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010673 /* if ECHILD, there are no children (ret is -1 or 0) */
10674 /* if ret == 0, no children changed state */
10675 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010676 if (errno == ECHILD || ret) {
10677 ret--;
10678 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010679 ret = 0;
10680 sigprocmask(SIG_SETMASK, &oldset, NULL);
10681 break;
10682 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010683 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010684 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10685 /* Note: sigsuspend invokes signal handler */
10686 sigsuspend(&oldset);
10687 restore:
10688 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010689 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010690 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010691 sig = check_and_run_traps();
10692 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020010693 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010694 ret = 128 + sig;
10695 break;
10696 }
10697 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10698 }
10699 return ret;
10700}
10701
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010702static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000010703{
Denys Vlasenko7e675362016-10-28 21:57:31 +020010704 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010705 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000010706
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010707 argv = skip_dash_dash(argv);
10708 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010709 /* Don't care about wait results */
10710 /* Note 1: must wait until there are no more children */
10711 /* Note 2: must be interruptible */
10712 /* Examples:
10713 * $ sleep 3 & sleep 6 & wait
10714 * [1] 30934 sleep 3
10715 * [2] 30935 sleep 6
10716 * [1] Done sleep 3
10717 * [2] Done sleep 6
10718 * $ sleep 3 & sleep 6 & wait
10719 * [1] 30936 sleep 3
10720 * [2] 30937 sleep 6
10721 * [1] Done sleep 3
10722 * ^C <-- after ~4 sec from keyboard
10723 * $
10724 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010725 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010726 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000010727
Denys Vlasenko7e675362016-10-28 21:57:31 +020010728 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000010729 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010730 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010731#if ENABLE_HUSH_JOB
10732 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010733 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010734 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010735 wait_pipe = parse_jobspec(*argv);
10736 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010737 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010738 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010739 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010740 } else {
10741 /* waiting on "last dead job" removes it */
10742 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020010743 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010744 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010745 /* else: parse_jobspec() already emitted error msg */
10746 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010747 }
10748#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000010749 /* mimic bash message */
10750 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010751 ret = EXIT_FAILURE;
10752 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000010753 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010010754
Denys Vlasenko7e675362016-10-28 21:57:31 +020010755 /* Do we have such child? */
10756 ret = waitpid(pid, &status, WNOHANG);
10757 if (ret < 0) {
10758 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010759 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010760 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020010761 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010762 /* "wait $!" but last bg task has already exited. Try:
10763 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10764 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010765 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010766 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010767 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010768 } else {
10769 /* Example: "wait 1". mimic bash message */
10770 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010771 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010772 } else {
10773 /* ??? */
10774 bb_perror_msg("wait %s", *argv);
10775 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010776 continue; /* bash checks all argv[] */
10777 }
10778 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020010779 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010780 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010781 } else {
10782 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010783 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020010784 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010785 if (WIFSIGNALED(status))
10786 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010787 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010788 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010789
10790 return ret;
10791}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010792#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000010793
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010794#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10795static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10796{
10797 if (argv[1]) {
10798 def = bb_strtou(argv[1], NULL, 10);
10799 if (errno || def < def_min || argv[2]) {
10800 bb_error_msg("%s: bad arguments", argv[0]);
10801 def = UINT_MAX;
10802 }
10803 }
10804 return def;
10805}
10806#endif
10807
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010808#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010809static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010810{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010811 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010812 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010813 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020010814 /* if we came from builtin_continue(), need to undo "= 1" */
10815 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000010816 return EXIT_SUCCESS; /* bash compat */
10817 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020010818 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010819
10820 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10821 if (depth == UINT_MAX)
10822 G.flag_break_continue = BC_BREAK;
10823 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000010824 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010825
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010826 return EXIT_SUCCESS;
10827}
10828
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010829static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010830{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010831 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10832 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010833}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010834#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010835
10836#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010837static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010838{
10839 int rc;
10840
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010841 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010842 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10843 return EXIT_FAILURE; /* bash compat */
10844 }
10845
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010846 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010847
10848 /* bash:
10849 * out of range: wraps around at 256, does not error out
10850 * non-numeric param:
10851 * f() { false; return qwe; }; f; echo $?
10852 * bash: return: qwe: numeric argument required <== we do this
10853 * 255 <== we also do this
10854 */
10855 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10856 return rc;
10857}
10858#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010859
Denys Vlasenko11f2e992017-08-10 16:34:03 +020010860#if ENABLE_HUSH_TIMES
10861static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10862{
10863 static const uint8_t times_tbl[] ALIGN1 = {
10864 ' ', offsetof(struct tms, tms_utime),
10865 '\n', offsetof(struct tms, tms_stime),
10866 ' ', offsetof(struct tms, tms_cutime),
10867 '\n', offsetof(struct tms, tms_cstime),
10868 0
10869 };
10870 const uint8_t *p;
10871 unsigned clk_tck;
10872 struct tms buf;
10873
10874 clk_tck = bb_clk_tck();
10875
10876 times(&buf);
10877 p = times_tbl;
10878 do {
10879 unsigned sec, frac;
10880 unsigned long t;
10881 t = *(clock_t *)(((char *) &buf) + p[1]);
10882 sec = t / clk_tck;
10883 frac = t % clk_tck;
10884 printf("%um%u.%03us%c",
10885 sec / 60, sec % 60,
10886 (frac * 1000) / clk_tck,
10887 p[0]);
10888 p += 2;
10889 } while (*p);
10890
10891 return EXIT_SUCCESS;
10892}
10893#endif
10894
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010895#if ENABLE_HUSH_MEMLEAK
10896static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10897{
10898 void *p;
10899 unsigned long l;
10900
10901# ifdef M_TRIM_THRESHOLD
10902 /* Optional. Reduces probability of false positives */
10903 malloc_trim(0);
10904# endif
10905 /* Crude attempt to find where "free memory" starts,
10906 * sans fragmentation. */
10907 p = malloc(240);
10908 l = (unsigned long)p;
10909 free(p);
10910 p = malloc(3400);
10911 if (l < (unsigned long)p) l = (unsigned long)p;
10912 free(p);
10913
10914
10915# if 0 /* debug */
10916 {
10917 struct mallinfo mi = mallinfo();
10918 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10919 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10920 }
10921# endif
10922
10923 if (!G.memleak_value)
10924 G.memleak_value = l;
10925
10926 l -= G.memleak_value;
10927 if ((long)l < 0)
10928 l = 0;
10929 l /= 1024;
10930 if (l > 127)
10931 l = 127;
10932
10933 /* Exitcode is "how many kilobytes we leaked since 1st call" */
10934 return l;
10935}
10936#endif