blob: 6e64efb70051f559640c449eb4035a4966af1f56 [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 Vlasenko2db74612017-07-07 22:07:28 +02001504static int fcntl_F_DUPFD(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:
1508 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001509 if (newfd < 0) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001510 if (errno == EBUSY)
1511 goto repeat;
1512 if (errno == EINTR)
1513 goto repeat;
1514 }
1515 return newfd;
1516}
1517
Denys Vlasenko657e9002017-07-30 23:34:04 +02001518static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
Denys Vlasenko2db74612017-07-07 22:07:28 +02001519{
1520 int newfd;
1521 repeat:
Denys Vlasenko657e9002017-07-30 23:34:04 +02001522 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001523 if (newfd < 0) {
1524 if (errno == EBUSY)
1525 goto repeat;
1526 if (errno == EINTR)
1527 goto repeat;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001528 /* fd was not open? */
1529 if (errno == EBADF)
1530 return fd;
1531 xfunc_die();
1532 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02001533 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
1534 fcntl(newfd, F_SETFD, FD_CLOEXEC);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001535 close(fd);
1536 return newfd;
1537}
1538
1539
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001540/* Manipulating the list of open FILEs */
1541static FILE *remember_FILE(FILE *fp)
1542{
1543 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001544 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001545 n->next = G.FILE_list;
1546 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001547 n->fp = fp;
1548 n->fd = fileno(fp);
1549 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001550 }
1551 return fp;
1552}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001553static void fclose_and_forget(FILE *fp)
1554{
1555 struct FILE_list **pp = &G.FILE_list;
1556 while (*pp) {
1557 struct FILE_list *cur = *pp;
1558 if (cur->fp == fp) {
1559 *pp = cur->next;
1560 free(cur);
1561 break;
1562 }
1563 pp = &cur->next;
1564 }
1565 fclose(fp);
1566}
Denys Vlasenko2db74612017-07-07 22:07:28 +02001567static int save_FILEs_on_redirect(int fd, int avoid_fd)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001568{
1569 struct FILE_list *fl = G.FILE_list;
1570 while (fl) {
1571 if (fd == fl->fd) {
1572 /* We use it only on script files, they are all CLOEXEC */
Denys Vlasenko657e9002017-07-30 23:34:04 +02001573 fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02001574 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 +02001575 return 1;
1576 }
1577 fl = fl->next;
1578 }
1579 return 0;
1580}
1581static void restore_redirected_FILEs(void)
1582{
1583 struct FILE_list *fl = G.FILE_list;
1584 while (fl) {
1585 int should_be = fileno(fl->fp);
1586 if (fl->fd != should_be) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02001587 debug_printf_redir("restoring script fd from %d to %d\n", fl->fd, should_be);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001588 xmove_fd(fl->fd, should_be);
1589 fl->fd = should_be;
1590 }
1591 fl = fl->next;
1592 }
1593}
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02001594#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001595static void close_all_FILE_list(void)
1596{
1597 struct FILE_list *fl = G.FILE_list;
1598 while (fl) {
1599 /* fclose would also free FILE object.
1600 * It is disastrous if we share memory with a vforked parent.
1601 * I'm not sure we never come here after vfork.
1602 * Therefore just close fd, nothing more.
1603 */
1604 /*fclose(fl->fp); - unsafe */
1605 close(fl->fd);
1606 fl = fl->next;
1607 }
1608}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001609#endif
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02001610static int fd_in_FILEs(int fd)
1611{
1612 struct FILE_list *fl = G.FILE_list;
1613 while (fl) {
1614 if (fl->fd == fd)
1615 return 1;
1616 fl = fl->next;
1617 }
1618 return 0;
1619}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001620
1621
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001622/* Helpers for setting new $n and restoring them back
1623 */
1624typedef struct save_arg_t {
1625 char *sv_argv0;
1626 char **sv_g_argv;
1627 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001628 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001629} save_arg_t;
1630
1631static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1632{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001633 sv->sv_argv0 = argv[0];
1634 sv->sv_g_argv = G.global_argv;
1635 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001636 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001637
1638 argv[0] = G.global_argv[0]; /* retain $0 */
1639 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001640 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001641
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02001642 G.global_argc = 1 + string_array_len(argv + 1);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001643}
1644
1645static void restore_G_args(save_arg_t *sv, char **argv)
1646{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001647#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001648 if (G.global_args_malloced) {
1649 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001650 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001651 while (*++pp) /* note: does not free $0 */
1652 free(*pp);
1653 free(G.global_argv);
1654 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001655#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001656 argv[0] = sv->sv_argv0;
1657 G.global_argv = sv->sv_g_argv;
1658 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001659 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001660}
1661
1662
Denis Vlasenkod5762932009-03-31 11:22:57 +00001663/* Basic theory of signal handling in shell
1664 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001665 * This does not describe what hush does, rather, it is current understanding
1666 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001667 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1668 *
1669 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1670 * is finished or backgrounded. It is the same in interactive and
1671 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001672 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001673 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001674 * backgrounds (i.e. stops) or kills all members of currently running
1675 * pipe.
1676 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001677 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001678 * or by SIGINT in interactive shell.
1679 *
1680 * Trap handlers will execute even within trap handlers. (right?)
1681 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001682 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1683 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001684 *
1685 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001686 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001687 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001688 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001689 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001690 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001691 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001692 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001693 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001694 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001695 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001696 *
1697 * SIGQUIT: ignore
1698 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001699 * SIGHUP (interactive):
1700 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001701 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001702 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1703 * that all pipe members are stopped. Try this in bash:
1704 * while :; do :; done - ^Z does not background it
1705 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001706 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001707 * of the command line, show prompt. NB: ^C does not send SIGINT
1708 * to interactive shell while shell is waiting for a pipe,
1709 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001710 * Example 1: this waits 5 sec, but does not execute ls:
1711 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1712 * Example 2: this does not wait and does not execute ls:
1713 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1714 * Example 3: this does not wait 5 sec, but executes ls:
1715 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001716 * Example 4: this does not wait and does not execute ls:
1717 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001718 *
1719 * (What happens to signals which are IGN on shell start?)
1720 * (What happens with signal mask on shell start?)
1721 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001722 * Old implementation
1723 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001724 * We use in-kernel pending signal mask to determine which signals were sent.
1725 * We block all signals which we don't want to take action immediately,
1726 * i.e. we block all signals which need to have special handling as described
1727 * above, and all signals which have traps set.
1728 * After each pipe execution, we extract any pending signals via sigtimedwait()
1729 * and act on them.
1730 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001731 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001732 * sigset_t blocked_set: current blocked signal set
1733 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001734 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001735 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001736 * "trap 'cmd' SIGxxx":
1737 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001738 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001739 * unblock signals with special interactive handling
1740 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001741 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001742 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001743 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001744 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001745 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001746 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001747 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001748 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001749 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001750 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001751 * Standard says "When a subshell is entered, traps that are not being ignored
1752 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001753 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001754 *
1755 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001756 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001757 * masked signals are not visible!
1758 *
1759 * New implementation
1760 * ==================
1761 * We record each signal we are interested in by installing signal handler
1762 * for them - a bit like emulating kernel pending signal mask in userspace.
1763 * We are interested in: signals which need to have special handling
1764 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001765 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001766 * After each pipe execution, we extract any pending signals
1767 * and act on them.
1768 *
1769 * unsigned special_sig_mask: a mask of shell-special signals.
1770 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1771 * char *traps[sig] if trap for sig is set (even if it's '').
1772 * sigset_t pending_set: set of sigs we received.
1773 *
1774 * "trap - SIGxxx":
1775 * if sig is in special_sig_mask, set handler back to:
1776 * record_pending_signo, or to IGN if it's a tty stop signal
1777 * if sig is in fatal_sig_mask, set handler back to sigexit.
1778 * else: set handler back to SIG_DFL
1779 * "trap 'cmd' SIGxxx":
1780 * set handler to record_pending_signo.
1781 * "trap '' SIGxxx":
1782 * set handler to SIG_IGN.
1783 * after [v]fork, if we plan to be a shell:
1784 * set signals with special interactive handling to SIG_DFL
1785 * (because child shell is not interactive),
1786 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1787 * after [v]fork, if we plan to exec:
1788 * POSIX says fork clears pending signal mask in child - no need to clear it.
1789 *
1790 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1791 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1792 *
1793 * Note (compat):
1794 * Standard says "When a subshell is entered, traps that are not being ignored
1795 * are set to the default actions". bash interprets it so that traps which
1796 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001797 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001798enum {
1799 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001800 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001801 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001802 | (1 << SIGHUP)
1803 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001804 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001805#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001806 | (1 << SIGTTIN)
1807 | (1 << SIGTTOU)
1808 | (1 << SIGTSTP)
1809#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001810 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001811};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001812
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001813static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001814{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001815 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001816#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001817 if (sig == SIGCHLD) {
1818 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001819//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 +02001820 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001821#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001822}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001823
Denys Vlasenko0806e402011-05-12 23:06:20 +02001824static sighandler_t install_sighandler(int sig, sighandler_t handler)
1825{
1826 struct sigaction old_sa;
1827
1828 /* We could use signal() to install handlers... almost:
1829 * except that we need to mask ALL signals while handlers run.
1830 * I saw signal nesting in strace, race window isn't small.
1831 * SA_RESTART is also needed, but in Linux, signal()
1832 * sets SA_RESTART too.
1833 */
1834 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1835 /* sigfillset(&G.sa.sa_mask); - already done */
1836 /* G.sa.sa_flags = SA_RESTART; - already done */
1837 G.sa.sa_handler = handler;
1838 sigaction(sig, &G.sa, &old_sa);
1839 return old_sa.sa_handler;
1840}
1841
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001842static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001843
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001844static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001845static void restore_ttypgrp_and__exit(void)
1846{
1847 /* xfunc has failed! die die die */
1848 /* no EXIT traps, this is an escape hatch! */
1849 G.exiting = 1;
1850 hush_exit(xfunc_error_retval);
1851}
1852
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001853#if ENABLE_HUSH_JOB
1854
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001855/* Needed only on some libc:
1856 * It was observed that on exit(), fgetc'ed buffered data
1857 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1858 * With the net effect that even after fork(), not vfork(),
1859 * exit() in NOEXECed applet in "sh SCRIPT":
1860 * noexec_applet_here
1861 * echo END_OF_SCRIPT
1862 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1863 * This makes "echo END_OF_SCRIPT" executed twice.
Denys Vlasenko39701202017-08-02 19:44:05 +02001864 * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001865 * and in `cmd` handling.
1866 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1867 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001868static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001869static void fflush_and__exit(void)
1870{
1871 fflush_all();
1872 _exit(xfunc_error_retval);
1873}
1874
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001875/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001876# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001877/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001878# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001879
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001880/* Restores tty foreground process group, and exits.
1881 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001882 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001883 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001884 * We also call it if xfunc is exiting.
1885 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001886static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001887static void sigexit(int sig)
1888{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001889 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001890 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001891 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1892 /* Disable all signals: job control, SIGPIPE, etc.
1893 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1894 */
1895 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001896 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001897 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001898
1899 /* Not a signal, just exit */
1900 if (sig <= 0)
1901 _exit(- sig);
1902
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001903 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001904}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001905#else
1906
Denys Vlasenko8391c482010-05-22 17:50:43 +02001907# define disable_restore_tty_pgrp_on_exit() ((void)0)
1908# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001909
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001910#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001911
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001912static sighandler_t pick_sighandler(unsigned sig)
1913{
1914 sighandler_t handler = SIG_DFL;
1915 if (sig < sizeof(unsigned)*8) {
1916 unsigned sigmask = (1 << sig);
1917
1918#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001919 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001920 if (G_fatal_sig_mask & sigmask)
1921 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001922 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001923#endif
1924 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001925 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001926 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001927 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001928 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001929 * in an endless loop when we try to do some
1930 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001931 */
1932 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1933 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001934 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001935 }
1936 return handler;
1937}
1938
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001939/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001940static void hush_exit(int exitcode)
1941{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001942#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1943 save_history(G.line_input_state);
1944#endif
1945
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001946 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001947 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001948 char *argv[3];
1949 /* argv[0] is unused */
Denys Vlasenko46f839c2018-01-19 16:58:44 +01001950 argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001951 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001952 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001953 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001954 * "trap" will still show it, if executed
1955 * in the handler */
1956 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001957 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001958
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001959#if ENABLE_FEATURE_CLEAN_UP
1960 {
1961 struct variable *cur_var;
1962 if (G.cwd != bb_msg_unknown)
1963 free((char*)G.cwd);
1964 cur_var = G.top_var;
1965 while (cur_var) {
1966 struct variable *tmp = cur_var;
1967 if (!cur_var->max_len)
1968 free(cur_var->varstr);
1969 cur_var = cur_var->next;
1970 free(tmp);
1971 }
1972 }
1973#endif
1974
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001975 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001976#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001977 sigexit(- (exitcode & 0xff));
1978#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001979 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001980#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001981}
1982
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001983
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001984//TODO: return a mask of ALL handled sigs?
1985static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001986{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001987 int last_sig = 0;
1988
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001989 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001990 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001991
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001992 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001993 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001994 sig = 0;
1995 do {
1996 sig++;
1997 if (sigismember(&G.pending_set, sig)) {
1998 sigdelset(&G.pending_set, sig);
1999 goto got_sig;
2000 }
2001 } while (sig < NSIG);
2002 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002003 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002004 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002005 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01002006 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002007 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002008 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002009 char *argv[3];
2010 /* argv[0] is unused */
Denys Vlasenko749575d2018-01-30 04:29:03 +01002011 argv[1] = xstrdup(G_traps[sig]);
2012 /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002013 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002014 save_rcode = G.last_exitcode;
2015 builtin_eval(argv);
Denys Vlasenko749575d2018-01-30 04:29:03 +01002016 free(argv[1]);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002017//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002018 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002019 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002020 } /* else: "" trap, ignoring signal */
2021 continue;
2022 }
2023 /* not a trap: special action */
2024 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002025 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002026 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002027 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002028 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002029 break;
2030#if ENABLE_HUSH_JOB
2031 case SIGHUP: {
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02002032//TODO: why are we doing this? ash and dash don't do this,
2033//they have no handler for SIGHUP at all,
2034//they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002035 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002036 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002037 /* bash is observed to signal whole process groups,
2038 * not individual processes */
2039 for (job = G.job_list; job; job = job->next) {
2040 if (job->pgrp <= 0)
2041 continue;
2042 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
2043 if (kill(- job->pgrp, SIGHUP) == 0)
2044 kill(- job->pgrp, SIGCONT);
2045 }
2046 sigexit(SIGHUP);
2047 }
2048#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002049#if ENABLE_HUSH_FAST
2050 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002051 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002052 G.count_SIGCHLD++;
2053//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2054 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002055 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002056 * This simplifies wait builtin a bit.
2057 */
2058 break;
2059#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002060 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02002061 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002062 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002063 /* Note:
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002064 * We don't do 'last_sig = sig' here -> NOT returning this sig.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002065 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02002066 * in interactive shell, because TERM is ignored.
2067 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002068 break;
2069 }
2070 }
2071 return last_sig;
2072}
2073
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002074
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002075static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002076{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002077 if (force || G.cwd == NULL) {
2078 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
2079 * we must not try to free(bb_msg_unknown) */
2080 if (G.cwd == bb_msg_unknown)
2081 G.cwd = NULL;
2082 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
2083 if (!G.cwd)
2084 G.cwd = bb_msg_unknown;
2085 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002086 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002087}
2088
Denis Vlasenko83506862007-11-23 13:11:42 +00002089
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002090/*
2091 * Shell and environment variable support
2092 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002093static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002094{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002095 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002096 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002097
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002098 pp = &G.top_var;
2099 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002100 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002101 return pp;
2102 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002103 }
2104 return NULL;
2105}
2106
Denys Vlasenko03dad222010-01-12 23:29:57 +01002107static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002108{
Denys Vlasenko29082232010-07-16 13:52:32 +02002109 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002110 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02002111
2112 if (G.expanded_assignments) {
2113 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02002114 while (*cpp) {
2115 char *cp = *cpp;
2116 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
2117 return cp + len + 1;
2118 cpp++;
2119 }
2120 }
2121
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002122 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02002123 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002124 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02002125
Denys Vlasenkodea47882009-10-09 15:40:49 +02002126 if (strcmp(name, "PPID") == 0)
2127 return utoa(G.root_ppid);
2128 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002129#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002130 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02002131 return utoa(next_random(&G.random_gen));
2132#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002133 return NULL;
2134}
2135
2136/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002137 * We take ownership of it.
Mike Frysinger6379bb42009-03-28 18:55:03 +00002138 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002139#define SETFLAG_EXPORT (1 << 0)
2140#define SETFLAG_UNEXPORT (1 << 1)
2141#define SETFLAG_MAKE_RO (1 << 2)
2142#define SETFLAG_LOCAL_SHIFT 3
2143static int set_local_var(char *str, unsigned flags)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002144{
Denys Vlasenko295fef82009-06-03 12:47:26 +02002145 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002146 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002147 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002148 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002149 int name_len;
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002150 IF_HUSH_LOCAL(unsigned local_lvl = (flags >> SETFLAG_LOCAL_SHIFT);)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002151
Denis Vlasenko950bd722009-04-21 11:23:56 +00002152 eq_sign = strchr(str, '=');
2153 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002154 free(str);
2155 return -1;
2156 }
2157
Denis Vlasenko950bd722009-04-21 11:23:56 +00002158 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko5807e182018-02-08 19:19:04 +01002159#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002160 if (G.lineno_var) {
2161 if (name_len == 7 && strncmp("LINENO", str, 6) == 0)
2162 G.lineno_var = NULL;
2163 }
2164#endif
2165
Denys Vlasenko295fef82009-06-03 12:47:26 +02002166 var_pp = &G.top_var;
2167 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002168 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002169 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002170 continue;
2171 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002172
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002173 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002174 if (cur->flg_read_only) {
Denys Vlasenko6b48e1f2017-07-17 21:31:17 +02002175 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002176 free(str);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002177//NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
2178//but export per se succeeds (does put the var in env). We don't mimic that.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002179 return -1;
2180 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002181 if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002182 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2183 *eq_sign = '\0';
2184 unsetenv(str);
2185 *eq_sign = '=';
2186 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002187#if ENABLE_HUSH_LOCAL
2188 if (cur->func_nest_level < local_lvl) {
2189 /* New variable is declared as local,
2190 * and existing one is global, or local
2191 * from enclosing function.
2192 * Remove and save old one: */
2193 *var_pp = cur->next;
2194 cur->next = *G.shadowed_vars_pp;
2195 *G.shadowed_vars_pp = cur;
2196 /* bash 3.2.33(1) and exported vars:
2197 * # export z=z
2198 * # f() { local z=a; env | grep ^z; }
2199 * # f
2200 * z=a
2201 * # env | grep ^z
2202 * z=z
2203 */
2204 if (cur->flg_export)
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002205 flags |= SETFLAG_EXPORT;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002206 break;
2207 }
2208#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00002209 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002210 free_and_exp:
2211 free(str);
2212 goto exp;
2213 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002214 if (cur->max_len != 0) {
2215 if (cur->max_len >= strlen(str)) {
2216 /* This one is from startup env, reuse space */
2217 strcpy(cur->varstr, str);
2218 goto free_and_exp;
2219 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002220 /* Can't reuse */
2221 cur->max_len = 0;
2222 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002223 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002224 /* max_len == 0 signifies "malloced" var, which we can
2225 * (and have to) free. But we can't free(cur->varstr) here:
2226 * if cur->flg_export is 1, it is in the environment.
2227 * We should either unsetenv+free, or wait until putenv,
2228 * then putenv(new)+free(old).
2229 */
2230 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002231 goto set_str_and_exp;
2232 }
2233
Denys Vlasenko295fef82009-06-03 12:47:26 +02002234 /* Not found - create new variable struct */
2235 cur = xzalloc(sizeof(*cur));
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002236 IF_HUSH_LOCAL(cur->func_nest_level = local_lvl;)
Denys Vlasenko295fef82009-06-03 12:47:26 +02002237 cur->next = *var_pp;
2238 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002239
2240 set_str_and_exp:
2241 cur->varstr = str;
2242 exp:
Denys Vlasenko1e660422017-07-17 21:10:50 +02002243#if !BB_MMU || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002244 if (flags & SETFLAG_MAKE_RO) {
2245 cur->flg_read_only = 1;
Denys Vlasenko1e660422017-07-17 21:10:50 +02002246 }
2247#endif
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002248 if (flags & SETFLAG_EXPORT)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002249 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002250 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2251 cmdedit_update_prompt();
Denys Vlasenko238ff982017-08-29 13:38:30 +02002252#if ENABLE_HUSH_GETOPTS
Denys Vlasenko55af51c2017-08-29 13:48:49 +02002253 /* defoptindvar is a "OPTIND=..." constant string */
2254 if (strncmp(cur->varstr, defoptindvar, 7) == 0)
Denys Vlasenko238ff982017-08-29 13:38:30 +02002255 G.getopt_count = 0;
2256#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002257 if (cur->flg_export) {
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002258 if (flags & SETFLAG_UNEXPORT) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002259 cur->flg_export = 0;
2260 /* unsetenv was already done */
2261 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002262 int i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002263 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002264 i = putenv(cur->varstr);
2265 /* only now we can free old exported malloced string */
2266 free(free_me);
2267 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002268 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002269 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002270 free(free_me);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002271 return 0;
2272}
2273
Denys Vlasenko6db47842009-09-05 20:15:17 +02002274/* Used at startup and after each cd */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002275static void set_pwd_var(unsigned flag)
Denys Vlasenko6db47842009-09-05 20:15:17 +02002276{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002277 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002278}
2279
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002280static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002281{
2282 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002283 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002284
2285 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002286 return EXIT_SUCCESS;
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002287
Denys Vlasenko238ff982017-08-29 13:38:30 +02002288#if ENABLE_HUSH_GETOPTS
2289 if (name_len == 6 && strncmp(name, "OPTIND", 6) == 0)
2290 G.getopt_count = 0;
2291#endif
Denys Vlasenko5807e182018-02-08 19:19:04 +01002292#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002293 if (name_len == 6 && G.lineno_var && strncmp(name, "LINENO", 6) == 0)
2294 G.lineno_var = NULL;
2295#endif
2296
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002297 var_pp = &G.top_var;
2298 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002299 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2300 if (cur->flg_read_only) {
2301 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002302 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002303 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002304 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002305 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2306 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002307 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2308 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002309 if (!cur->max_len)
2310 free(cur->varstr);
2311 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002312 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002313 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002314 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002316 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002317}
2318
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002319#if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002320static int unset_local_var(const char *name)
2321{
2322 return unset_local_var_len(name, strlen(name));
2323}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002324#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002325
2326static void unset_vars(char **strings)
2327{
2328 char **v;
2329
2330 if (!strings)
2331 return;
2332 v = strings;
2333 while (*v) {
2334 const char *eq = strchrnul(*v, '=');
2335 unset_local_var_len(*v, (int)(eq - *v));
2336 v++;
2337 }
2338 free(strings);
2339}
2340
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01002341#if BASH_HOSTNAME_VAR || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_READ || ENABLE_HUSH_GETOPTS
Denys Vlasenko03dad222010-01-12 23:29:57 +01002342static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002343{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002344 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002345 set_local_var(var, /*flag:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002346}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002347#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002348
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002349
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002350/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002351 * Helpers for "var1=val1 var2=val2 cmd" feature
2352 */
2353static void add_vars(struct variable *var)
2354{
2355 struct variable *next;
2356
2357 while (var) {
2358 next = var->next;
2359 var->next = G.top_var;
2360 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002361 if (var->flg_export) {
2362 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002363 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002364 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002365 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002366 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002367 var = next;
2368 }
2369}
2370
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002371static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002372{
2373 char **s;
2374 struct variable *old = NULL;
2375
2376 if (!strings)
2377 return old;
2378 s = strings;
2379 while (*s) {
2380 struct variable *var_p;
2381 struct variable **var_pp;
2382 char *eq;
2383
2384 eq = strchr(*s, '=');
2385 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002386 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002387 if (var_pp) {
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002388 var_p = *var_pp;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002389 if (var_p->flg_read_only) {
Denys Vlasenkocf511092017-07-18 15:58:02 +02002390 char **p;
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002391 bb_error_msg("%s: readonly variable", *s);
Denys Vlasenkocf511092017-07-18 15:58:02 +02002392 /*
2393 * "VAR=V BLTIN" unsets VARs after BLTIN completes.
2394 * If VAR is readonly, leaving it in the list
2395 * after asssignment error (msg above)
2396 * causes doubled error message later, on unset.
2397 */
2398 debug_printf_env("removing/freeing '%s' element\n", *s);
2399 free(*s);
2400 p = s;
2401 do { *p = p[1]; p++; } while (*p);
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002402 goto next;
2403 }
2404 /* Remove variable from global linked list */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002405 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002406 *var_pp = var_p->next;
2407 /* Add it to returned list */
2408 var_p->next = old;
2409 old = var_p;
2410 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02002411 set_local_var(*s, SETFLAG_EXPORT);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002412 }
Denys Vlasenko5b2cc0a2017-07-18 02:44:06 +02002413 next:
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002414 s++;
2415 }
2416 return old;
2417}
2418
2419
2420/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002421 * Unicode helper
2422 */
2423static void reinit_unicode_for_hush(void)
2424{
2425 /* Unicode support should be activated even if LANG is set
2426 * _during_ shell execution, not only if it was set when
2427 * shell was started. Therefore, re-check LANG every time:
2428 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002429 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2430 || ENABLE_UNICODE_USING_LOCALE
2431 ) {
2432 const char *s = get_local_var_value("LC_ALL");
2433 if (!s) s = get_local_var_value("LC_CTYPE");
2434 if (!s) s = get_local_var_value("LANG");
2435 reinit_unicode(s);
2436 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002437}
2438
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002439/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002440 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002441 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002442
2443#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002444/* To test correct lineedit/interactive behavior, type from command line:
2445 * echo $P\
2446 * \
2447 * AT\
2448 * H\
2449 * \
Denys Vlasenko10ad6222017-04-17 16:13:32 +02002450 * It exercises a lot of corner cases.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002451 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002452static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002453{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002454 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002455 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002456 if (G.PS1 == NULL)
2457 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002458 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002459 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002460 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002461 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002462 if (G.PS2 == NULL)
2463 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002464}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002465static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002466{
2467 const char *prompt_str;
2468 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002469 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2470 /* Set up the prompt */
2471 if (promptmode == 0) { /* PS1 */
2472 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002473 /* bash uses $PWD value, even if it is set by user.
2474 * It uses current dir only if PWD is unset.
2475 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002476 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002477 prompt_str = G.PS1;
2478 } else
2479 prompt_str = G.PS2;
2480 } else
2481 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002482 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002483 return prompt_str;
2484}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002485static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002486{
2487 int r;
2488 const char *prompt_str;
2489
2490 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002491# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002492 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002493 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002494 if (G.flag_SIGINT) {
2495 /* There was ^C'ed, make it look prettier: */
2496 bb_putchar('\n');
2497 G.flag_SIGINT = 0;
2498 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002499 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002500 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002501 r = read_line_input(G.line_input_state, prompt_str,
Denys Vlasenko84ea60e2017-08-02 17:27:28 +02002502 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
Denys Vlasenko0448c552016-09-29 20:25:44 +02002503 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002504 /* read_line_input intercepts ^C, "convert" it to SIGINT */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002505 if (r == 0)
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002506 raise(SIGINT);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002507 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002508 if (r != 0 && !G.flag_SIGINT)
2509 break;
2510 /* ^C or SIGINT: repeat */
Denys Vlasenkodd4b4462017-08-02 16:52:12 +02002511 /* bash prints ^C even on real SIGINT (non-kbd generated) */
2512 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002513 G.last_exitcode = 128 + SIGINT;
2514 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002515 if (r < 0) {
2516 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002517 i->p = NULL;
2518 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002519 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002520 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002521 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002522 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002523# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002524 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002525 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002526 if (i->last_char == '\0' || i->last_char == '\n') {
2527 /* Why check_and_run_traps here? Try this interactively:
2528 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2529 * $ <[enter], repeatedly...>
2530 * Without check_and_run_traps, handler never runs.
2531 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002532 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002533 fputs(prompt_str, stdout);
2534 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002535 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002536//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002537 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002538 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2539 * no ^C masking happens during fgetc, no special code for ^C:
2540 * it generates SIGINT as usual.
2541 */
2542 check_and_run_traps();
2543 if (G.flag_SIGINT)
2544 G.last_exitcode = 128 + SIGINT;
2545 if (r != '\0')
2546 break;
2547 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002548 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002549# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002550}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002551/* This is the magic location that prints prompts
2552 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002553static int fgetc_interactive(struct in_str *i)
2554{
2555 int ch;
2556 /* If it's interactive stdin, get new line. */
2557 if (G_interactive_fd && i->file == stdin) {
2558 /* Returns first char (or EOF), the rest is in i->p[] */
2559 ch = get_user_input(i);
2560 i->promptmode = 1; /* PS2 */
2561 } else {
2562 /* Not stdin: script file, sourced file, etc */
2563 do ch = fgetc(i->file); while (ch == '\0');
2564 }
2565 return ch;
2566}
2567#else
2568static inline int fgetc_interactive(struct in_str *i)
2569{
2570 int ch;
2571 do ch = fgetc(i->file); while (ch == '\0');
2572 return ch;
2573}
2574#endif /* INTERACTIVE */
2575
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002576static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002577{
2578 int ch;
2579
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002580 if (!i->file) {
2581 /* string-based in_str */
2582 ch = (unsigned char)*i->p;
2583 if (ch != '\0') {
2584 i->p++;
2585 i->last_char = ch;
2586 return ch;
2587 }
2588 return EOF;
2589 }
2590
2591 /* FILE-based in_str */
2592
Denys Vlasenko4074d492016-09-30 01:49:53 +02002593#if ENABLE_FEATURE_EDITING
2594 /* This can be stdin, check line editing char[] buffer */
2595 if (i->p && *i->p != '\0') {
2596 ch = (unsigned char)*i->p++;
2597 goto out;
2598 }
2599#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002600 /* peek_buf[] is an int array, not char. Can contain EOF. */
2601 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002602 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002603 int ch2 = i->peek_buf[1];
2604 i->peek_buf[0] = ch2;
2605 if (ch2 == 0) /* very likely, avoid redundant write */
2606 goto out;
2607 i->peek_buf[1] = 0;
2608 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002609 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002610
Denys Vlasenko4074d492016-09-30 01:49:53 +02002611 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002612 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002613 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002614 i->last_char = ch;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002615#if ENABLE_HUSH_LINENO_VAR
2616 if (ch == '\n') {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002617 G.lineno++;
Denys Vlasenko5807e182018-02-08 19:19:04 +01002618 debug_printf_parse("G.lineno++ = %u\n", G.lineno);
2619 }
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01002620#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002621 return ch;
2622}
2623
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002624static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002625{
2626 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002627
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002628 if (!i->file) {
2629 /* string-based in_str */
2630 /* Doesn't report EOF on NUL. None of the callers care. */
2631 return (unsigned char)*i->p;
2632 }
2633
2634 /* FILE-based in_str */
2635
Denys Vlasenko4074d492016-09-30 01:49:53 +02002636#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002637 /* This can be stdin, check line editing char[] buffer */
2638 if (i->p && *i->p != '\0')
2639 return (unsigned char)*i->p;
2640#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002641 /* peek_buf[] is an int array, not char. Can contain EOF. */
2642 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002643 if (ch != 0)
2644 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002645
Denys Vlasenko4074d492016-09-30 01:49:53 +02002646 /* Need to get a new char */
2647 ch = fgetc_interactive(i);
2648 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2649
2650 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2651#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2652 if (i->p) {
2653 i->p -= 1;
2654 return ch;
2655 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002656#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002657 i->peek_buf[0] = ch;
2658 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002659 return ch;
2660}
2661
Denys Vlasenko4074d492016-09-30 01:49:53 +02002662/* Only ever called if i_peek() was called, and did not return EOF.
2663 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2664 * not end-of-line. Therefore we never need to read a new editing line here.
2665 */
2666static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002667{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002668 int ch;
2669
2670 /* There are two cases when i->p[] buffer exists.
2671 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002672 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002673 * In both cases, we know that i->p[0] exists and not NUL, and
2674 * the peek2 result is in i->p[1].
2675 */
2676 if (i->p)
2677 return (unsigned char)i->p[1];
2678
2679 /* Now we know it is a file-based in_str. */
2680
2681 /* peek_buf[] is an int array, not char. Can contain EOF. */
2682 /* Is there 2nd char? */
2683 ch = i->peek_buf[1];
2684 if (ch == 0) {
2685 /* We did not read it yet, get it now */
2686 do ch = fgetc(i->file); while (ch == '\0');
2687 i->peek_buf[1] = ch;
2688 }
2689
2690 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2691 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002692}
2693
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002694static void setup_file_in_str(struct in_str *i, FILE *f)
2695{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002696 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002697 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002698 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002699 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002700}
2701
2702static void setup_string_in_str(struct in_str *i, const char *s)
2703{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002704 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002705 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002706 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002707 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002708}
2709
2710
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002711/*
2712 * o_string support
2713 */
2714#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002715
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002716static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002717{
2718 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002719 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002720 if (o->data)
2721 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002722}
2723
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002724static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002725{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002726 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002727 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002728}
2729
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002730static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2731{
2732 free(o->data);
2733}
2734
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002735static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002736{
2737 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002738 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002739 o->data = xrealloc(o->data, 1 + o->maxlen);
2740 }
2741}
2742
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002743static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002744{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002745 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002746 if (o->length < o->maxlen) {
2747 /* likely. avoid o_grow_by() call */
2748 add:
2749 o->data[o->length] = ch;
2750 o->length++;
2751 o->data[o->length] = '\0';
2752 return;
2753 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002754 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002755 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002756}
2757
Denys Vlasenko657086a2016-09-29 18:07:42 +02002758#if 0
2759/* Valid only if we know o_string is not empty */
2760static void o_delchr(o_string *o)
2761{
2762 o->length--;
2763 o->data[o->length] = '\0';
2764}
2765#endif
2766
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002767static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002768{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002769 o_grow_by(o, len);
Denys Vlasenko0675b032017-07-24 02:17:05 +02002770 ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002771 o->length += len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002772}
2773
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002774static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002775{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002776 o_addblock(o, str, strlen(str));
2777}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002778
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002779#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002780static void nommu_addchr(o_string *o, int ch)
2781{
2782 if (o)
2783 o_addchr(o, ch);
2784}
2785#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002786# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002787#endif
2788
2789static void o_addstr_with_NUL(o_string *o, const char *str)
2790{
2791 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002792}
2793
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002794/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002795 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002796 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2797 * Apparently, on unquoted $v bash still does globbing
2798 * ("v='*.txt'; echo $v" prints all .txt files),
2799 * but NOT brace expansion! Thus, there should be TWO independent
2800 * quoting mechanisms on $v expansion side: one protects
2801 * $v from brace expansion, and other additionally protects "$v" against globbing.
2802 * We have only second one.
2803 */
2804
Denys Vlasenko9e800222010-10-03 14:28:04 +02002805#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002806# define MAYBE_BRACES "{}"
2807#else
2808# define MAYBE_BRACES ""
2809#endif
2810
Eric Andersen25f27032001-04-26 23:22:31 +00002811/* My analysis of quoting semantics tells me that state information
2812 * is associated with a destination, not a source.
2813 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002814static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002815{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002816 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002817 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002818 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002819 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002820 o_grow_by(o, sz);
2821 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002822 o->data[o->length] = '\\';
2823 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002824 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002825 o->data[o->length] = ch;
2826 o->length++;
2827 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002828}
2829
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002830static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002831{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002832 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002833 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2834 && strchr("*?[\\" MAYBE_BRACES, ch)
2835 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002836 sz++;
2837 o->data[o->length] = '\\';
2838 o->length++;
2839 }
2840 o_grow_by(o, sz);
2841 o->data[o->length] = ch;
2842 o->length++;
2843 o->data[o->length] = '\0';
2844}
2845
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002846static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002847{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002848 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002849 char ch;
2850 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002851 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002852 if (ordinary_cnt > len) /* paranoia */
2853 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002854 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002855 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002856 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002857 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002858 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002859
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002860 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002861 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002862 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002863 sz++;
2864 o->data[o->length] = '\\';
2865 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002866 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002867 o_grow_by(o, sz);
2868 o->data[o->length] = ch;
2869 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002870 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002871 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002872}
2873
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002874static void o_addQblock(o_string *o, const char *str, int len)
2875{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002876 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002877 o_addblock(o, str, len);
2878 return;
2879 }
2880 o_addqblock(o, str, len);
2881}
2882
Denys Vlasenko38292b62010-09-05 14:49:40 +02002883static void o_addQstr(o_string *o, const char *str)
2884{
2885 o_addQblock(o, str, strlen(str));
2886}
2887
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002888/* A special kind of o_string for $VAR and `cmd` expansion.
2889 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002890 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002891 * list[i] contains an INDEX (int!) into this string data.
2892 * It means that if list[] needs to grow, data needs to be moved higher up
2893 * but list[i]'s need not be modified.
2894 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002895 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002896 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2897 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002898#if DEBUG_EXPAND || DEBUG_GLOB
2899static void debug_print_list(const char *prefix, o_string *o, int n)
2900{
2901 char **list = (char**)o->data;
2902 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2903 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002904
2905 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002906 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 +02002907 prefix, list, n, string_start, o->length, o->maxlen,
2908 !!(o->o_expflags & EXP_FLAG_GLOB),
2909 o->has_quoted_part,
2910 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002911 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002912 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002913 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2914 o->data + (int)(uintptr_t)list[i] + string_start,
2915 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002916 i++;
2917 }
2918 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002919 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002920 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002921 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002922 }
2923}
2924#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002925# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002926#endif
2927
2928/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2929 * in list[n] so that it points past last stored byte so far.
2930 * It returns n+1. */
2931static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002932{
2933 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002934 int string_start;
2935 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002936
2937 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002938 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2939 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002940 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002941 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002942 /* list[n] points to string_start, make space for 16 more pointers */
2943 o->maxlen += 0x10 * sizeof(list[0]);
2944 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002945 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002946 memmove(list + n + 0x10, list + n, string_len);
2947 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002948 } else {
2949 debug_printf_list("list[%d]=%d string_start=%d\n",
2950 n, string_len, string_start);
2951 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002952 } else {
2953 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002954 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2955 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002956 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2957 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002958 o->has_empty_slot = 0;
2959 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002960 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002961 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002962 return n + 1;
2963}
2964
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002965/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002966static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002967{
2968 char **list = (char**)o->data;
2969 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2970
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002971 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002972}
2973
Denys Vlasenko9e800222010-10-03 14:28:04 +02002974#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002975/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2976 * first, it processes even {a} (no commas), second,
2977 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002978 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002979 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002980
2981/* Helper */
2982static int glob_needed(const char *s)
2983{
2984 while (*s) {
2985 if (*s == '\\') {
2986 if (!s[1])
2987 return 0;
2988 s += 2;
2989 continue;
2990 }
2991 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2992 return 1;
2993 s++;
2994 }
2995 return 0;
2996}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002997/* Return pointer to next closing brace or to comma */
2998static const char *next_brace_sub(const char *cp)
2999{
3000 unsigned depth = 0;
3001 cp++;
3002 while (*cp != '\0') {
3003 if (*cp == '\\') {
3004 if (*++cp == '\0')
3005 break;
3006 cp++;
3007 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01003008 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003009 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003010 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003011 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003012 depth++;
3013 }
3014
3015 return *cp != '\0' ? cp : NULL;
3016}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003017/* Recursive brace globber. Note: may garble pattern[]. */
3018static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003019{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003020 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003021 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003022 const char *next;
3023 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003024 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003025 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003026
3027 debug_printf_glob("glob_brace('%s')\n", pattern);
3028
3029 begin = pattern;
3030 while (1) {
3031 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003032 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003033 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003034 /* Find the first sub-pattern and at the same time
3035 * find the rest after the closing brace */
3036 next = next_brace_sub(begin);
3037 if (next == NULL) {
3038 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003039 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003040 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003041 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003042 /* "{abc}" with no commas - illegal
3043 * brace expr, disregard and skip it */
3044 begin = next + 1;
3045 continue;
3046 }
3047 break;
3048 }
3049 if (*begin == '\\' && begin[1] != '\0')
3050 begin++;
3051 begin++;
3052 }
3053 debug_printf_glob("begin:%s\n", begin);
3054 debug_printf_glob("next:%s\n", next);
3055
3056 /* Now find the end of the whole brace expression */
3057 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003058 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003059 rest = next_brace_sub(rest);
3060 if (rest == NULL) {
3061 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003062 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003063 }
3064 debug_printf_glob("rest:%s\n", rest);
3065 }
3066 rest_len = strlen(++rest) + 1;
3067
3068 /* We are sure the brace expression is well-formed */
3069
3070 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003071 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003072
3073 /* We have a brace expression. BEGIN points to the opening {,
3074 * NEXT points past the terminator of the first element, and REST
3075 * points past the final }. We will accumulate result names from
3076 * recursive runs for each brace alternative in the buffer using
3077 * GLOB_APPEND. */
3078
3079 p = begin + 1;
3080 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003081 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003082 memcpy(
3083 mempcpy(
3084 mempcpy(new_pattern_buf,
3085 /* We know the prefix for all sub-patterns */
3086 pattern, begin - pattern),
3087 p, next - p),
3088 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003089
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003090 /* Note: glob_brace() may garble new_pattern_buf[].
3091 * That's why we re-copy prefix every time (1st memcpy above).
3092 */
3093 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02003094 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003095 /* We saw the last entry */
3096 break;
3097 }
3098 p = next + 1;
3099 next = next_brace_sub(next);
3100 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003101 free(new_pattern_buf);
3102 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003103
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003104 simple_glob:
3105 {
3106 int gr;
3107 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003108
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003109 memset(&globdata, 0, sizeof(globdata));
3110 gr = glob(pattern, 0, NULL, &globdata);
3111 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
3112 if (gr != 0) {
3113 if (gr == GLOB_NOMATCH) {
3114 globfree(&globdata);
3115 /* NB: garbles parameter */
3116 unbackslash(pattern);
3117 o_addstr_with_NUL(o, pattern);
3118 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3119 return o_save_ptr_helper(o, n);
3120 }
3121 if (gr == GLOB_NOSPACE)
3122 bb_error_msg_and_die(bb_msg_memory_exhausted);
3123 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3124 * but we didn't specify it. Paranoia again. */
3125 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
3126 }
3127 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3128 char **argv = globdata.gl_pathv;
3129 while (1) {
3130 o_addstr_with_NUL(o, *argv);
3131 n = o_save_ptr_helper(o, n);
3132 argv++;
3133 if (!*argv)
3134 break;
3135 }
3136 }
3137 globfree(&globdata);
3138 }
3139 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003140}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003141/* Performs globbing on last list[],
3142 * saving each result as a new list[].
3143 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003144static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003145{
3146 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003147
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003148 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003149 if (!o->data)
3150 return o_save_ptr_helper(o, n);
3151 pattern = o->data + o_get_last_ptr(o, n);
3152 debug_printf_glob("glob pattern '%s'\n", pattern);
3153 if (!glob_needed(pattern)) {
3154 /* unbackslash last string in o in place, fix length */
3155 o->length = unbackslash(pattern) - o->data;
3156 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
3157 return o_save_ptr_helper(o, n);
3158 }
3159
3160 copy = xstrdup(pattern);
3161 /* "forget" pattern in o */
3162 o->length = pattern - o->data;
3163 n = glob_brace(copy, o, n);
3164 free(copy);
3165 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003166 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003167 return n;
3168}
3169
Denys Vlasenko238081f2010-10-03 14:26:26 +02003170#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003171
3172/* Helper */
3173static int glob_needed(const char *s)
3174{
3175 while (*s) {
3176 if (*s == '\\') {
3177 if (!s[1])
3178 return 0;
3179 s += 2;
3180 continue;
3181 }
3182 if (*s == '*' || *s == '[' || *s == '?')
3183 return 1;
3184 s++;
3185 }
3186 return 0;
3187}
3188/* Performs globbing on last list[],
3189 * saving each result as a new list[].
3190 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003191static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003192{
3193 glob_t globdata;
3194 int gr;
3195 char *pattern;
3196
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003197 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003198 if (!o->data)
3199 return o_save_ptr_helper(o, n);
3200 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003201 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003202 if (!glob_needed(pattern)) {
3203 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003204 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003205 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003206 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003207 return o_save_ptr_helper(o, n);
3208 }
3209
3210 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003211 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3212 * If we glob "*.\*" and don't find anything, we need
3213 * to fall back to using literal "*.*", but GLOB_NOCHECK
3214 * will return "*.\*"!
3215 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003216 gr = glob(pattern, 0, NULL, &globdata);
3217 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003218 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003219 if (gr == GLOB_NOMATCH) {
3220 globfree(&globdata);
3221 goto literal;
3222 }
3223 if (gr == GLOB_NOSPACE)
3224 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003225 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3226 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003227 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003228 }
3229 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3230 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003231 /* "forget" pattern in o */
3232 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003233 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003234 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003235 n = o_save_ptr_helper(o, n);
3236 argv++;
3237 if (!*argv)
3238 break;
3239 }
3240 }
3241 globfree(&globdata);
3242 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003243 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003244 return n;
3245}
3246
Denys Vlasenko238081f2010-10-03 14:26:26 +02003247#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003248
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003249/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003250 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003251static int o_save_ptr(o_string *o, int n)
3252{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003253 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003254 /* If o->has_empty_slot, list[n] was already globbed
3255 * (if it was requested back then when it was filled)
3256 * so don't do that again! */
3257 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003258 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003259 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003260 return o_save_ptr_helper(o, n);
3261}
3262
3263/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003264static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003265{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003266 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003267 int string_start;
3268
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003269 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3270 if (DEBUG_EXPAND)
3271 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003272 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003273 list = (char**)o->data;
3274 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3275 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003276 while (n) {
3277 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003278 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003279 }
3280 return list;
3281}
3282
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003283static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003284
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003285/* Returns pi->next - next pipe in the list */
3286static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003287{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003288 struct pipe *next;
3289 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003290
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003291 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003292 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003293 struct command *command;
3294 struct redir_struct *r, *rnext;
3295
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003296 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003297 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003298 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003299 if (DEBUG_CLEAN) {
3300 int a;
3301 char **p;
3302 for (a = 0, p = command->argv; *p; a++, p++) {
3303 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3304 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003305 }
3306 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003307 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003308 }
3309 /* not "else if": on syntax error, we may have both! */
3310 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003311 debug_printf_clean(" begin group (cmd_type:%d)\n",
3312 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003313 free_pipe_list(command->group);
3314 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003315 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003316 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003317 /* else is crucial here.
3318 * If group != NULL, child_func is meaningless */
3319#if ENABLE_HUSH_FUNCTIONS
3320 else if (command->child_func) {
3321 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3322 command->child_func->parent_cmd = NULL;
3323 }
3324#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003325#if !BB_MMU
3326 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003327 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003328#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003329 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003330 debug_printf_clean(" redirect %d%s",
3331 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003332 /* guard against the case >$FOO, where foo is unset or blank */
3333 if (r->rd_filename) {
3334 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3335 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003336 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003337 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003338 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003339 rnext = r->next;
3340 free(r);
3341 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003342 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003343 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003344 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003345 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003346#if ENABLE_HUSH_JOB
3347 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003348 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003349#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003350
3351 next = pi->next;
3352 free(pi);
3353 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003354}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003355
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003356static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003357{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003358 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003359#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003360 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003361#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003362 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003363 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003364 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003365}
3366
3367
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003368/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003369
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003370#ifndef debug_print_tree
3371static void debug_print_tree(struct pipe *pi, int lvl)
3372{
3373 static const char *const PIPE[] = {
3374 [PIPE_SEQ] = "SEQ",
3375 [PIPE_AND] = "AND",
3376 [PIPE_OR ] = "OR" ,
3377 [PIPE_BG ] = "BG" ,
3378 };
3379 static const char *RES[] = {
3380 [RES_NONE ] = "NONE" ,
3381# if ENABLE_HUSH_IF
3382 [RES_IF ] = "IF" ,
3383 [RES_THEN ] = "THEN" ,
3384 [RES_ELIF ] = "ELIF" ,
3385 [RES_ELSE ] = "ELSE" ,
3386 [RES_FI ] = "FI" ,
3387# endif
3388# if ENABLE_HUSH_LOOPS
3389 [RES_FOR ] = "FOR" ,
3390 [RES_WHILE] = "WHILE",
3391 [RES_UNTIL] = "UNTIL",
3392 [RES_DO ] = "DO" ,
3393 [RES_DONE ] = "DONE" ,
3394# endif
3395# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3396 [RES_IN ] = "IN" ,
3397# endif
3398# if ENABLE_HUSH_CASE
3399 [RES_CASE ] = "CASE" ,
3400 [RES_CASE_IN ] = "CASE_IN" ,
3401 [RES_MATCH] = "MATCH",
3402 [RES_CASE_BODY] = "CASE_BODY",
3403 [RES_ESAC ] = "ESAC" ,
3404# endif
3405 [RES_XXXX ] = "XXXX" ,
3406 [RES_SNTX ] = "SNTX" ,
3407 };
3408 static const char *const CMDTYPE[] = {
3409 "{}",
3410 "()",
3411 "[noglob]",
3412# if ENABLE_HUSH_FUNCTIONS
3413 "func()",
3414# endif
3415 };
3416
3417 int pin, prn;
3418
3419 pin = 0;
3420 while (pi) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003421 fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
3422 lvl*2, "",
3423 pin,
3424 (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
3425 RES[pi->res_word],
3426 pi->followup, PIPE[pi->followup]
3427 );
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003428 prn = 0;
3429 while (prn < pi->num_cmds) {
3430 struct command *command = &pi->cmds[prn];
3431 char **argv = command->argv;
3432
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003433 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003434 lvl*2, "", prn,
3435 command->assignment_cnt);
Denys Vlasenko5807e182018-02-08 19:19:04 +01003436#if ENABLE_HUSH_LINENO_VAR
3437 fdprintf(2, " LINENO:%u", command->lineno);
3438#endif
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003439 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003440 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003441 CMDTYPE[command->cmd_type],
3442 argv
3443# if !BB_MMU
3444 , " group_as_string:", command->group_as_string
3445# else
3446 , "", ""
3447# endif
3448 );
3449 debug_print_tree(command->group, lvl+1);
3450 prn++;
3451 continue;
3452 }
3453 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003454 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003455 argv++;
3456 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003457 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003458 prn++;
3459 }
3460 pi = pi->next;
3461 pin++;
3462 }
3463}
3464#endif /* debug_print_tree */
3465
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003466static struct pipe *new_pipe(void)
3467{
Eric Andersen25f27032001-04-26 23:22:31 +00003468 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003469 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003470 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003471 return pi;
3472}
3473
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003474/* Command (member of a pipe) is complete, or we start a new pipe
3475 * if ctx->command is NULL.
3476 * No errors possible here.
3477 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003478static int done_command(struct parse_context *ctx)
3479{
3480 /* The command is really already in the pipe structure, so
3481 * advance the pipe counter and make a new, null command. */
3482 struct pipe *pi = ctx->pipe;
3483 struct command *command = ctx->command;
3484
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003485#if 0 /* Instead we emit error message at run time */
3486 if (ctx->pending_redirect) {
3487 /* For example, "cmd >" (no filename to redirect to) */
Denys Vlasenko39701202017-08-02 19:44:05 +02003488 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003489 ctx->pending_redirect = NULL;
3490 }
3491#endif
3492
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003493 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003494 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003495 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003496 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003497 }
3498 pi->num_cmds++;
3499 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003500 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003501 } else {
3502 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3503 }
3504
3505 /* Only real trickiness here is that the uncommitted
3506 * command structure is not counted in pi->num_cmds. */
3507 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003508 ctx->command = command = &pi->cmds[pi->num_cmds];
3509 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003510 memset(command, 0, sizeof(*command));
Denys Vlasenko5807e182018-02-08 19:19:04 +01003511#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003512 command->lineno = G.lineno;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003513 debug_printf_parse("command->lineno = G.lineno (%u)\n", G.lineno);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01003514#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003515 return pi->num_cmds; /* used only for 0/nonzero check */
3516}
3517
3518static void done_pipe(struct parse_context *ctx, pipe_style type)
3519{
3520 int not_null;
3521
3522 debug_printf_parse("done_pipe entered, followup %d\n", type);
3523 /* Close previous command */
3524 not_null = done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003525#if HAS_KEYWORDS
3526 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3527 ctx->ctx_inverted = 0;
3528 ctx->pipe->res_word = ctx->ctx_res_w;
3529#endif
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003530 if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
3531 /* Necessary since && and || have precedence over &:
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003532 * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
3533 * in a backgrounded subshell.
3534 */
3535 struct pipe *pi;
3536 struct command *command;
3537
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003538 /* Is this actually this construct, all pipes end with && or ||? */
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003539 pi = ctx->list_head;
3540 while (pi != ctx->pipe) {
3541 if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
3542 goto no_conv;
3543 pi = pi->next;
3544 }
3545
3546 debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
3547 pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
3548 pi = xzalloc(sizeof(*pi));
3549 pi->followup = PIPE_BG;
3550 pi->num_cmds = 1;
3551 pi->cmds = xzalloc(sizeof(pi->cmds[0]));
3552 command = &pi->cmds[0];
3553 if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
3554 command->cmd_type = CMD_NORMAL;
3555 command->group = ctx->list_head;
3556#if !BB_MMU
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003557 command->group_as_string = xstrndup(
3558 ctx->as_string.data,
3559 ctx->as_string.length - 1 /* do not copy last char, "&" */
3560 );
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003561#endif
3562 /* Replace all pipes in ctx with one newly created */
3563 ctx->list_head = ctx->pipe = pi;
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02003564 } else {
3565 no_conv:
3566 ctx->pipe->followup = type;
Denys Vlasenkoee553b92017-07-15 22:51:55 +02003567 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003568
3569 /* Without this check, even just <enter> on command line generates
3570 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003571 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003572 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003573#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003574 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003575#endif
3576#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003577 || ctx->ctx_res_w == RES_DONE
3578 || ctx->ctx_res_w == RES_FOR
3579 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003580#endif
3581#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003582 || ctx->ctx_res_w == RES_ESAC
3583#endif
3584 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003585 struct pipe *new_p;
3586 debug_printf_parse("done_pipe: adding new pipe: "
3587 "not_null:%d ctx->ctx_res_w:%d\n",
3588 not_null, ctx->ctx_res_w);
3589 new_p = new_pipe();
3590 ctx->pipe->next = new_p;
3591 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003592 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003593 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003594 * This is used to control execution.
3595 * RES_FOR and RES_IN are NOT sticky (needed to support
3596 * cases where variable or value happens to match a keyword):
3597 */
3598#if ENABLE_HUSH_LOOPS
3599 if (ctx->ctx_res_w == RES_FOR
3600 || ctx->ctx_res_w == RES_IN)
3601 ctx->ctx_res_w = RES_NONE;
3602#endif
3603#if ENABLE_HUSH_CASE
3604 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003605 ctx->ctx_res_w = RES_CASE_BODY;
3606 if (ctx->ctx_res_w == RES_CASE)
3607 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003608#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003609 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003610 /* Create the memory for command, roughly:
3611 * ctx->pipe->cmds = new struct command;
3612 * ctx->command = &ctx->pipe->cmds[0];
3613 */
3614 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003615 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003616 }
3617 debug_printf_parse("done_pipe return\n");
3618}
3619
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003620static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003621{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003622 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003623 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003624 /* Create the memory for command, roughly:
3625 * ctx->pipe->cmds = new struct command;
3626 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003627 */
3628 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003629}
3630
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003631/* If a reserved word is found and processed, parse context is modified
3632 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003633 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003634#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003635struct reserved_combo {
3636 char literal[6];
3637 unsigned char res;
3638 unsigned char assignment_flag;
3639 int flag;
3640};
3641enum {
3642 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003643# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003644 FLAG_IF = (1 << RES_IF ),
3645 FLAG_THEN = (1 << RES_THEN ),
3646 FLAG_ELIF = (1 << RES_ELIF ),
3647 FLAG_ELSE = (1 << RES_ELSE ),
3648 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003649# endif
3650# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003651 FLAG_FOR = (1 << RES_FOR ),
3652 FLAG_WHILE = (1 << RES_WHILE),
3653 FLAG_UNTIL = (1 << RES_UNTIL),
3654 FLAG_DO = (1 << RES_DO ),
3655 FLAG_DONE = (1 << RES_DONE ),
3656 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003657# endif
3658# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003659 FLAG_MATCH = (1 << RES_MATCH),
3660 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003661# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003662 FLAG_START = (1 << RES_XXXX ),
3663};
3664
3665static const struct reserved_combo* match_reserved_word(o_string *word)
3666{
Eric Andersen25f27032001-04-26 23:22:31 +00003667 /* Mostly a list of accepted follow-up reserved words.
3668 * FLAG_END means we are done with the sequence, and are ready
3669 * to turn the compound list into a command.
3670 * FLAG_START means the word must start a new compound list.
3671 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003672 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003673# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003674 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3675 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3676 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3677 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3678 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3679 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003680# endif
3681# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003682 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3683 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3684 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3685 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3686 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3687 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003688# endif
3689# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003690 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3691 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003692# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003693 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003694 const struct reserved_combo *r;
3695
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003696 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003697 if (strcmp(word->data, r->literal) == 0)
3698 return r;
3699 }
3700 return NULL;
3701}
Denys Vlasenko5807e182018-02-08 19:19:04 +01003702/* Return NULL: not a keyword, else: keyword
Denis Vlasenkobb929512009-04-16 10:59:40 +00003703 */
Denys Vlasenko5807e182018-02-08 19:19:04 +01003704static const struct reserved_combo* reserved_word(o_string *word, struct parse_context *ctx)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003705{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003706# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003707 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003708 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003709 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003710# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003711 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003712
Denys Vlasenko38292b62010-09-05 14:49:40 +02003713 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003714 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003715 r = match_reserved_word(word);
3716 if (!r)
Denys Vlasenko5807e182018-02-08 19:19:04 +01003717 return r; /* NULL */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003718
3719 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003720# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003721 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3722 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003723 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003724 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003725# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003726 if (r->flag == 0) { /* '!' */
3727 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003728 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003729 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003730 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003731 ctx->ctx_inverted = 1;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003732 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003733 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003734 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003735 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003736
Denys Vlasenko9e55a152017-07-10 10:01:12 +02003737 old = xmemdup(ctx, sizeof(*ctx));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003738 debug_printf_parse("push stack %p\n", old);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003739 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003740 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003741 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003742 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003743 ctx->ctx_res_w = RES_SNTX;
Denys Vlasenko5807e182018-02-08 19:19:04 +01003744 return r;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003745 } else {
3746 /* "{...} fi" is ok. "{...} if" is not
3747 * Example:
3748 * if { echo foo; } then { echo bar; } fi */
3749 if (ctx->command->group)
3750 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003751 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003752
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003753 ctx->ctx_res_w = r->res;
3754 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003755 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003756 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003757
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003758 if (ctx->old_flag & FLAG_END) {
3759 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003760
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003761 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003762 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003763 old = ctx->stack;
3764 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003765 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003766# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003767 /* At this point, the compound command's string is in
3768 * ctx->as_string... except for the leading keyword!
3769 * Consider this example: "echo a | if true; then echo a; fi"
3770 * ctx->as_string will contain "true; then echo a; fi",
3771 * with "if " remaining in old->as_string!
3772 */
3773 {
3774 char *str;
3775 int len = old->as_string.length;
3776 /* Concatenate halves */
3777 o_addstr(&old->as_string, ctx->as_string.data);
3778 o_free_unsafe(&ctx->as_string);
3779 /* Find where leading keyword starts in first half */
3780 str = old->as_string.data + len;
3781 if (str > old->as_string.data)
3782 str--; /* skip whitespace after keyword */
3783 while (str > old->as_string.data && isalpha(str[-1]))
3784 str--;
3785 /* Ugh, we're done with this horrid hack */
3786 old->command->group_as_string = xstrdup(str);
3787 debug_printf_parse("pop, remembering as:'%s'\n",
3788 old->command->group_as_string);
3789 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003790# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003791 *ctx = *old; /* physical copy */
3792 free(old);
3793 }
Denys Vlasenko5807e182018-02-08 19:19:04 +01003794 return r;
Eric Andersen25f27032001-04-26 23:22:31 +00003795}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003796#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003797
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003798/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003799 * Normal return is 0. Syntax errors return 1.
3800 * Note: on return, word is reset, but not o_free'd!
3801 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003802static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003803{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003804 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003805
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003806 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003807 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003808 debug_printf_parse("done_word return 0: true null, ignored\n");
3809 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003810 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003811
Eric Andersen25f27032001-04-26 23:22:31 +00003812 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003813 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3814 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003815 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3816 * "2.7 Redirection
3817 * ...the word that follows the redirection operator
3818 * shall be subjected to tilde expansion, parameter expansion,
3819 * command substitution, arithmetic expansion, and quote
3820 * removal. Pathname expansion shall not be performed
3821 * on the word by a non-interactive shell; an interactive
3822 * shell may perform it, but shall do so only when
3823 * the expansion would result in one word."
3824 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003825 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003826 /* Cater for >\file case:
3827 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3828 * Same with heredocs:
3829 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3830 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003831 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3832 unbackslash(ctx->pending_redirect->rd_filename);
3833 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003834 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003835 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3836 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003837 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003838 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003839 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003840 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003841#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003842# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003843 if (ctx->ctx_dsemicolon
3844 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3845 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003846 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003847 /* ctx->ctx_res_w = RES_MATCH; */
3848 ctx->ctx_dsemicolon = 0;
3849 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003850# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003851 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003852# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003853 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3854 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003855# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003856# if ENABLE_HUSH_CASE
3857 && ctx->ctx_res_w != RES_CASE
3858# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003859 ) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003860 const struct reserved_combo *reserved;
3861 reserved = reserved_word(word, ctx);
3862 debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003863 if (reserved) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01003864# if ENABLE_HUSH_LINENO_VAR
3865/* Case:
3866 * "while ...; do
3867 * cmd ..."
3868 * If we don't close the pipe _now_, immediately after "do", lineno logic
3869 * sees "cmd" as starting at "do" - i.e., at the previous line.
3870 */
3871 if (0
3872 IF_HUSH_IF(|| reserved->res == RES_THEN)
3873 IF_HUSH_IF(|| reserved->res == RES_ELIF)
3874 IF_HUSH_IF(|| reserved->res == RES_ELSE)
3875 IF_HUSH_LOOPS(|| reserved->res == RES_DO)
3876 ) {
3877 done_pipe(ctx, PIPE_SEQ);
3878 }
3879# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003880 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003881 debug_printf_parse("done_word return %d\n",
3882 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003883 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003884 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01003885# if BASH_TEST2
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003886 if (strcmp(word->data, "[[") == 0) {
3887 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3888 }
3889 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003890# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003891 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003892#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003893 if (command->group) {
3894 /* "{ echo foo; } echo bar" - bad */
3895 syntax_error_at(word->data);
3896 debug_printf_parse("done_word return 1: syntax error, "
3897 "groups and arglists don't mix\n");
3898 return 1;
3899 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003900
3901 /* If this word wasn't an assignment, next ones definitely
3902 * can't be assignments. Even if they look like ones. */
3903 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3904 && word->o_assignment != WORD_IS_KEYWORD
3905 ) {
3906 word->o_assignment = NOT_ASSIGNMENT;
3907 } else {
3908 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3909 command->assignment_cnt++;
3910 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3911 }
3912 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3913 word->o_assignment = MAYBE_ASSIGNMENT;
3914 }
3915 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003916 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003917 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003918 }
Eric Andersen25f27032001-04-26 23:22:31 +00003919
Denis Vlasenko06810332007-05-21 23:30:54 +00003920#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003921 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003922 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003923 || !is_well_formed_var_name(command->argv[0], '\0')
3924 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003925 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003926 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003927 return 1;
3928 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003929 /* Force FOR to have just one word (variable name) */
3930 /* NB: basically, this makes hush see "for v in ..."
3931 * syntax as if it is "for v; in ...". FOR and IN become
3932 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003933 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003934 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003935#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003936#if ENABLE_HUSH_CASE
3937 /* Force CASE to have just one word */
3938 if (ctx->ctx_res_w == RES_CASE) {
3939 done_pipe(ctx, PIPE_SEQ);
3940 }
3941#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003942
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003943 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003944
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003945 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003946 return 0;
3947}
3948
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003949
3950/* Peek ahead in the input to find out if we have a "&n" construct,
3951 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003952 * Return:
3953 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3954 * REDIRFD_SYNTAX_ERR if syntax error,
3955 * REDIRFD_TO_FILE if no & was seen,
3956 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003957 */
3958#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003959#define parse_redir_right_fd(as_string, input) \
3960 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003961#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003962static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003963{
3964 int ch, d, ok;
3965
3966 ch = i_peek(input);
3967 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003968 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003969
3970 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003971 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003972 ch = i_peek(input);
3973 if (ch == '-') {
3974 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003975 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003976 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003977 }
3978 d = 0;
3979 ok = 0;
3980 while (ch != EOF && isdigit(ch)) {
3981 d = d*10 + (ch-'0');
3982 ok = 1;
3983 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003984 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003985 ch = i_peek(input);
3986 }
3987 if (ok) return d;
3988
3989//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3990
3991 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003992 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003993}
3994
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003995/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003996 */
3997static int parse_redirect(struct parse_context *ctx,
3998 int fd,
3999 redir_type style,
4000 struct in_str *input)
4001{
4002 struct command *command = ctx->command;
4003 struct redir_struct *redir;
4004 struct redir_struct **redirp;
4005 int dup_num;
4006
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004007 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004008 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004009 /* Check for a '>&1' type redirect */
4010 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4011 if (dup_num == REDIRFD_SYNTAX_ERR)
4012 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004013 } else {
4014 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004015 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004016 if (dup_num) { /* <<-... */
4017 ch = i_getch(input);
4018 nommu_addchr(&ctx->as_string, ch);
4019 ch = i_peek(input);
4020 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004021 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004022
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004023 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004024 int ch = i_peek(input);
4025 if (ch == '|') {
4026 /* >|FILE redirect ("clobbering" >).
4027 * Since we do not support "set -o noclobber" yet,
4028 * >| and > are the same for now. Just eat |.
4029 */
4030 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004031 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004032 }
4033 }
4034
4035 /* Create a new redir_struct and append it to the linked list */
4036 redirp = &command->redirects;
4037 while ((redir = *redirp) != NULL) {
4038 redirp = &(redir->next);
4039 }
4040 *redirp = redir = xzalloc(sizeof(*redir));
4041 /* redir->next = NULL; */
4042 /* redir->rd_filename = NULL; */
4043 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004044 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004045
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004046 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4047 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004048
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004049 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004050 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004051 /* Erik had a check here that the file descriptor in question
4052 * is legit; I postpone that to "run time"
4053 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004054 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4055 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004056 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004057#if 0 /* Instead we emit error message at run time */
4058 if (ctx->pending_redirect) {
4059 /* For example, "cmd > <file" */
Denys Vlasenko39701202017-08-02 19:44:05 +02004060 syntax_error("invalid redirect");
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02004061 }
4062#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004063 /* Set ctx->pending_redirect, so we know what to do at the
4064 * end of the next parsed word. */
4065 ctx->pending_redirect = redir;
4066 }
4067 return 0;
4068}
4069
Eric Andersen25f27032001-04-26 23:22:31 +00004070/* If a redirect is immediately preceded by a number, that number is
4071 * supposed to tell which file descriptor to redirect. This routine
4072 * looks for such preceding numbers. In an ideal world this routine
4073 * needs to handle all the following classes of redirects...
4074 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4075 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4076 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4077 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004078 *
4079 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4080 * "2.7 Redirection
4081 * ... If n is quoted, the number shall not be recognized as part of
4082 * the redirection expression. For example:
4083 * echo \2>a
4084 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02004085 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004086 *
4087 * A -1 return means no valid number was found,
4088 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004089 */
4090static int redirect_opt_num(o_string *o)
4091{
4092 int num;
4093
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004094 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004095 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004096 num = bb_strtou(o->data, NULL, 10);
4097 if (errno || num < 0)
4098 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004099 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004100 return num;
4101}
4102
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004103#if BB_MMU
4104#define fetch_till_str(as_string, input, word, skip_tabs) \
4105 fetch_till_str(input, word, skip_tabs)
4106#endif
4107static char *fetch_till_str(o_string *as_string,
4108 struct in_str *input,
4109 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004110 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004111{
4112 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004113 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004114 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004115 int ch;
4116
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004117 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02004118
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004119 while (1) {
4120 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004121 if (ch != EOF)
4122 nommu_addchr(as_string, ch);
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004123 if (ch == '\n' || ch == EOF) {
4124 check_heredoc_end:
4125 if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
4126 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4127 heredoc.data[past_EOL] = '\0';
4128 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4129 return heredoc.data;
4130 }
4131 if (ch == '\n') {
4132 /* This is a new line.
4133 * Remember position and backslash-escaping status.
4134 */
4135 o_addchr(&heredoc, ch);
4136 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004137 jump_in:
Denys Vlasenko0f018b32017-07-29 20:43:26 +02004138 past_EOL = heredoc.length;
4139 /* Get 1st char of next line, possibly skipping leading tabs */
4140 do {
4141 ch = i_getch(input);
4142 if (ch != EOF)
4143 nommu_addchr(as_string, ch);
4144 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
4145 /* If this immediately ended the line,
4146 * go back to end-of-line checks.
4147 */
4148 if (ch == '\n')
4149 goto check_heredoc_end;
4150 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004151 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004152 }
4153 if (ch == EOF) {
4154 o_free_unsafe(&heredoc);
4155 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004156 }
4157 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004158 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02004159 if (prev == '\\' && ch == '\\')
4160 /* Correctly handle foo\\<eol> (not a line cont.) */
4161 prev = 0; /* not \ */
4162 else
4163 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004164 }
4165}
4166
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004167/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4168 * and load them all. There should be exactly heredoc_cnt of them.
4169 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004170static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4171{
4172 struct pipe *pi = ctx->list_head;
4173
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004174 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004175 int i;
4176 struct command *cmd = pi->cmds;
4177
4178 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4179 pi->num_cmds,
4180 cmd->argv ? cmd->argv[0] : "NONE");
4181 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004182 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004183
4184 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4185 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004186 while (redir) {
4187 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004188 char *p;
4189
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004190 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004191 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004192 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004193 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004194 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004195 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004196 return 1;
4197 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004198 free(redir->rd_filename);
4199 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004200 heredoc_cnt--;
4201 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004202 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004203 }
4204 cmd++;
4205 }
4206 pi = pi->next;
4207 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004208#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004209 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004210 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004211 bb_error_msg_and_die("heredoc BUG 2");
4212#endif
4213 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004214}
4215
4216
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004217static int run_list(struct pipe *pi);
4218#if BB_MMU
4219#define parse_stream(pstring, input, end_trigger) \
4220 parse_stream(input, end_trigger)
4221#endif
4222static struct pipe *parse_stream(char **pstring,
4223 struct in_str *input,
4224 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004225
Eric Andersen25f27032001-04-26 23:22:31 +00004226
Denys Vlasenkoc2704542009-11-20 19:14:19 +01004227#if !ENABLE_HUSH_FUNCTIONS
4228#define parse_group(dest, ctx, input, ch) \
4229 parse_group(ctx, input, ch)
4230#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004231static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004232 struct in_str *input, int ch)
4233{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004234 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004235 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004236 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004237 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004238 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004239 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004240
4241 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004242#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02004243 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004244 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004245 if (done_word(dest, ctx))
4246 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004247 if (!command->argv)
4248 goto skip; /* (... */
4249 if (command->argv[1]) { /* word word ... (... */
4250 syntax_error_unexpected_ch('(');
4251 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004252 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004253 /* it is "word(..." or "word (..." */
4254 do
4255 ch = i_getch(input);
4256 while (ch == ' ' || ch == '\t');
4257 if (ch != ')') {
4258 syntax_error_unexpected_ch(ch);
4259 return 1;
4260 }
4261 nommu_addchr(&ctx->as_string, ch);
4262 do
4263 ch = i_getch(input);
4264 while (ch == ' ' || ch == '\t' || ch == '\n');
4265 if (ch != '{') {
4266 syntax_error_unexpected_ch(ch);
4267 return 1;
4268 }
4269 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004270 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004271 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004272 }
4273#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004274
4275#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004276 if (command->argv /* word [word]{... */
4277 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004278 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004279 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004280 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004281 debug_printf_parse("parse_group return 1: "
4282 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004283 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004284 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004285#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004286
4287#if ENABLE_HUSH_FUNCTIONS
4288 skip:
4289#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004290 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004291 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004292 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004293 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004294 } else {
4295 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004296 ch = i_peek(input);
4297 if (ch != ' ' && ch != '\t' && ch != '\n'
4298 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4299 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004300 syntax_error_unexpected_ch(ch);
4301 return 1;
4302 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004303 if (ch != '(') {
4304 ch = i_getch(input);
4305 nommu_addchr(&ctx->as_string, ch);
4306 }
Eric Andersen25f27032001-04-26 23:22:31 +00004307 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004308
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004309 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004310#if BB_MMU
4311# define as_string NULL
4312#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004313 char *as_string = NULL;
4314#endif
4315 pipe_list = parse_stream(&as_string, input, endch);
4316#if !BB_MMU
4317 if (as_string)
4318 o_addstr(&ctx->as_string, as_string);
4319#endif
4320 /* empty ()/{} or parse error? */
4321 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00004322 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004323 if (!BB_MMU)
4324 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004325 debug_printf_parse("parse_group return 1: "
4326 "parse_stream returned %p\n", pipe_list);
4327 return 1;
4328 }
4329 command->group = pipe_list;
4330#if !BB_MMU
4331 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4332 command->group_as_string = as_string;
4333 debug_printf_parse("end of group, remembering as:'%s'\n",
4334 command->group_as_string);
4335#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004336#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004337 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004338 debug_printf_parse("parse_group return 0\n");
4339 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004340 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004341}
4342
Denys Vlasenko46e64982016-09-29 19:50:55 +02004343static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4344{
4345 for (;;) {
4346 int ch, ch2;
4347
4348 ch = i_getch(input);
4349 if (ch != '\\')
4350 return ch;
4351 ch2 = i_peek(input);
4352 if (ch2 != '\n')
4353 return ch;
4354 /* backslash+newline, skip it */
4355 i_getch(input);
4356 }
4357}
4358
Denys Vlasenko657086a2016-09-29 18:07:42 +02004359static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4360{
4361 for (;;) {
4362 int ch, ch2;
4363
4364 ch = i_peek(input);
4365 if (ch != '\\')
4366 return ch;
4367 ch2 = i_peek2(input);
4368 if (ch2 != '\n')
4369 return ch;
4370 /* backslash+newline, skip it */
4371 i_getch(input);
4372 i_getch(input);
4373 }
4374}
4375
Denys Vlasenko0b883582016-12-23 16:49:07 +01004376#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004377/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004378static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004379/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004380static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004381{
4382 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004383 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004384 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004385 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004386 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004387 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004388 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004389 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004390 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004391 }
4392}
4393/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004394static int add_till_double_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 Vlasenko7b4f3f12008-06-10 18:04:32 +00004404 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004405 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004406 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004407 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004408 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004409 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004410 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4411 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004412 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004413 continue;
4414 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004415 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004416 }
4417}
4418/* Process `cmd` - copy contents until "`" is seen. Complicated by
4419 * \` quoting.
4420 * "Within the backquoted style of command substitution, backslash
4421 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4422 * The search for the matching backquote shall be satisfied by the first
4423 * backquote found without a preceding backslash; during this search,
4424 * if a non-escaped backquote is encountered within a shell comment,
4425 * a here-document, an embedded command substitution of the $(command)
4426 * form, or a quoted string, undefined results occur. A single-quoted
4427 * or double-quoted string that begins, but does not end, within the
4428 * "`...`" sequence produces undefined results."
4429 * Example Output
4430 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4431 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004432static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004433{
4434 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004435 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004436 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004437 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004438 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004439 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4440 ch = i_getch(input);
4441 if (ch != '`'
4442 && ch != '$'
4443 && ch != '\\'
4444 && (!in_dquote || ch != '"')
4445 ) {
4446 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004447 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004448 }
4449 if (ch == EOF) {
4450 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004451 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004452 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004453 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004454 }
4455}
4456/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4457 * quoting and nested ()s.
4458 * "With the $(command) style of command substitution, all characters
4459 * following the open parenthesis to the matching closing parenthesis
4460 * constitute the command. Any valid shell script can be used for command,
4461 * except a script consisting solely of redirections which produces
4462 * unspecified results."
4463 * Example Output
4464 * echo $(echo '(TEST)' BEST) (TEST) BEST
4465 * echo $(echo 'TEST)' BEST) TEST) BEST
4466 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004467 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004468 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004469 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004470 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4471 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004472 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004473#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004474static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004475{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004476 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004477 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004478# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004479 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004480# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004481 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4482
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004483 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004484 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004485 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004486 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004487 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004488 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004489 if (ch == end_ch
4490# if BASH_SUBSTR || BASH_PATTERN_SUBST
Denys Vlasenko55f81332018-03-02 18:12:12 +01004491 || ch == end_char2
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004492# endif
4493 ) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004494 if (!dbl)
4495 break;
4496 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004497 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004498 i_getch(input); /* eat second ')' */
4499 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004500 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004501 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004502 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004503 //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004504 if (ch == '(' || ch == '{') {
4505 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004506 if (!add_till_closing_bracket(dest, input, ch))
4507 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004508 o_addchr(dest, ch);
4509 continue;
4510 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004511 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004512 if (!add_till_single_quote(dest, input))
4513 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004514 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004515 continue;
4516 }
4517 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004518 if (!add_till_double_quote(dest, input))
4519 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004520 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004521 continue;
4522 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004523 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004524 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4525 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004526 o_addchr(dest, ch);
4527 continue;
4528 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004529 if (ch == '\\') {
4530 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004531 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004532 if (ch == EOF) {
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004533 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004534 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004535 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004536#if 0
4537 if (ch == '\n') {
4538 /* "backslash+newline", ignore both */
4539 o_delchr(dest); /* undo insertion of '\' */
4540 continue;
4541 }
4542#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004543 o_addchr(dest, ch);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01004544 //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004545 continue;
4546 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004547 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004548 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004549}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004550#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004551
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004552/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004553#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004554#define parse_dollar(as_string, dest, input, quote_mask) \
4555 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004556#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004557#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004558static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004559 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004560 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004561{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004562 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004563
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004564 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004565 if (isalpha(ch)) {
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004566 make_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004567 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004568 nommu_addchr(as_string, ch);
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004569 /*make_var1:*/
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004570 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004571 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004572 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004573 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004574 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004575 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004576 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004577 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004578 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004579 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004580 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004581 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004582 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004583 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004584 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004585 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004586 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004587 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004588 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004589 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004590 o_addchr(dest, ch | quote_mask);
4591 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004592 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004593 case '$': /* pid */
4594 case '!': /* last bg pid */
4595 case '?': /* last exit code */
4596 case '#': /* number of args */
4597 case '*': /* args */
4598 case '@': /* args */
4599 goto make_one_char_var;
4600 case '{': {
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004601 char len_single_ch;
4602
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004603 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4604
Denys Vlasenko74369502010-05-21 19:52:01 +02004605 ch = i_getch(input); /* eat '{' */
4606 nommu_addchr(as_string, ch);
4607
Denys Vlasenko46e64982016-09-29 19:50:55 +02004608 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004609 /* It should be ${?}, or ${#var},
4610 * or even ${?+subst} - operator acting on a special variable,
4611 * or the beginning of variable name.
4612 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004613 if (ch == EOF
4614 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4615 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004616 bad_dollar_syntax:
4617 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004618 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4619 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004620 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004621 nommu_addchr(as_string, ch);
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004622 len_single_ch = ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004623 ch |= quote_mask;
4624
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004625 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004626 * However, this regresses some of our testsuite cases
4627 * which check invalid constructs like ${%}.
4628 * Oh well... let's check that the var name part is fine... */
4629
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004630 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004631 unsigned pos;
4632
Denys Vlasenko74369502010-05-21 19:52:01 +02004633 o_addchr(dest, ch);
4634 debug_printf_parse(": '%c'\n", ch);
4635
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004636 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004637 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004638 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004639 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004640
Denys Vlasenko74369502010-05-21 19:52:01 +02004641 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004642 unsigned end_ch;
4643 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004644 /* handle parameter expansions
4645 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4646 */
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004647 if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
4648 if (len_single_ch != '#'
4649 /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
4650 || i_peek(input) != '}'
4651 ) {
4652 goto bad_dollar_syntax;
4653 }
4654 /* else: it's "length of C" ${#C} op,
4655 * where C is a single char
4656 * special var name, e.g. ${#!}.
4657 */
4658 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004659 /* Eat everything until closing '}' (or ':') */
4660 end_ch = '}';
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004661 if (BASH_SUBSTR
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004662 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004663 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004664 ) {
4665 /* It's ${var:N[:M]} thing */
4666 end_ch = '}' * 0x100 + ':';
4667 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004668 if (BASH_PATTERN_SUBST
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004669 && ch == '/'
4670 ) {
4671 /* It's ${var/[/]pattern[/repl]} thing */
4672 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4673 i_getch(input);
4674 nommu_addchr(as_string, '/');
4675 ch = '\\';
4676 }
4677 end_ch = '}' * 0x100 + '/';
4678 }
4679 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004680 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004681 if (!BB_MMU)
4682 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004683#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004684 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004685 if (last_ch == 0) /* error? */
4686 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004687#else
4688#error Simple code to only allow ${var} is not implemented
4689#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004690 if (as_string) {
4691 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004692 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004693 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004694
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004695 if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
4696 && (end_ch & 0xff00)
4697 ) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004698 /* close the first block: */
4699 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004700 /* while parsing N from ${var:N[:M]}
4701 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004702 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004703 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004704 end_ch = '}';
4705 goto again;
4706 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004707 /* got '}' */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004708 if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004709 /* it's ${var:N} - emulate :999999999 */
4710 o_addstr(dest, "999999999");
4711 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004712 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004713 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004714 }
Denys Vlasenko2093ad22017-07-26 00:07:27 +02004715 len_single_ch = 0; /* it can't be ${#C} op */
Denys Vlasenko74369502010-05-21 19:52:01 +02004716 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004717 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4718 break;
4719 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004720#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004721 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004722 unsigned pos;
4723
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004724 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004725 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004726# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004727 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004728 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004729 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004730 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4731 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004732 if (!BB_MMU)
4733 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004734 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4735 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004736 if (as_string) {
4737 o_addstr(as_string, dest->data + pos);
4738 o_addchr(as_string, ')');
4739 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004740 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004741 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004742 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004743 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004744# endif
4745# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004746 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4747 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004748 if (!BB_MMU)
4749 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004750 if (!add_till_closing_bracket(dest, input, ')'))
4751 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004752 if (as_string) {
4753 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004754 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004755 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004756 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004757# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004758 break;
4759 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004760#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004761 case '_':
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004762 goto make_var;
4763#if 0
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004764 /* TODO: $_ and $-: */
4765 /* $_ Shell or shell script name; or last argument of last command
4766 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4767 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004768 /* $- Option flags set by set builtin or shell options (-i etc) */
Denys Vlasenko0ca31982018-01-25 13:20:50 +01004769 ch = i_getch(input);
4770 nommu_addchr(as_string, ch);
4771 ch = i_peek_and_eat_bkslash_nl(input);
4772 if (isalnum(ch)) { /* it's $_name or $_123 */
4773 ch = '_';
4774 goto make_var1;
4775 }
4776 /* else: it's $_ */
4777#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004778 default:
4779 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004780 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004781 debug_printf_parse("parse_dollar return 1 (ok)\n");
4782 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004783#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004784}
4785
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004786#if BB_MMU
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004787# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004788#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4789 encode_string(dest, input, dquote_end, process_bkslash)
4790# else
4791/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4792#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4793 encode_string(dest, input, dquote_end)
4794# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004795#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004796
4797#else /* !MMU */
4798
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004799# if BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004800/* all parameters are needed, no macro tricks */
4801# else
4802#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4803 encode_string(as_string, dest, input, dquote_end)
4804# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004805#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004806static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004807 o_string *dest,
4808 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004809 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004810 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004811{
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01004812#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004813 const int process_bkslash = 1;
4814#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004815 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004816 int next;
4817
4818 again:
4819 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004820 if (ch != EOF)
4821 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004822 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004823 debug_printf_parse("encode_string return 1 (ok)\n");
4824 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004825 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004826 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004827 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004828 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004829 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004830 }
4831 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004832 if (ch != '\n') {
4833 next = i_peek(input);
4834 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004835 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004836 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004837 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004838 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004839 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004840 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004841 }
4842 /* bash:
4843 * "The backslash retains its special meaning [in "..."]
4844 * only when followed by one of the following characters:
4845 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004846 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004847 * NB: in (unquoted) heredoc, above does not apply to ",
4848 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004849 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004850 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004851 ch = i_getch(input); /* eat next */
4852 if (ch == '\n')
4853 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004854 } /* else: ch remains == '\\', and we double it below: */
4855 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004856 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004857 goto again;
4858 }
4859 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004860 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4861 debug_printf_parse("encode_string return 0: "
4862 "parse_dollar returned 0 (error)\n");
4863 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004864 }
4865 goto again;
4866 }
4867#if ENABLE_HUSH_TICK
4868 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004869 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004870 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4871 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004872 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4873 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004874 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4875 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004876 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004877 }
4878#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004879 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004880 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004881#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004882}
4883
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004884/*
4885 * Scan input until EOF or end_trigger char.
4886 * Return a list of pipes to execute, or NULL on EOF
4887 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004888 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004889 * reset parsing machinery and start parsing anew,
4890 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004891 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004892static struct pipe *parse_stream(char **pstring,
4893 struct in_str *input,
4894 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004895{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004896 struct parse_context ctx;
4897 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004898 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004899
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004900 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004901 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004902 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004903 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004904 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004905 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004906
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004907 /* If very first arg is "" or '', dest.data may end up NULL.
4908 * Preventing this: */
4909 o_addchr(&dest, '\0');
4910 dest.length = 0;
4911
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004912 /* We used to separate words on $IFS here. This was wrong.
4913 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004914 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004915 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004916
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004917 if (MAYBE_ASSIGNMENT != 0)
4918 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004919 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004920 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004921 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004922 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004923 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004924 int ch;
4925 int next;
4926 int redir_fd;
4927 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004928
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004929 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004930 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004931 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004932 if (ch == EOF) {
4933 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004934
4935 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004936 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004937 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004938 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004939 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004940 syntax_error_unterm_ch('(');
4941 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004942 }
Denys Vlasenko42246472016-11-07 16:22:35 +01004943 if (end_trigger == '}') {
4944 syntax_error_unterm_ch('{');
4945 goto parse_error;
4946 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004947
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004948 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004949 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004950 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004951 o_free(&dest);
4952 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004953 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004954 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004955 /* (this makes bare "&" cmd a no-op.
4956 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004957 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004958 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004959 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004960 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004961 pi = NULL;
4962 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004963#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004964 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004965 if (pstring)
4966 *pstring = ctx.as_string.data;
4967 else
4968 o_free_unsafe(&ctx.as_string);
4969#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004970 debug_leave();
4971 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004972 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004973 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004974 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004975
4976 next = '\0';
4977 if (ch != '\n')
4978 next = i_peek(input);
4979
4980 is_special = "{}<>;&|()#'" /* special outside of "str" */
Denys Vlasenko932b9972018-01-11 12:39:48 +01004981 "\\$\"" IF_HUSH_TICK("`") /* always special */
4982 SPECIAL_VAR_SYMBOL_STR;
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004983 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004984 if (ctx.command->argv /* word [word]{... - non-special */
4985 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004986 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004987 || (next != ';' /* }; - special */
4988 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004989 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004990 && next != '&' /* }& and }&& ... - special */
4991 && next != '|' /* }|| ... - special */
4992 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004993 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004994 ) {
4995 /* They are not special, skip "{}" */
4996 is_special += 2;
4997 }
4998 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004999 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005000
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005001 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005002 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005003 o_addQchr(&dest, ch);
5004 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5005 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005006 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005007 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005008 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005009 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005010 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005011 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005012 continue;
5013 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005014
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005015 if (is_blank) {
Denys Vlasenko5807e182018-02-08 19:19:04 +01005016#if ENABLE_HUSH_LINENO_VAR
5017/* Case:
5018 * "while ...; do<whitespace><newline>
5019 * cmd ..."
5020 * would think that "cmd" starts in <whitespace> -
5021 * i.e., at the previous line.
5022 * We need to skip all whitespace before newlines.
5023 */
Denys Vlasenkof7869012018-02-08 19:39:42 +01005024 while (ch != '\n') {
5025 next = i_peek(input);
5026 if (next != ' ' && next != '\t' && next != '\n')
5027 break; /* next char is not ws */
5028 ch = i_getch(input);
Denys Vlasenko5807e182018-02-08 19:19:04 +01005029 }
Denys Vlasenkof7869012018-02-08 19:39:42 +01005030 /* ch == last eaten whitespace char */
Denys Vlasenko5807e182018-02-08 19:19:04 +01005031#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005032 if (done_word(&dest, &ctx)) {
5033 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005034 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005035 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005036 /* Is this a case when newline is simply ignored?
5037 * Some examples:
5038 * "cmd | <newline> cmd ..."
5039 * "case ... in <newline> word) ..."
5040 */
5041 if (IS_NULL_CMD(ctx.command)
5042 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00005043 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005044 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005045 * Without check #1, interactive shell
5046 * ignores even bare <newline>,
5047 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005048 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005049 * ps2> _ <=== wrong, should be ps1
5050 * Without check #2, "cmd & <newline>"
5051 * is similarly mistreated.
5052 * (BTW, this makes "cmd & cmd"
5053 * and "cmd && cmd" non-orthogonal.
5054 * Really, ask yourself, why
5055 * "cmd && <newline>" doesn't start
5056 * cmd but waits for more input?
Denys Vlasenkob24e55d2017-07-16 20:29:35 +02005057 * The only reason is that it might be
5058 * a "cmd1 && <nl> cmd2 &" construct,
5059 * cmd1 may need to run in BG).
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005060 */
5061 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005062 if (pi->num_cmds != 0 /* check #1 */
5063 && pi->followup != PIPE_BG /* check #2 */
5064 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01005065 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01005066 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00005067 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005068 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005069 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005070 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5071 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005072 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005073 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005074 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005075 heredoc_cnt = 0;
5076 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005077 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005078 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005079 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005080 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005081 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005082 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005083 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005084
5085 /* "cmd}" or "cmd }..." without semicolon or &:
5086 * } is an ordinary char in this case, even inside { cmd; }
5087 * Pathological example: { ""}; } should exec "}" cmd
5088 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005089 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005090 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005091 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005092 ) {
5093 goto ordinary_char;
5094 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005095 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
5096 /* Generally, there should be semicolon: "cmd; }"
5097 * However, bash allows to omit it if "cmd" is
5098 * a group. Examples:
5099 * { { echo 1; } }
5100 * {(echo 1)}
5101 * { echo 0 >&2 | { echo 1; } }
5102 * { while false; do :; done }
5103 * { case a in b) ;; esac }
5104 */
5105 if (ctx.command->group)
5106 goto term_group;
5107 goto ordinary_char;
5108 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005109 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005110 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005111 goto skip_end_trigger;
5112 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005113 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01005114 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005115 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005116 && (ch != ';' || heredoc_cnt == 0)
5117#if ENABLE_HUSH_CASE
5118 && (ch != ')'
5119 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02005120 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005121 )
5122#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005123 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005124 if (heredoc_cnt) {
5125 /* This is technically valid:
5126 * { cat <<HERE; }; echo Ok
5127 * heredoc
5128 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005129 * HERE
5130 * but we don't support this.
5131 * We require heredoc to be in enclosing {}/(),
5132 * if any.
5133 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005134 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005135 goto parse_error;
5136 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005137 if (done_word(&dest, &ctx)) {
5138 goto parse_error;
5139 }
5140 done_pipe(&ctx, PIPE_SEQ);
5141 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005142 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00005143 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005144 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01005145 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005146 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005147 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005148#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02005149 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005150 if (pstring)
5151 *pstring = ctx.as_string.data;
5152 else
5153 o_free_unsafe(&ctx.as_string);
5154#endif
Denys Vlasenko39701202017-08-02 19:44:05 +02005155 if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
5156 /* Example: bare "{ }", "()" */
5157 G.last_exitcode = 2; /* bash compat */
5158 syntax_error_unexpected_ch(ch);
5159 goto parse_error2;
5160 }
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005161 debug_printf_parse("parse_stream return %p: "
5162 "end_trigger char found\n",
5163 ctx.list_head);
Denys Vlasenko39701202017-08-02 19:44:05 +02005164 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005165 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005166 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005167 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005168 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005169 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005170 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005171
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005172 /* Catch <, > before deciding whether this word is
5173 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5174 switch (ch) {
5175 case '>':
5176 redir_fd = redirect_opt_num(&dest);
5177 if (done_word(&dest, &ctx)) {
5178 goto parse_error;
5179 }
5180 redir_style = REDIRECT_OVERWRITE;
5181 if (next == '>') {
5182 redir_style = REDIRECT_APPEND;
5183 ch = i_getch(input);
5184 nommu_addchr(&ctx.as_string, ch);
5185 }
5186#if 0
5187 else if (next == '(') {
5188 syntax_error(">(process) not supported");
5189 goto parse_error;
5190 }
5191#endif
5192 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5193 goto parse_error;
5194 continue; /* back to top of while (1) */
5195 case '<':
5196 redir_fd = redirect_opt_num(&dest);
5197 if (done_word(&dest, &ctx)) {
5198 goto parse_error;
5199 }
5200 redir_style = REDIRECT_INPUT;
5201 if (next == '<') {
5202 redir_style = REDIRECT_HEREDOC;
5203 heredoc_cnt++;
5204 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5205 ch = i_getch(input);
5206 nommu_addchr(&ctx.as_string, ch);
5207 } else if (next == '>') {
5208 redir_style = REDIRECT_IO;
5209 ch = i_getch(input);
5210 nommu_addchr(&ctx.as_string, ch);
5211 }
5212#if 0
5213 else if (next == '(') {
5214 syntax_error("<(process) not supported");
5215 goto parse_error;
5216 }
5217#endif
5218 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5219 goto parse_error;
5220 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005221 case '#':
5222 if (dest.length == 0 && !dest.has_quoted_part) {
5223 /* skip "#comment" */
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005224 /* note: we do not add it to &ctx.as_string */
5225/* TODO: in bash:
5226 * comment inside $() goes to the next \n, even inside quoted string (!):
5227 * cmd "$(cmd2 #comment)" - syntax error
5228 * cmd "`cmd2 #comment`" - ok
5229 * We accept both (comment ends where command subst ends, in both cases).
5230 */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005231 while (1) {
5232 ch = i_peek(input);
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005233 if (ch == '\n') {
5234 nommu_addchr(&ctx.as_string, '\n');
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005235 break;
Denys Vlasenko25f3b732017-10-22 15:55:48 +02005236 }
5237 ch = i_getch(input);
5238 if (ch == EOF)
5239 break;
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005240 }
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005241 continue; /* back to top of while (1) */
5242 }
5243 break;
5244 case '\\':
5245 if (next == '\n') {
5246 /* It's "\<newline>" */
5247#if !BB_MMU
5248 /* Remove trailing '\' from ctx.as_string */
5249 ctx.as_string.data[--ctx.as_string.length] = '\0';
5250#endif
5251 ch = i_getch(input); /* eat it */
5252 continue; /* back to top of while (1) */
5253 }
5254 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005255 }
5256
5257 if (dest.o_assignment == MAYBE_ASSIGNMENT
5258 /* check that we are not in word in "a=1 2>word b=1": */
5259 && !ctx.pending_redirect
5260 ) {
5261 /* ch is a special char and thus this word
5262 * cannot be an assignment */
5263 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005264 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005265 }
5266
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02005267 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
5268
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005269 switch (ch) {
Denys Vlasenko932b9972018-01-11 12:39:48 +01005270 case SPECIAL_VAR_SYMBOL:
5271 /* Convert raw ^C to corresponding special variable reference */
5272 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5273 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5274 /* fall through */
5275 case '#':
5276 /* non-comment #: "echo a#b" etc */
5277 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005278 break;
5279 case '\\':
5280 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005281 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005282 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005283 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005284 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01005285 /* note: ch != '\n' (that case does not reach this place) */
5286 o_addchr(&dest, '\\');
5287 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
5288 o_addchr(&dest, ch);
5289 nommu_addchr(&ctx.as_string, ch);
5290 /* Example: echo Hello \2>file
5291 * we need to know that word 2 is quoted */
5292 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005293 break;
5294 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005295 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005296 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005297 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005298 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005299 }
Eric Andersen25f27032001-04-26 23:22:31 +00005300 break;
5301 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005302 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005303 if (next == '\'' && !ctx.pending_redirect) {
5304 insert_empty_quoted_str_marker:
5305 nommu_addchr(&ctx.as_string, next);
5306 i_getch(input); /* eat second ' */
5307 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5308 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5309 } else {
5310 while (1) {
5311 ch = i_getch(input);
5312 if (ch == EOF) {
5313 syntax_error_unterm_ch('\'');
5314 goto parse_error;
5315 }
5316 nommu_addchr(&ctx.as_string, ch);
5317 if (ch == '\'')
5318 break;
Denys Vlasenko9809a822018-01-13 19:14:27 +01005319 if (ch == SPECIAL_VAR_SYMBOL) {
5320 /* Convert raw ^C to corresponding special variable reference */
5321 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5322 o_addchr(&dest, SPECIAL_VAR_QUOTED_SVS);
5323 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005324 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005325 }
Eric Andersen25f27032001-04-26 23:22:31 +00005326 }
Eric Andersen25f27032001-04-26 23:22:31 +00005327 break;
5328 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005329 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005330 if (next == '"' && !ctx.pending_redirect)
5331 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005332 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005333 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005334 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005335 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005336 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00005337 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005338#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005339 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005340 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005341
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005342 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5343 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02005344 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005345 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5346 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005347# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005348 o_addstr(&ctx.as_string, dest.data + pos);
5349 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005350# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005351 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5352 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005353 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005354 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005355#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005356 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005357#if ENABLE_HUSH_CASE
5358 case_semi:
5359#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005360 if (done_word(&dest, &ctx)) {
5361 goto parse_error;
5362 }
5363 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005364#if ENABLE_HUSH_CASE
5365 /* Eat multiple semicolons, detect
5366 * whether it means something special */
5367 while (1) {
5368 ch = i_peek(input);
5369 if (ch != ';')
5370 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005371 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005372 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005373 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005374 ctx.ctx_dsemicolon = 1;
5375 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005376 break;
5377 }
5378 }
5379#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005380 new_cmd:
5381 /* We just finished a cmd. New one may start
5382 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005383 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005384 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00005385 break;
5386 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005387 if (done_word(&dest, &ctx)) {
5388 goto parse_error;
5389 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005390 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005391 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005392 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005393 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005394 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005395 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005396 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005397 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005398 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005399 if (done_word(&dest, &ctx)) {
5400 goto parse_error;
5401 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005402#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005403 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005404 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005405#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005406 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005407 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005408 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005409 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005410 } else {
5411 /* we could pick up a file descriptor choice here
5412 * with redirect_opt_num(), but bash doesn't do it.
5413 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005414 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005415 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005416 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005417 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005418#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005419 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005420 if (ctx.ctx_res_w == RES_MATCH
5421 && ctx.command->argv == NULL /* not (word|(... */
5422 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005423 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005424 ) {
5425 continue;
5426 }
5427#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005428 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005429 if (parse_group(&dest, &ctx, input, ch) != 0) {
5430 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005431 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005432 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005433 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005434#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005435 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005436 goto case_semi;
5437#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005438 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005439 /* proper use of this character is caught by end_trigger:
5440 * if we see {, we call parse_group(..., end_trigger='}')
5441 * and it will match } earlier (not here). */
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005442 G.last_exitcode = 2;
Denys Vlasenko39701202017-08-02 19:44:05 +02005443 syntax_error_unexpected_ch(ch);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005444 goto parse_error2;
Eric Andersen25f27032001-04-26 23:22:31 +00005445 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005446 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005447 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005448 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005449 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005450
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005451 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005452 G.last_exitcode = 1;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02005453 parse_error2:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005454 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005455 struct parse_context *pctx;
5456 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005457
5458 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005459 * Sample for finding leaks on syntax error recovery path.
5460 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005461 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005462 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005463 * while if (true | { true;}); then echo ok; fi; do break; done
5464 * 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 +00005465 */
5466 pctx = &ctx;
5467 do {
5468 /* Update pipe/command counts,
5469 * otherwise freeing may miss some */
5470 done_pipe(pctx, PIPE_SEQ);
5471 debug_printf_clean("freeing list %p from ctx %p\n",
5472 pctx->list_head, pctx);
5473 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005474 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005475 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005476#if !BB_MMU
5477 o_free_unsafe(&pctx->as_string);
5478#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005479 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005480 if (pctx != &ctx) {
5481 free(pctx);
5482 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005483 IF_HAS_KEYWORDS(pctx = p2;)
5484 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005485
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005486 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005487#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005488 if (pstring)
5489 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005490#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005491 debug_leave();
5492 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005493 }
Eric Andersen25f27032001-04-26 23:22:31 +00005494}
5495
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005496
5497/*** Execution routines ***/
5498
5499/* Expansion can recurse, need forward decls: */
Denys Vlasenko637982f2017-07-06 01:52:23 +02005500#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005501/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5502#define expand_string_to_string(str, do_unbackslash) \
5503 expand_string_to_string(str)
5504#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005505static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005506#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005507static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005508#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005509
5510/* expand_strvec_to_strvec() takes a list of strings, expands
5511 * all variable references within and returns a pointer to
5512 * a list of expanded strings, possibly with larger number
5513 * of strings. (Think VAR="a b"; echo $VAR).
5514 * This new list is allocated as a single malloc block.
5515 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005516 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005517 * Caller can deallocate entire list by single free(list). */
5518
Denys Vlasenko238081f2010-10-03 14:26:26 +02005519/* A horde of its helpers come first: */
5520
5521static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5522{
5523 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005524 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005525
Denys Vlasenko9e800222010-10-03 14:28:04 +02005526#if ENABLE_HUSH_BRACE_EXPANSION
5527 if (c == '{' || c == '}') {
5528 /* { -> \{, } -> \} */
5529 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005530 /* And now we want to add { or } and continue:
5531 * o_addchr(o, c);
5532 * continue;
Denys Vlasenko10ad6222017-04-17 16:13:32 +02005533 * luckily, just falling through achieves this.
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005534 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005535 }
5536#endif
5537 o_addchr(o, c);
5538 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005539 /* \z -> \\\z; \<eol> -> \\<eol> */
5540 o_addchr(o, '\\');
5541 if (len) {
5542 len--;
5543 o_addchr(o, '\\');
5544 o_addchr(o, *str++);
5545 }
5546 }
5547 }
5548}
5549
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005550/* Store given string, finalizing the word and starting new one whenever
5551 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005552 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5553 * Return in *ended_with_ifs:
5554 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5555 */
5556static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005557{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005558 int last_is_ifs = 0;
5559
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005560 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005561 int word_len;
5562
5563 if (!*str) /* EOL - do not finalize word */
5564 break;
5565 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005566 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005567 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005568 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005569 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005570 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005571 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005572 * Example: "v='\*'; echo b$v" prints "b\*"
5573 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005574 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005575 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005576 /*/ Why can't we do it easier? */
5577 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5578 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5579 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005580 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005581 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005582 if (!*str) /* EOL - do not finalize word */
5583 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005584 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005585
5586 /* We know str here points to at least one IFS char */
5587 last_is_ifs = 1;
5588 str += strspn(str, G.ifs); /* skip IFS chars */
5589 if (!*str) /* EOL - do not finalize word */
5590 break;
5591
5592 /* Start new word... but not always! */
5593 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005594 if (output->has_quoted_part
5595 /* Case "v=' a'; echo $v":
5596 * here nothing precedes the space in $v expansion,
5597 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005598 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005599 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005600 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005601 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005602 o_addchr(output, '\0');
5603 debug_print_list("expand_on_ifs", output, n);
5604 n = o_save_ptr(output, n);
5605 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005606 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005607
5608 if (ended_with_ifs)
5609 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005610 debug_print_list("expand_on_ifs[1]", output, n);
5611 return n;
5612}
5613
5614/* Helper to expand $((...)) and heredoc body. These act as if
5615 * they are in double quotes, with the exception that they are not :).
5616 * Just the rules are similar: "expand only $var and `cmd`"
5617 *
5618 * Returns malloced string.
5619 * As an optimization, we return NULL if expansion is not needed.
5620 */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005621#if !BASH_PATTERN_SUBST
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005622/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5623#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5624 encode_then_expand_string(str)
5625#endif
5626static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005627{
Denys Vlasenko637982f2017-07-06 01:52:23 +02005628#if !BASH_PATTERN_SUBST
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01005629 enum { do_unbackslash = 1 };
Denys Vlasenko637982f2017-07-06 01:52:23 +02005630#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005631 char *exp_str;
5632 struct in_str input;
5633 o_string dest = NULL_O_STRING;
5634
5635 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005636 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005637#if ENABLE_HUSH_TICK
5638 && !strchr(str, '`')
5639#endif
5640 ) {
5641 return NULL;
5642 }
5643
5644 /* We need to expand. Example:
5645 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5646 */
5647 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005648 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005649//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005650 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005651 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005652 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5653 o_free_unsafe(&dest);
5654 return exp_str;
5655}
5656
Denys Vlasenko0b883582016-12-23 16:49:07 +01005657#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005658static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005659{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005660 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005661 arith_t res;
5662 char *exp_str;
5663
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005664 math_state.lookupvar = get_local_var_value;
5665 math_state.setvar = set_local_var_from_halves;
5666 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005667 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005668 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005669 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005670 if (errmsg_p)
5671 *errmsg_p = math_state.errmsg;
5672 if (math_state.errmsg)
Denys Vlasenko39701202017-08-02 19:44:05 +02005673 msg_and_die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005674 return res;
5675}
5676#endif
5677
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005678#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005679/* ${var/[/]pattern[/repl]} helpers */
5680static char *strstr_pattern(char *val, const char *pattern, int *size)
5681{
5682 while (1) {
5683 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5684 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5685 if (end) {
5686 *size = end - val;
5687 return val;
5688 }
5689 if (*val == '\0')
5690 return NULL;
5691 /* Optimization: if "*pat" did not match the start of "string",
5692 * we know that "tring", "ring" etc will not match too:
5693 */
5694 if (pattern[0] == '*')
5695 return NULL;
5696 val++;
5697 }
5698}
5699static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5700{
5701 char *result = NULL;
5702 unsigned res_len = 0;
5703 unsigned repl_len = strlen(repl);
5704
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005705 /* Null pattern never matches, including if "var" is empty */
5706 if (!pattern[0])
5707 return result; /* NULL, no replaces happened */
5708
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005709 while (1) {
5710 int size;
5711 char *s = strstr_pattern(val, pattern, &size);
5712 if (!s)
5713 break;
5714
5715 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
Denys Vlasenko0675b032017-07-24 02:17:05 +02005716 strcpy(mempcpy(result + res_len, val, s - val), repl);
5717 res_len += (s - val) + repl_len;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005718 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5719
5720 val = s + size;
5721 if (exp_op == '/')
5722 break;
5723 }
Denys Vlasenko0675b032017-07-24 02:17:05 +02005724 if (*val && result) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005725 result = xrealloc(result, res_len + strlen(val) + 1);
5726 strcpy(result + res_len, val);
5727 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5728 }
5729 debug_printf_varexp("result:'%s'\n", result);
5730 return result;
5731}
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005732#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005733
5734/* Helper:
5735 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5736 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005737static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005738{
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005739 const char *val;
5740 char *to_be_freed;
5741 char *p;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005742 char *var;
5743 char first_char;
5744 char exp_op;
5745 char exp_save = exp_save; /* for compiler */
5746 char *exp_saveptr; /* points to expansion operator */
5747 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005748 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005749
Denys Vlasenko0ca31982018-01-25 13:20:50 +01005750 val = NULL;
5751 to_be_freed = NULL;
5752 p = *pp;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005753 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005754 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005755 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005756 arg0 = arg[0];
5757 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005758 exp_op = 0;
5759
Denys Vlasenko2093ad22017-07-26 00:07:27 +02005760 if (first_char == '#' && arg[1] /* ${#...} but not ${#} */
5761 && (!exp_saveptr /* and ( not(${#<op_char>...}) */
5762 || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
5763 ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005764 ) {
5765 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005766 var++;
5767 exp_op = 'L';
5768 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005769 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005770 if (exp_saveptr /* if 2nd char is one of expansion operators */
5771 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5772 ) {
5773 /* ${?:0}, ${#[:]%0} etc */
5774 exp_saveptr = var + 1;
5775 } else {
5776 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5777 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5778 }
5779 exp_op = exp_save = *exp_saveptr;
5780 if (exp_op) {
5781 exp_word = exp_saveptr + 1;
5782 if (exp_op == ':') {
5783 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005784//TODO: try ${var:} and ${var:bogus} in non-bash config
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005785 if (BASH_SUBSTR
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005786 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005787 ) {
5788 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5789 exp_op = ':';
5790 exp_word--;
5791 }
5792 }
5793 *exp_saveptr = '\0';
5794 } /* else: it's not an expansion op, but bare ${var} */
5795 }
5796
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005797 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005798 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005799 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005800 int n = xatoi_positive(var);
5801 if (n < G.global_argc)
5802 val = G.global_argv[n];
5803 /* else val remains NULL: $N with too big N */
5804 } else {
5805 switch (var[0]) {
5806 case '$': /* pid */
5807 val = utoa(G.root_pid);
5808 break;
5809 case '!': /* bg pid */
5810 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5811 break;
5812 case '?': /* exitcode */
5813 val = utoa(G.last_exitcode);
5814 break;
5815 case '#': /* argc */
5816 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5817 break;
5818 default:
5819 val = get_local_var_value(var);
5820 }
5821 }
5822
5823 /* Handle any expansions */
5824 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005825 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005826 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005827 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005828 debug_printf_expand("%s\n", val);
5829 } else if (exp_op) {
5830 if (exp_op == '%' || exp_op == '#') {
5831 /* Standard-mandated substring removal ops:
5832 * ${parameter%word} - remove smallest suffix pattern
5833 * ${parameter%%word} - remove largest suffix pattern
5834 * ${parameter#word} - remove smallest prefix pattern
5835 * ${parameter##word} - remove largest prefix pattern
5836 *
5837 * Word is expanded to produce a glob pattern.
5838 * Then var's value is matched to it and matching part removed.
5839 */
5840 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005841 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005842 char *exp_exp_word;
5843 char *loc;
5844 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005845 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005846 exp_word++;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005847 debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
Denys Vlasenkod4802c62018-03-02 20:48:36 +01005848 /*
5849 * process_bkslash:1 unbackslash:1 breaks this:
5850 * a='a\\'; echo ${a%\\\\} # correct output is: a
5851 * process_bkslash:1 unbackslash:0 breaks this:
5852 * a='a}'; echo ${a%\}} # correct output is: a
5853 */
5854 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005855 if (exp_exp_word)
5856 exp_word = exp_exp_word;
Denys Vlasenko55f81332018-03-02 18:12:12 +01005857 debug_printf_expand("expand: exp_exp_word:'%s'\n", exp_word);
Denys Vlasenko4f870492010-09-10 11:06:01 +02005858 /* HACK ALERT. We depend here on the fact that
5859 * G.global_argv and results of utoa and get_local_var_value
5860 * are actually in writable memory:
5861 * scan_and_match momentarily stores NULs there. */
5862 t = (char*)val;
5863 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenko55f81332018-03-02 18:12:12 +01005864 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 +02005865 free(exp_exp_word);
5866 if (loc) { /* match was found */
5867 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005868 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005869 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005870 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005871 }
5872 }
5873 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005874#if BASH_PATTERN_SUBST
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005875 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005876 /* It's ${var/[/]pattern[/repl]} thing.
5877 * Note that in encoded form it has TWO parts:
5878 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005879 * and if // is used, it is encoded as \:
5880 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005881 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005882 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005883 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005884 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005885 * by the usual expansion rules:
5886 * >az; >bz;
5887 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5888 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5889 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5890 * v='a bz'; echo ${v/a*z/\z} prints "z"
5891 * (note that a*z _pattern_ is never globbed!)
5892 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005893 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005894 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005895 if (!pattern)
5896 pattern = xstrdup(exp_word);
5897 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5898 *p++ = SPECIAL_VAR_SYMBOL;
5899 exp_word = p;
5900 p = strchr(p, SPECIAL_VAR_SYMBOL);
5901 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005902 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005903 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5904 /* HACK ALERT. We depend here on the fact that
5905 * G.global_argv and results of utoa and get_local_var_value
5906 * are actually in writable memory:
5907 * replace_pattern momentarily stores NULs there. */
5908 t = (char*)val;
5909 to_be_freed = replace_pattern(t,
5910 pattern,
5911 (repl ? repl : exp_word),
5912 exp_op);
5913 if (to_be_freed) /* at least one replace happened */
5914 val = to_be_freed;
5915 free(pattern);
5916 free(repl);
Denys Vlasenkocba79a82018-01-25 14:07:40 +01005917 } else {
5918 /* Empty variable always gives nothing */
5919 // "v=''; echo ${v/*/w}" prints "", not "w"
5920 /* Just skip "replace" part */
5921 *p++ = SPECIAL_VAR_SYMBOL;
5922 p = strchr(p, SPECIAL_VAR_SYMBOL);
5923 *p = '\0';
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005924 }
5925 }
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005926#endif /* BASH_PATTERN_SUBST */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005927 else if (exp_op == ':') {
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01005928#if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005929 /* It's ${var:N[:M]} bashism.
5930 * Note that in encoded form it has TWO parts:
5931 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5932 */
5933 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005934 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005935
Denys Vlasenko063847d2010-09-15 13:33:02 +02005936 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5937 if (errmsg)
5938 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005939 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5940 *p++ = SPECIAL_VAR_SYMBOL;
5941 exp_word = p;
5942 p = strchr(p, SPECIAL_VAR_SYMBOL);
5943 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005944 len = expand_and_evaluate_arith(exp_word, &errmsg);
5945 if (errmsg)
5946 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005947 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005948 if (beg < 0) {
5949 /* negative beg counts from the end */
5950 beg = (arith_t)strlen(val) + beg;
5951 if (beg < 0) /* ${v: -999999} is "" */
5952 beg = len = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005953 }
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005954 debug_printf_varexp("from val:'%s'\n", val);
5955 if (len < 0) {
5956 /* in bash, len=-n means strlen()-n */
5957 len = (arith_t)strlen(val) - beg + len;
5958 if (len < 0) /* bash compat */
Denys Vlasenko39701202017-08-02 19:44:05 +02005959 msg_and_die_if_script("%s: substring expression < 0", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005960 }
Denys Vlasenko0ba80e42017-07-17 16:50:20 +02005961 if (len <= 0 || !val || beg >= strlen(val)) {
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005962 arith_err:
5963 val = NULL;
5964 } else {
5965 /* Paranoia. What if user entered 9999999999999
5966 * which fits in arith_t but not int? */
5967 if (len >= INT_MAX)
5968 len = INT_MAX;
5969 val = to_be_freed = xstrndup(val + beg, len);
5970 }
5971 debug_printf_varexp("val:'%s'\n", val);
5972#else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
Denys Vlasenko39701202017-08-02 19:44:05 +02005973 msg_and_die_if_script("malformed ${%s:...}", var);
Denys Vlasenkoe32b6502017-07-17 16:46:57 +02005974 val = NULL;
5975#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005976 } else { /* one of "-=+?" */
5977 /* Standard-mandated substitution ops:
5978 * ${var?word} - indicate error if unset
5979 * If var is unset, word (or a message indicating it is unset
5980 * if word is null) is written to standard error
5981 * and the shell exits with a non-zero exit status.
5982 * Otherwise, the value of var is substituted.
5983 * ${var-word} - use default value
5984 * If var is unset, word is substituted.
5985 * ${var=word} - assign and use default value
5986 * If var is unset, word is assigned to var.
5987 * In all cases, final value of var is substituted.
5988 * ${var+word} - use alternative value
5989 * If var is unset, null is substituted.
5990 * Otherwise, word is substituted.
5991 *
5992 * Word is subjected to tilde expansion, parameter expansion,
5993 * command substitution, and arithmetic expansion.
5994 * If word is not needed, it is not expanded.
5995 *
5996 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5997 * but also treat null var as if it is unset.
5998 */
5999 int use_word = (!val || ((exp_save == ':') && !val[0]));
6000 if (exp_op == '+')
6001 use_word = !use_word;
6002 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
6003 (exp_save == ':') ? "true" : "false", use_word);
6004 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006005 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006006 if (to_be_freed)
6007 exp_word = to_be_freed;
6008 if (exp_op == '?') {
6009 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006010 msg_and_die_if_script("%s: %s",
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006011 var,
Denys Vlasenko645c6972017-07-25 15:18:57 +02006012 exp_word[0]
6013 ? exp_word
6014 : "parameter null or not set"
6015 /* ash has more specific messages, a-la: */
6016 /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006017 );
6018//TODO: how interactive bash aborts expansion mid-command?
6019 } else {
6020 val = exp_word;
6021 }
6022
6023 if (exp_op == '=') {
6024 /* ${var=[word]} or ${var:=[word]} */
6025 if (isdigit(var[0]) || var[0] == '#') {
6026 /* mimic bash message */
Denys Vlasenko39701202017-08-02 19:44:05 +02006027 msg_and_die_if_script("$%s: cannot assign in this way", var);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006028 val = NULL;
6029 } else {
6030 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02006031 set_local_var(new_var, /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006032 }
6033 }
6034 }
6035 } /* one of "-=+?" */
6036
6037 *exp_saveptr = exp_save;
6038 } /* if (exp_op) */
6039
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006040 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006041
6042 *pp = p;
6043 *to_be_freed_pp = to_be_freed;
6044 return val;
6045}
6046
6047/* Expand all variable references in given string, adding words to list[]
6048 * at n, n+1,... positions. Return updated n (so that list[n] is next one
6049 * to be filled). This routine is extremely tricky: has to deal with
6050 * variables/parameters with whitespace, $* and $@, and constructs like
6051 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006052static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006053{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006054 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006055 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006056 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006057 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006058 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006059 char *p;
6060
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006061 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
6062 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006063 debug_print_list("expand_vars_to_list", output, n);
6064 n = o_save_ptr(output, n);
6065 debug_print_list("expand_vars_to_list[0]", output, n);
6066
6067 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
6068 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006069 char *to_be_freed = NULL;
6070 const char *val = NULL;
6071#if ENABLE_HUSH_TICK
6072 o_string subst_result = NULL_O_STRING;
6073#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006074#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006075 char arith_buf[sizeof(arith_t)*3 + 2];
6076#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006077
6078 if (ended_in_ifs) {
6079 o_addchr(output, '\0');
6080 n = o_save_ptr(output, n);
6081 ended_in_ifs = 0;
6082 }
6083
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006084 o_addblock(output, arg, p - arg);
6085 debug_print_list("expand_vars_to_list[1]", output, n);
6086 arg = ++p;
6087 p = strchr(p, SPECIAL_VAR_SYMBOL);
6088
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006089 /* Fetch special var name (if it is indeed one of them)
6090 * and quote bit, force the bit on if singleword expansion -
6091 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006092 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006093
6094 /* Is this variable quoted and thus expansion can't be null?
6095 * "$@" is special. Even if quoted, it can still
6096 * expand to nothing (not even an empty string),
6097 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006098 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006099 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006100
6101 switch (first_ch & 0x7f) {
6102 /* Highest bit in first_ch indicates that var is double-quoted */
6103 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006104 case '@': {
6105 int i;
6106 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006107 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006108 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006109 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006110 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006111 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006112 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006113 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
6114 if (G.global_argv[i++][0] && G.global_argv[i]) {
6115 /* this argv[] is not empty and not last:
6116 * put terminating NUL, start new word */
6117 o_addchr(output, '\0');
6118 debug_print_list("expand_vars_to_list[2]", output, n);
6119 n = o_save_ptr(output, n);
6120 debug_print_list("expand_vars_to_list[3]", output, n);
6121 }
6122 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006123 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006124 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006125 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006126 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006127 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006128 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006129 while (1) {
6130 o_addQstr(output, G.global_argv[i]);
6131 if (++i >= G.global_argc)
6132 break;
6133 o_addchr(output, '\0');
6134 debug_print_list("expand_vars_to_list[4]", output, n);
6135 n = o_save_ptr(output, n);
6136 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006137 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006138 while (1) {
6139 o_addQstr(output, G.global_argv[i]);
6140 if (!G.global_argv[++i])
6141 break;
6142 if (G.ifs[0])
6143 o_addchr(output, G.ifs[0]);
6144 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006145 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006146 }
6147 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02006148 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006149 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
6150 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006151 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006152 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006153 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006154 break;
Denys Vlasenko932b9972018-01-11 12:39:48 +01006155 case SPECIAL_VAR_QUOTED_SVS:
6156 /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
6157 arg++;
6158 val = SPECIAL_VAR_SYMBOL_STR;
6159 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006160#if ENABLE_HUSH_TICK
6161 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006162 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006163 arg++;
6164 /* Can't just stuff it into output o_string,
6165 * expanded result may need to be globbed
Denys Vlasenko10ad6222017-04-17 16:13:32 +02006166 * and $IFS-split */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006167 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
6168 G.last_exitcode = process_command_subs(&subst_result, arg);
6169 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
6170 val = subst_result.data;
6171 goto store_val;
6172#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01006173#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006174 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
6175 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006176
6177 arg++; /* skip '+' */
6178 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
6179 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02006180 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02006181 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
6182 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006183 val = arith_buf;
6184 break;
6185 }
6186#endif
6187 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006188 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006189 IF_HUSH_TICK(store_val:)
6190 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006191 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
6192 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006193 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006194 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006195 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006196 }
6197 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02006198 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006199 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
6200 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006201 }
6202 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006203 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
6204
6205 if (val && val[0]) {
6206 o_addQstr(output, val);
6207 }
6208 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006209
6210 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
6211 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006212 if (*p != SPECIAL_VAR_SYMBOL)
6213 *p = SPECIAL_VAR_SYMBOL;
6214
6215#if ENABLE_HUSH_TICK
6216 o_free(&subst_result);
6217#endif
6218 arg = ++p;
6219 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
6220
6221 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02006222 if (ended_in_ifs) {
6223 o_addchr(output, '\0');
6224 n = o_save_ptr(output, n);
6225 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006226 debug_print_list("expand_vars_to_list[a]", output, n);
6227 /* this part is literal, and it was already pre-quoted
6228 * if needed (much earlier), do not use o_addQstr here! */
6229 o_addstr_with_NUL(output, arg);
6230 debug_print_list("expand_vars_to_list[b]", output, n);
6231 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02006232 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006233 ) {
6234 n--;
6235 /* allow to reuse list[n] later without re-growth */
6236 output->has_empty_slot = 1;
6237 } else {
6238 o_addchr(output, '\0');
6239 }
6240
6241 return n;
6242}
6243
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006244static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006245{
6246 int n;
6247 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006248 o_string output = NULL_O_STRING;
6249
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006250 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006251
6252 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006253 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02006254 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006255 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006256 }
6257 debug_print_list("expand_variables", &output, n);
6258
6259 /* output.data (malloced in one block) gets returned in "list" */
6260 list = o_finalize_list(&output, n);
6261 debug_print_strings("expand_variables[1]", list);
6262 return list;
6263}
6264
6265static char **expand_strvec_to_strvec(char **argv)
6266{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006267 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006268}
6269
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01006270#if BASH_TEST2
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006271static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
6272{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006273 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006274}
6275#endif
6276
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006277/* Used for expansion of right hand of assignments,
6278 * $((...)), heredocs, variable espansion parts.
6279 *
6280 * NB: should NOT do globbing!
6281 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
6282 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006283static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006284{
Denys Vlasenko637982f2017-07-06 01:52:23 +02006285#if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006286 const int do_unbackslash = 1;
6287#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006288 char *argv[2], **list;
6289
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006290 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006291 /* This is generally an optimization, but it also
6292 * handles "", which otherwise trips over !list[0] check below.
6293 * (is this ever happens that we actually get str="" here?)
6294 */
6295 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
6296 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006297 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006298 return xstrdup(str);
6299 }
6300
6301 argv[0] = (char*)str;
6302 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006303 list = expand_variables(argv, do_unbackslash
6304 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
6305 : EXP_FLAG_SINGLEWORD
6306 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006307 if (HUSH_DEBUG)
6308 if (!list[0] || list[1])
6309 bb_error_msg_and_die("BUG in varexp2");
6310 /* actually, just move string 2*sizeof(char*) bytes back */
6311 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006312 if (do_unbackslash)
6313 unbackslash((char*)list);
6314 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006315 return (char*)list;
6316}
6317
Denys Vlasenko1f191122018-01-11 13:17:30 +01006318#if ENABLE_HUSH_CASE
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006319static char* expand_strvec_to_string(char **argv)
6320{
6321 char **list;
6322
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02006323 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006324 /* Convert all NULs to spaces */
6325 if (list[0]) {
6326 int n = 1;
6327 while (list[n]) {
6328 if (HUSH_DEBUG)
6329 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
6330 bb_error_msg_and_die("BUG in varexp3");
6331 /* bash uses ' ' regardless of $IFS contents */
6332 list[n][-1] = ' ';
6333 n++;
6334 }
6335 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02006336 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006337 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
6338 return (char*)list;
6339}
Denys Vlasenko1f191122018-01-11 13:17:30 +01006340#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006341
6342static char **expand_assignments(char **argv, int count)
6343{
6344 int i;
6345 char **p;
6346
6347 G.expanded_assignments = p = NULL;
6348 /* Expand assignments into one string each */
6349 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006350 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006351 }
6352 G.expanded_assignments = NULL;
6353 return p;
6354}
6355
6356
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006357static void switch_off_special_sigs(unsigned mask)
6358{
6359 unsigned sig = 0;
6360 while ((mask >>= 1) != 0) {
6361 sig++;
6362 if (!(mask & 1))
6363 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006364#if ENABLE_HUSH_TRAP
6365 if (G_traps) {
6366 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006367 /* trap is '', has to remain SIG_IGN */
6368 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006369 free(G_traps[sig]);
6370 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006371 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006372#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006373 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006374 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006375 }
6376}
6377
Denys Vlasenkob347df92011-08-09 22:49:15 +02006378#if BB_MMU
6379/* never called */
6380void re_execute_shell(char ***to_free, const char *s,
6381 char *g_argv0, char **g_argv,
6382 char **builtin_argv) NORETURN;
6383
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006384static void reset_traps_to_defaults(void)
6385{
6386 /* This function is always called in a child shell
6387 * after fork (not vfork, NOMMU doesn't use this function).
6388 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006389 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006390 unsigned mask;
6391
6392 /* Child shells are not interactive.
6393 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6394 * Testcase: (while :; do :; done) + ^Z should background.
6395 * Same goes for SIGTERM, SIGHUP, SIGINT.
6396 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006397 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006398 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006399 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006400
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006401 /* Switch off special sigs */
6402 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006403# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006404 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006405# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006406 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006407 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6408 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006409
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006410# if ENABLE_HUSH_TRAP
6411 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006412 return;
6413
6414 /* Reset all sigs to default except ones with empty traps */
6415 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006416 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006417 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006418 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006419 continue; /* empty trap: has to remain SIG_IGN */
6420 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006421 free(G_traps[sig]);
6422 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006423 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006424 if (sig == 0)
6425 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006426 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006427 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006428# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006429}
6430
6431#else /* !BB_MMU */
6432
6433static void re_execute_shell(char ***to_free, const char *s,
6434 char *g_argv0, char **g_argv,
6435 char **builtin_argv) NORETURN;
6436static void re_execute_shell(char ***to_free, const char *s,
6437 char *g_argv0, char **g_argv,
6438 char **builtin_argv)
6439{
6440# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6441 /* delims + 2 * (number of bytes in printed hex numbers) */
6442 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6443 char *heredoc_argv[4];
6444 struct variable *cur;
6445# if ENABLE_HUSH_FUNCTIONS
6446 struct function *funcp;
6447# endif
6448 char **argv, **pp;
6449 unsigned cnt;
6450 unsigned long long empty_trap_mask;
6451
6452 if (!g_argv0) { /* heredoc */
6453 argv = heredoc_argv;
6454 argv[0] = (char *) G.argv0_for_re_execing;
6455 argv[1] = (char *) "-<";
6456 argv[2] = (char *) s;
6457 argv[3] = NULL;
6458 pp = &argv[3]; /* used as pointer to empty environment */
6459 goto do_exec;
6460 }
6461
6462 cnt = 0;
6463 pp = builtin_argv;
6464 if (pp) while (*pp++)
6465 cnt++;
6466
6467 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006468 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006469 int sig;
6470 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006471 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006472 empty_trap_mask |= 1LL << sig;
6473 }
6474 }
6475
6476 sprintf(param_buf, NOMMU_HACK_FMT
6477 , (unsigned) G.root_pid
6478 , (unsigned) G.root_ppid
6479 , (unsigned) G.last_bg_pid
6480 , (unsigned) G.last_exitcode
6481 , cnt
6482 , empty_trap_mask
6483 IF_HUSH_LOOPS(, G.depth_of_loop)
6484 );
6485# undef NOMMU_HACK_FMT
6486 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6487 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6488 */
6489 cnt += 6;
6490 for (cur = G.top_var; cur; cur = cur->next) {
6491 if (!cur->flg_export || cur->flg_read_only)
6492 cnt += 2;
6493 }
6494# if ENABLE_HUSH_FUNCTIONS
6495 for (funcp = G.top_func; funcp; funcp = funcp->next)
6496 cnt += 3;
6497# endif
6498 pp = g_argv;
6499 while (*pp++)
6500 cnt++;
6501 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6502 *pp++ = (char *) G.argv0_for_re_execing;
6503 *pp++ = param_buf;
6504 for (cur = G.top_var; cur; cur = cur->next) {
6505 if (strcmp(cur->varstr, hush_version_str) == 0)
6506 continue;
6507 if (cur->flg_read_only) {
6508 *pp++ = (char *) "-R";
6509 *pp++ = cur->varstr;
6510 } else if (!cur->flg_export) {
6511 *pp++ = (char *) "-V";
6512 *pp++ = cur->varstr;
6513 }
6514 }
6515# if ENABLE_HUSH_FUNCTIONS
6516 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6517 *pp++ = (char *) "-F";
6518 *pp++ = funcp->name;
6519 *pp++ = funcp->body_as_string;
6520 }
6521# endif
6522 /* We can pass activated traps here. Say, -Tnn:trap_string
6523 *
6524 * However, POSIX says that subshells reset signals with traps
6525 * to SIG_DFL.
6526 * I tested bash-3.2 and it not only does that with true subshells
6527 * of the form ( list ), but with any forked children shells.
6528 * I set trap "echo W" WINCH; and then tried:
6529 *
6530 * { echo 1; sleep 20; echo 2; } &
6531 * while true; do echo 1; sleep 20; echo 2; break; done &
6532 * true | { echo 1; sleep 20; echo 2; } | cat
6533 *
6534 * In all these cases sending SIGWINCH to the child shell
6535 * did not run the trap. If I add trap "echo V" WINCH;
6536 * _inside_ group (just before echo 1), it works.
6537 *
6538 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006539 */
6540 *pp++ = (char *) "-c";
6541 *pp++ = (char *) s;
6542 if (builtin_argv) {
6543 while (*++builtin_argv)
6544 *pp++ = *builtin_argv;
6545 *pp++ = (char *) "";
6546 }
6547 *pp++ = g_argv0;
6548 while (*g_argv)
6549 *pp++ = *g_argv++;
6550 /* *pp = NULL; - is already there */
6551 pp = environ;
6552
6553 do_exec:
6554 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006555 /* Don't propagate SIG_IGN to the child */
6556 if (SPECIAL_JOBSTOP_SIGS != 0)
6557 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006558 execve(bb_busybox_exec_path, argv, pp);
6559 /* Fallback. Useful for init=/bin/hush usage etc */
6560 if (argv[0][0] == '/')
6561 execve(argv[0], argv, pp);
6562 xfunc_error_retval = 127;
6563 bb_error_msg_and_die("can't re-execute the shell");
6564}
6565#endif /* !BB_MMU */
6566
6567
6568static int run_and_free_list(struct pipe *pi);
6569
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006570/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006571 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6572 * end_trigger controls how often we stop parsing
6573 * NUL: parse all, execute, return
6574 * ';': parse till ';' or newline, execute, repeat till EOF
6575 */
6576static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006577{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006578 /* Why we need empty flag?
6579 * An obscure corner case "false; ``; echo $?":
6580 * empty command in `` should still set $? to 0.
6581 * But we can't just set $? to 0 at the start,
6582 * this breaks "false; echo `echo $?`" case.
6583 */
6584 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006585 while (1) {
6586 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006587
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006588#if ENABLE_HUSH_INTERACTIVE
6589 if (end_trigger == ';')
6590 inp->promptmode = 0; /* PS1 */
6591#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006592 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006593 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6594 /* If we are in "big" script
6595 * (not in `cmd` or something similar)...
6596 */
6597 if (pipe_list == ERR_PTR && end_trigger == ';') {
6598 /* Discard cached input (rest of line) */
6599 int ch = inp->last_char;
6600 while (ch != EOF && ch != '\n') {
6601 //bb_error_msg("Discarded:'%c'", ch);
6602 ch = i_getch(inp);
6603 }
6604 /* Force prompt */
6605 inp->p = NULL;
6606 /* This stream isn't empty */
6607 empty = 0;
6608 continue;
6609 }
6610 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006611 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006612 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006613 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006614 debug_print_tree(pipe_list, 0);
6615 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6616 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006617 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006618 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006619 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006620 }
Eric Andersen25f27032001-04-26 23:22:31 +00006621}
6622
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006623static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006624{
6625 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006626 //IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
6627
Eric Andersen25f27032001-04-26 23:22:31 +00006628 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006629 parse_and_run_stream(&input, '\0');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006630 //IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006631}
6632
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006633static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006634{
Eric Andersen25f27032001-04-26 23:22:31 +00006635 struct in_str input;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006636 IF_HUSH_LINENO_VAR(unsigned sv = G.lineno;)
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01006637
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006638 IF_HUSH_LINENO_VAR(G.lineno = 1;)
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01006639 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006640 parse_and_run_stream(&input, ';');
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006641 IF_HUSH_LINENO_VAR(G.lineno = sv;)
Eric Andersen25f27032001-04-26 23:22:31 +00006642}
6643
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006644#if ENABLE_HUSH_TICK
6645static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6646{
6647 pid_t pid;
6648 int channel[2];
6649# if !BB_MMU
6650 char **to_free = NULL;
6651# endif
6652
6653 xpipe(channel);
6654 pid = BB_MMU ? xfork() : xvfork();
6655 if (pid == 0) { /* child */
6656 disable_restore_tty_pgrp_on_exit();
6657 /* Process substitution is not considered to be usual
6658 * 'command execution'.
6659 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6660 */
6661 bb_signals(0
6662 + (1 << SIGTSTP)
6663 + (1 << SIGTTIN)
6664 + (1 << SIGTTOU)
6665 , SIG_IGN);
6666 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6667 close(channel[0]); /* NB: close _first_, then move fd! */
6668 xmove_fd(channel[1], 1);
6669 /* Prevent it from trying to handle ctrl-z etc */
6670 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006671# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006672 /* Awful hack for `trap` or $(trap).
6673 *
6674 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6675 * contains an example where "trap" is executed in a subshell:
6676 *
6677 * save_traps=$(trap)
6678 * ...
6679 * eval "$save_traps"
6680 *
6681 * Standard does not say that "trap" in subshell shall print
6682 * parent shell's traps. It only says that its output
6683 * must have suitable form, but then, in the above example
6684 * (which is not supposed to be normative), it implies that.
6685 *
6686 * bash (and probably other shell) does implement it
6687 * (traps are reset to defaults, but "trap" still shows them),
6688 * but as a result, "trap" logic is hopelessly messed up:
6689 *
6690 * # trap
6691 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6692 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6693 * # true | trap <--- trap is in subshell - no output (ditto)
6694 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6695 * trap -- 'echo Ho' SIGWINCH
6696 * # echo `(trap)` <--- in subshell in subshell - output
6697 * trap -- 'echo Ho' SIGWINCH
6698 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6699 * trap -- 'echo Ho' SIGWINCH
6700 *
6701 * The rules when to forget and when to not forget traps
6702 * get really complex and nonsensical.
6703 *
6704 * Our solution: ONLY bare $(trap) or `trap` is special.
6705 */
6706 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006707 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006708 && skip_whitespace(s + 4)[0] == '\0'
6709 ) {
6710 static const char *const argv[] = { NULL, NULL };
6711 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006712 fflush_all(); /* important */
6713 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006714 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006715# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006716# if BB_MMU
6717 reset_traps_to_defaults();
6718 parse_and_run_string(s);
6719 _exit(G.last_exitcode);
6720# else
6721 /* We re-execute after vfork on NOMMU. This makes this script safe:
6722 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6723 * huge=`cat BIG` # was blocking here forever
6724 * echo OK
6725 */
6726 re_execute_shell(&to_free,
6727 s,
6728 G.global_argv[0],
6729 G.global_argv + 1,
6730 NULL);
6731# endif
6732 }
6733
6734 /* parent */
6735 *pid_p = pid;
6736# if ENABLE_HUSH_FAST
6737 G.count_SIGCHLD++;
6738//bb_error_msg("[%d] fork in generate_stream_from_string:"
6739// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6740// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6741# endif
6742 enable_restore_tty_pgrp_on_exit();
6743# if !BB_MMU
6744 free(to_free);
6745# endif
6746 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006747 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006748}
6749
6750/* Return code is exit status of the process that is run. */
6751static int process_command_subs(o_string *dest, const char *s)
6752{
6753 FILE *fp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006754 pid_t pid;
6755 int status, ch, eol_cnt;
6756
6757 fp = generate_stream_from_string(s, &pid);
6758
6759 /* Now send results of command back into original context */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006760 eol_cnt = 0;
Denys Vlasenkoaa617ac2018-02-13 15:30:13 +01006761 while ((ch = getc(fp)) != EOF) {
6762 if (ch == '\0')
6763 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006764 if (ch == '\n') {
6765 eol_cnt++;
6766 continue;
6767 }
6768 while (eol_cnt) {
6769 o_addchr(dest, '\n');
6770 eol_cnt--;
6771 }
6772 o_addQchr(dest, ch);
6773 }
6774
6775 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006776 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006777 /* We need to extract exitcode. Test case
6778 * "true; echo `sleep 1; false` $?"
6779 * should print 1 */
6780 safe_waitpid(pid, &status, 0);
6781 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6782 return WEXITSTATUS(status);
6783}
6784#endif /* ENABLE_HUSH_TICK */
6785
6786
6787static void setup_heredoc(struct redir_struct *redir)
6788{
6789 struct fd_pair pair;
6790 pid_t pid;
6791 int len, written;
6792 /* the _body_ of heredoc (misleading field name) */
6793 const char *heredoc = redir->rd_filename;
6794 char *expanded;
6795#if !BB_MMU
6796 char **to_free;
6797#endif
6798
6799 expanded = NULL;
6800 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006801 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006802 if (expanded)
6803 heredoc = expanded;
6804 }
6805 len = strlen(heredoc);
6806
6807 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6808 xpiped_pair(pair);
6809 xmove_fd(pair.rd, redir->rd_fd);
6810
6811 /* Try writing without forking. Newer kernels have
6812 * dynamically growing pipes. Must use non-blocking write! */
6813 ndelay_on(pair.wr);
6814 while (1) {
6815 written = write(pair.wr, heredoc, len);
6816 if (written <= 0)
6817 break;
6818 len -= written;
6819 if (len == 0) {
6820 close(pair.wr);
6821 free(expanded);
6822 return;
6823 }
6824 heredoc += written;
6825 }
6826 ndelay_off(pair.wr);
6827
6828 /* Okay, pipe buffer was not big enough */
6829 /* Note: we must not create a stray child (bastard? :)
6830 * for the unsuspecting parent process. Child creates a grandchild
6831 * and exits before parent execs the process which consumes heredoc
6832 * (that exec happens after we return from this function) */
6833#if !BB_MMU
6834 to_free = NULL;
6835#endif
6836 pid = xvfork();
6837 if (pid == 0) {
6838 /* child */
6839 disable_restore_tty_pgrp_on_exit();
6840 pid = BB_MMU ? xfork() : xvfork();
6841 if (pid != 0)
6842 _exit(0);
6843 /* grandchild */
6844 close(redir->rd_fd); /* read side of the pipe */
6845#if BB_MMU
6846 full_write(pair.wr, heredoc, len); /* may loop or block */
6847 _exit(0);
6848#else
6849 /* Delegate blocking writes to another process */
6850 xmove_fd(pair.wr, STDOUT_FILENO);
6851 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6852#endif
6853 }
6854 /* parent */
6855#if ENABLE_HUSH_FAST
6856 G.count_SIGCHLD++;
6857//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6858#endif
6859 enable_restore_tty_pgrp_on_exit();
6860#if !BB_MMU
6861 free(to_free);
6862#endif
6863 close(pair.wr);
6864 free(expanded);
6865 wait(NULL); /* wait till child has died */
6866}
6867
Denys Vlasenko2db74612017-07-07 22:07:28 +02006868struct squirrel {
6869 int orig_fd;
6870 int moved_to;
6871 /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
6872 /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
6873};
6874
Denys Vlasenko621fc502017-07-24 12:42:17 +02006875static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
6876{
6877 sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
6878 sq[i].orig_fd = orig;
6879 sq[i].moved_to = moved;
6880 sq[i+1].orig_fd = -1; /* end marker */
6881 return sq;
6882}
6883
Denys Vlasenko2db74612017-07-07 22:07:28 +02006884static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
6885{
Denys Vlasenko621fc502017-07-24 12:42:17 +02006886 int moved_to;
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006887 int i;
Denys Vlasenko2db74612017-07-07 22:07:28 +02006888
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006889 i = 0;
6890 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006891 /* If we collide with an already moved fd... */
6892 if (fd == sq[i].moved_to) {
6893 sq[i].moved_to = fcntl_F_DUPFD(sq[i].moved_to, avoid_fd);
6894 debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
6895 if (sq[i].moved_to < 0) /* what? */
6896 xfunc_die();
6897 return sq;
6898 }
6899 if (fd == sq[i].orig_fd) {
6900 /* Example: echo Hello >/dev/null 1>&2 */
6901 debug_printf_redir("redirect_fd %d: already moved\n", fd);
6902 return sq;
6903 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006904 }
6905
Denys Vlasenko2db74612017-07-07 22:07:28 +02006906 /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
Denys Vlasenko621fc502017-07-24 12:42:17 +02006907 moved_to = fcntl_F_DUPFD(fd, avoid_fd);
6908 debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
6909 if (moved_to < 0 && errno != EBADF)
Denys Vlasenko2db74612017-07-07 22:07:28 +02006910 xfunc_die();
Denys Vlasenko621fc502017-07-24 12:42:17 +02006911 return append_squirrel(sq, i, fd, moved_to);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006912}
6913
Denys Vlasenko657e9002017-07-30 23:34:04 +02006914static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
6915{
6916 int i;
6917
Denys Vlasenkod16e6122017-08-11 15:41:39 +02006918 i = 0;
6919 if (sq) for (; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02006920 /* If we collide with an already moved fd... */
6921 if (fd == sq[i].orig_fd) {
6922 /* Examples:
6923 * "echo 3>FILE 3>&- 3>FILE"
6924 * "echo 3>&- 3>FILE"
6925 * No need for last redirect to insert
6926 * another "need to close 3" indicator.
6927 */
6928 debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
6929 return sq;
6930 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02006931 }
6932
6933 debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
6934 return append_squirrel(sq, i, fd, -1);
6935}
6936
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006937/* fd: redirect wants this fd to be used (e.g. 3>file).
6938 * Move all conflicting internally used fds,
6939 * and remember them so that we can restore them later.
6940 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006941static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006942{
Denys Vlasenko2db74612017-07-07 22:07:28 +02006943 if (avoid_fd < 9) /* the important case here is that it can be -1 */
6944 avoid_fd = 9;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006945
6946#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006947 if (fd == G.interactive_fd) {
6948 /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
Denys Vlasenko657e9002017-07-30 23:34:04 +02006949 G.interactive_fd = xdup_CLOEXEC_and_close(G.interactive_fd, avoid_fd);
Denys Vlasenko2db74612017-07-07 22:07:28 +02006950 debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G.interactive_fd);
6951 return 1; /* "we closed fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006952 }
6953#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006954 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6955 * (1) Redirect in a forked child. No need to save FILEs' fds,
6956 * we aren't going to use them anymore, ok to trash.
Denys Vlasenko2db74612017-07-07 22:07:28 +02006957 * (2) "exec 3>FILE". Bummer. We can save script FILEs' fds,
6958 * but how are we doing to restore them?
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006959 * "fileno(fd) = new_fd" can't be done.
6960 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02006961 if (!sqp)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006962 return 0;
6963
Denys Vlasenko2db74612017-07-07 22:07:28 +02006964 /* If this one of script's fds? */
6965 if (save_FILEs_on_redirect(fd, avoid_fd))
6966 return 1; /* yes. "we closed fd" */
6967
6968 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
6969 *sqp = add_squirrel(*sqp, fd, avoid_fd);
6970 return 0; /* "we did not close fd" */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006971}
6972
Denys Vlasenko2db74612017-07-07 22:07:28 +02006973static void restore_redirects(struct squirrel *sq)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006974{
Denys Vlasenko2db74612017-07-07 22:07:28 +02006975 if (sq) {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02006976 int i;
6977 for (i = 0; sq[i].orig_fd >= 0; i++) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02006978 if (sq[i].moved_to >= 0) {
6979 /* We simply die on error */
6980 debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
6981 xmove_fd(sq[i].moved_to, sq[i].orig_fd);
6982 } else {
6983 /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
6984 debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
6985 close(sq[i].orig_fd);
6986 }
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006987 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02006988 free(sq);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006989 }
6990
Denys Vlasenko2db74612017-07-07 22:07:28 +02006991 /* If moved, G.interactive_fd stays on new fd, not restoring it */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006992
6993 restore_redirected_FILEs();
6994}
6995
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02006996#if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02006997static void close_saved_fds_and_FILE_fds(void)
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02006998{
6999 if (G_interactive_fd)
7000 close(G_interactive_fd);
7001 close_all_FILE_list();
7002}
7003#endif
7004
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007005static int internally_opened_fd(int fd, struct squirrel *sq)
7006{
7007 int i;
7008
7009#if ENABLE_HUSH_INTERACTIVE
7010 if (fd == G.interactive_fd)
7011 return 1;
7012#endif
7013 /* If this one of script's fds? */
7014 if (fd_in_FILEs(fd))
7015 return 1;
7016
7017 if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
7018 if (fd == sq[i].moved_to)
7019 return 1;
7020 }
7021 return 0;
7022}
7023
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007024/* squirrel != NULL means we squirrel away copies of stdin, stdout,
7025 * and stderr if they are redirected. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02007026static int setup_redirects(struct command *prog, struct squirrel **sqp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007027{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007028 struct redir_struct *redir;
7029
7030 for (redir = prog->redirects; redir; redir = redir->next) {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007031 int newfd;
7032 int closed;
7033
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007034 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007035 /* "rd_fd<<HERE" case */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007036 save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007037 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
7038 * of the heredoc */
7039 debug_printf_parse("set heredoc '%s'\n",
7040 redir->rd_filename);
7041 setup_heredoc(redir);
7042 continue;
7043 }
7044
7045 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007046 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007047 char *p;
Denys Vlasenko657e9002017-07-30 23:34:04 +02007048 int mode;
7049
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007050 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02007051 /*
7052 * Examples:
7053 * "cmd >" (no filename)
7054 * "cmd > <file" (2nd redirect starts too early)
7055 */
Denys Vlasenko39701202017-08-02 19:44:05 +02007056 syntax_error("invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007057 continue;
7058 }
7059 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007060 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007061 newfd = open_or_warn(p, mode);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007062 free(p);
Denys Vlasenko657e9002017-07-30 23:34:04 +02007063 if (newfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02007064 /* Error message from open_or_warn can be lost
7065 * if stderr has been redirected, but bash
7066 * and ash both lose it as well
7067 * (though zsh doesn't!)
7068 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007069 return 1;
7070 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007071 if (newfd == redir->rd_fd && sqp) {
Denys Vlasenko621fc502017-07-24 12:42:17 +02007072 /* open() gave us precisely the fd we wanted.
7073 * This means that this fd was not busy
7074 * (not opened to anywhere).
7075 * Remember to close it on restore:
7076 */
Denys Vlasenko657e9002017-07-30 23:34:04 +02007077 *sqp = add_squirrel_closed(*sqp, newfd);
7078 debug_printf_redir("redir to previously closed fd %d\n", newfd);
Denys Vlasenko621fc502017-07-24 12:42:17 +02007079 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007080 } else {
Denys Vlasenko657e9002017-07-30 23:34:04 +02007081 /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
7082 newfd = redir->rd_dup;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007083 }
7084
Denys Vlasenko657e9002017-07-30 23:34:04 +02007085 if (newfd == redir->rd_fd)
7086 continue;
7087
7088 /* if "N>FILE": move newfd to redir->rd_fd */
7089 /* if "N>&M": dup newfd to redir->rd_fd */
7090 /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
7091
7092 closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
7093 if (newfd == REDIRFD_CLOSE) {
7094 /* "N>&-" means "close me" */
7095 if (!closed) {
7096 /* ^^^ optimization: saving may already
7097 * have closed it. If not... */
7098 close(redir->rd_fd);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007099 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007100 /* Sometimes we do another close on restore, getting EBADF.
7101 * Consider "echo 3>FILE 3>&-"
7102 * first redirect remembers "need to close 3",
7103 * and second redirect closes 3! Restore code then closes 3 again.
7104 */
7105 } else {
Denys Vlasenko32fdf2f2017-07-31 04:32:06 +02007106 /* if newfd is a script fd or saved fd, simulate EBADF */
7107 if (internally_opened_fd(newfd, sqp ? *sqp : NULL)) {
7108 //errno = EBADF;
7109 //bb_perror_msg_and_die("can't duplicate file descriptor");
7110 newfd = -1; /* same effect as code above */
7111 }
Denys Vlasenko657e9002017-07-30 23:34:04 +02007112 xdup2(newfd, redir->rd_fd);
7113 if (redir->rd_dup == REDIRFD_TO_FILE)
7114 /* "rd_fd > FILE" */
7115 close(newfd);
7116 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007117 }
7118 }
7119 return 0;
7120}
7121
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007122static char *find_in_path(const char *arg)
7123{
7124 char *ret = NULL;
7125 const char *PATH = get_local_var_value("PATH");
7126
7127 if (!PATH)
7128 return NULL;
7129
7130 while (1) {
7131 const char *end = strchrnul(PATH, ':');
7132 int sz = end - PATH; /* must be int! */
7133
7134 free(ret);
7135 if (sz != 0) {
7136 ret = xasprintf("%.*s/%s", sz, PATH, arg);
7137 } else {
7138 /* We have xxx::yyyy in $PATH,
7139 * it means "use current dir" */
7140 ret = xstrdup(arg);
7141 }
7142 if (access(ret, F_OK) == 0)
7143 break;
7144
7145 if (*end == '\0') {
7146 free(ret);
7147 return NULL;
7148 }
7149 PATH = end + 1;
7150 }
7151
7152 return ret;
7153}
7154
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007155static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007156 const struct built_in_command *x,
7157 const struct built_in_command *end)
7158{
7159 while (x != end) {
7160 if (strcmp(name, x->b_cmd) != 0) {
7161 x++;
7162 continue;
7163 }
7164 debug_printf_exec("found builtin '%s'\n", name);
7165 return x;
7166 }
7167 return NULL;
7168}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007169static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007170{
7171 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
7172}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007173static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007174{
7175 const struct built_in_command *x = find_builtin1(name);
7176 if (x)
7177 return x;
7178 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
7179}
7180
7181#if ENABLE_HUSH_FUNCTIONS
7182static struct function **find_function_slot(const char *name)
7183{
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007184 struct function *funcp;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007185 struct function **funcpp = &G.top_func;
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007186
7187 while ((funcp = *funcpp) != NULL) {
7188 if (strcmp(name, funcp->name) == 0) {
7189 debug_printf_exec("found function '%s'\n", name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007190 break;
7191 }
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007192 funcpp = &funcp->next;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007193 }
7194 return funcpp;
7195}
7196
Denys Vlasenko33f7c8f2018-03-06 17:21:57 +01007197static ALWAYS_INLINE const struct function *find_function(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007198{
7199 const struct function *funcp = *find_function_slot(name);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007200 return funcp;
7201}
7202
7203/* Note: takes ownership on name ptr */
7204static struct function *new_function(char *name)
7205{
7206 struct function **funcpp = find_function_slot(name);
7207 struct function *funcp = *funcpp;
7208
7209 if (funcp != NULL) {
7210 struct command *cmd = funcp->parent_cmd;
7211 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
7212 if (!cmd) {
7213 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
7214 free(funcp->name);
7215 /* Note: if !funcp->body, do not free body_as_string!
7216 * This is a special case of "-F name body" function:
7217 * body_as_string was not malloced! */
7218 if (funcp->body) {
7219 free_pipe_list(funcp->body);
7220# if !BB_MMU
7221 free(funcp->body_as_string);
7222# endif
7223 }
7224 } else {
7225 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
7226 cmd->argv[0] = funcp->name;
7227 cmd->group = funcp->body;
7228# if !BB_MMU
7229 cmd->group_as_string = funcp->body_as_string;
7230# endif
7231 }
7232 } else {
7233 debug_printf_exec("remembering new function '%s'\n", name);
7234 funcp = *funcpp = xzalloc(sizeof(*funcp));
7235 /*funcp->next = NULL;*/
7236 }
7237
7238 funcp->name = name;
7239 return funcp;
7240}
7241
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007242# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007243static void unset_func(const char *name)
7244{
7245 struct function **funcpp = find_function_slot(name);
7246 struct function *funcp = *funcpp;
7247
7248 if (funcp != NULL) {
7249 debug_printf_exec("freeing function '%s'\n", funcp->name);
7250 *funcpp = funcp->next;
7251 /* funcp is unlinked now, deleting it.
7252 * Note: if !funcp->body, the function was created by
7253 * "-F name body", do not free ->body_as_string
7254 * and ->name as they were not malloced. */
7255 if (funcp->body) {
7256 free_pipe_list(funcp->body);
7257 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007258# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007259 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007260# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007261 }
7262 free(funcp);
7263 }
7264}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01007265# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007266
7267# if BB_MMU
7268#define exec_function(to_free, funcp, argv) \
7269 exec_function(funcp, argv)
7270# endif
7271static void exec_function(char ***to_free,
7272 const struct function *funcp,
7273 char **argv) NORETURN;
7274static void exec_function(char ***to_free,
7275 const struct function *funcp,
7276 char **argv)
7277{
7278# if BB_MMU
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007279 int n;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007280
7281 argv[0] = G.global_argv[0];
7282 G.global_argv = argv;
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02007283 G.global_argc = n = 1 + string_array_len(argv + 1);
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007284
7285// Example when we are here: "cmd | func"
7286// func will run with saved-redirect fds open.
7287// $ f() { echo /proc/self/fd/*; }
7288// $ true | f
7289// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
7290// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
7291// Same in script:
7292// $ . ./SCRIPT
7293// /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
7294// stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
7295// They are CLOEXEC so external programs won't see them, but
7296// for "more correctness" we might want to close those extra fds here:
7297//? close_saved_fds_and_FILE_fds();
7298
7299 /* "we are in function, ok to use return" */
7300 G_flag_return_in_progress = -1;
7301 IF_HUSH_LOCAL(G.func_nest_level++;)
7302
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007303 /* On MMU, funcp->body is always non-NULL */
7304 n = run_list(funcp->body);
7305 fflush_all();
7306 _exit(n);
7307# else
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007308//? close_saved_fds_and_FILE_fds();
7309
7310//TODO: check whether "true | func_with_return" works
7311
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007312 re_execute_shell(to_free,
7313 funcp->body_as_string,
7314 G.global_argv[0],
7315 argv + 1,
7316 NULL);
7317# endif
7318}
7319
7320static int run_function(const struct function *funcp, char **argv)
7321{
7322 int rc;
7323 save_arg_t sv;
7324 smallint sv_flg;
7325
7326 save_and_replace_G_args(&sv, argv);
7327
7328 /* "we are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007329 sv_flg = G_flag_return_in_progress;
7330 G_flag_return_in_progress = -1;
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007331 IF_HUSH_LOCAL(G.func_nest_level++;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007332
7333 /* On MMU, funcp->body is always non-NULL */
7334# if !BB_MMU
7335 if (!funcp->body) {
7336 /* Function defined by -F */
7337 parse_and_run_string(funcp->body_as_string);
7338 rc = G.last_exitcode;
7339 } else
7340# endif
7341 {
7342 rc = run_list(funcp->body);
7343 }
7344
7345# if ENABLE_HUSH_LOCAL
7346 {
7347 struct variable *var;
7348 struct variable **var_pp;
7349
7350 var_pp = &G.top_var;
7351 while ((var = *var_pp) != NULL) {
7352 if (var->func_nest_level < G.func_nest_level) {
7353 var_pp = &var->next;
7354 continue;
7355 }
7356 /* Unexport */
7357 if (var->flg_export)
7358 bb_unsetenv(var->varstr);
7359 /* Remove from global list */
7360 *var_pp = var->next;
7361 /* Free */
7362 if (!var->max_len)
7363 free(var->varstr);
7364 free(var);
7365 }
7366 G.func_nest_level--;
7367 }
7368# endif
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007369 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007370
7371 restore_G_args(&sv, argv);
7372
7373 return rc;
7374}
7375#endif /* ENABLE_HUSH_FUNCTIONS */
7376
7377
7378#if BB_MMU
7379#define exec_builtin(to_free, x, argv) \
7380 exec_builtin(x, argv)
7381#else
7382#define exec_builtin(to_free, x, argv) \
7383 exec_builtin(to_free, argv)
7384#endif
7385static void exec_builtin(char ***to_free,
7386 const struct built_in_command *x,
7387 char **argv) NORETURN;
7388static void exec_builtin(char ***to_free,
7389 const struct built_in_command *x,
7390 char **argv)
7391{
7392#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007393 int rcode;
7394 fflush_all();
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007395//? close_saved_fds_and_FILE_fds();
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007396 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007397 fflush_all();
7398 _exit(rcode);
7399#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007400 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007401 /* On NOMMU, we must never block!
7402 * Example: { sleep 99 | read line; } & echo Ok
7403 */
7404 re_execute_shell(to_free,
7405 argv[0],
7406 G.global_argv[0],
7407 G.global_argv + 1,
7408 argv);
7409#endif
7410}
7411
7412
7413static void execvp_or_die(char **argv) NORETURN;
7414static void execvp_or_die(char **argv)
7415{
Denys Vlasenko04465da2016-10-03 01:01:15 +02007416 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007417 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007418 /* Don't propagate SIG_IGN to the child */
7419 if (SPECIAL_JOBSTOP_SIGS != 0)
7420 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007421 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007422 e = 2;
7423 if (errno == EACCES) e = 126;
7424 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007425 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02007426 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007427}
7428
7429#if ENABLE_HUSH_MODE_X
7430static void dump_cmd_in_x_mode(char **argv)
7431{
7432 if (G_x_mode && argv) {
7433 /* We want to output the line in one write op */
7434 char *buf, *p;
7435 int len;
7436 int n;
7437
7438 len = 3;
7439 n = 0;
7440 while (argv[n])
7441 len += strlen(argv[n++]) + 1;
7442 buf = xmalloc(len);
7443 buf[0] = '+';
7444 p = buf + 1;
7445 n = 0;
7446 while (argv[n])
7447 p += sprintf(p, " %s", argv[n++]);
7448 *p++ = '\n';
7449 *p = '\0';
7450 fputs(buf, stderr);
7451 free(buf);
7452 }
7453}
7454#else
7455# define dump_cmd_in_x_mode(argv) ((void)0)
7456#endif
7457
Denys Vlasenko57000292018-01-12 14:41:45 +01007458#if ENABLE_HUSH_COMMAND
7459static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
7460{
7461 char *to_free;
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007462
Denys Vlasenko57000292018-01-12 14:41:45 +01007463 if (!opt_vV)
7464 return;
7465
7466 to_free = NULL;
7467 if (!explanation) {
7468 char *path = getenv("PATH");
7469 explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007470 if (!explanation)
7471 _exit(1); /* PROG was not found */
Denys Vlasenko57000292018-01-12 14:41:45 +01007472 if (opt_vV != 'V')
7473 cmd = to_free; /* -v PROG prints "/path/to/PROG" */
7474 }
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007475 printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
Denys Vlasenko57000292018-01-12 14:41:45 +01007476 free(to_free);
7477 fflush_all();
Denys Vlasenkoafb73a22018-01-12 16:17:59 +01007478 _exit(0);
Denys Vlasenko57000292018-01-12 14:41:45 +01007479}
7480#else
7481# define if_command_vV_print_and_exit(a,b,c) ((void)0)
7482#endif
7483
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007484#if BB_MMU
7485#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
7486 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
7487#define pseudo_exec(nommu_save, command, argv_expanded) \
7488 pseudo_exec(command, argv_expanded)
7489#endif
7490
7491/* Called after [v]fork() in run_pipe, or from builtin_exec.
7492 * Never returns.
7493 * Don't exit() here. If you don't exec, use _exit instead.
7494 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007495 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02007496 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007497static void pseudo_exec_argv(nommu_save_t *nommu_save,
7498 char **argv, int assignment_cnt,
7499 char **argv_expanded) NORETURN;
7500static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
7501 char **argv, int assignment_cnt,
7502 char **argv_expanded)
7503{
Denys Vlasenko57000292018-01-12 14:41:45 +01007504 const struct built_in_command *x;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007505 char **new_env;
Denys Vlasenko57000292018-01-12 14:41:45 +01007506#if ENABLE_HUSH_COMMAND
7507 char opt_vV = 0;
7508#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007509
7510 new_env = expand_assignments(argv, assignment_cnt);
7511 dump_cmd_in_x_mode(new_env);
7512
7513 if (!argv[assignment_cnt]) {
7514 /* Case when we are here: ... | var=val | ...
7515 * (note that we do not exit early, i.e., do not optimize out
7516 * expand_assignments(): think about ... | var=`sleep 1` | ...
7517 */
7518 free_strings(new_env);
7519 _exit(EXIT_SUCCESS);
7520 }
7521
7522#if BB_MMU
7523 set_vars_and_save_old(new_env);
7524 free(new_env); /* optional */
7525 /* we can also destroy set_vars_and_save_old's return value,
7526 * to save memory */
7527#else
7528 nommu_save->new_env = new_env;
7529 nommu_save->old_vars = set_vars_and_save_old(new_env);
7530#endif
7531
7532 if (argv_expanded) {
7533 argv = argv_expanded;
7534 } else {
7535 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7536#if !BB_MMU
7537 nommu_save->argv = argv;
7538#endif
7539 }
7540 dump_cmd_in_x_mode(argv);
7541
7542#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7543 if (strchr(argv[0], '/') != NULL)
7544 goto skip;
7545#endif
7546
Denys Vlasenko75481d32017-07-31 05:27:09 +02007547#if ENABLE_HUSH_FUNCTIONS
7548 /* Check if the command matches any functions (this goes before bltins) */
7549 {
7550 const struct function *funcp = find_function(argv[0]);
7551 if (funcp) {
7552 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7553 }
7554 }
7555#endif
7556
Denys Vlasenko57000292018-01-12 14:41:45 +01007557#if ENABLE_HUSH_COMMAND
7558 /* "command BAR": run BAR without looking it up among functions
7559 * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
7560 * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
7561 */
7562 while (strcmp(argv[0], "command") == 0 && argv[1]) {
7563 char *p;
7564
7565 argv++;
7566 p = *argv;
7567 if (p[0] != '-' || !p[1])
7568 continue; /* bash allows "command command command [-OPT] BAR" */
7569
7570 for (;;) {
7571 p++;
7572 switch (*p) {
7573 case '\0':
7574 argv++;
7575 p = *argv;
7576 if (p[0] != '-' || !p[1])
7577 goto after_opts;
7578 continue; /* next arg is also -opts, process it too */
7579 case 'v':
7580 case 'V':
7581 opt_vV = *p;
7582 continue;
7583 default:
7584 bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
7585 }
7586 }
7587 }
7588 after_opts:
7589# if ENABLE_HUSH_FUNCTIONS
7590 if (opt_vV && find_function(argv[0]))
7591 if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
7592# endif
7593#endif
7594
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007595 /* Check if the command matches any of the builtins.
7596 * Depending on context, this might be redundant. But it's
7597 * easier to waste a few CPU cycles than it is to figure out
7598 * if this is one of those cases.
7599 */
Denys Vlasenko57000292018-01-12 14:41:45 +01007600 /* Why "BB_MMU ? :" difference in logic? -
7601 * On NOMMU, it is more expensive to re-execute shell
7602 * just in order to run echo or test builtin.
7603 * It's better to skip it here and run corresponding
7604 * non-builtin later. */
7605 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7606 if (x) {
7607 if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
7608 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007609 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007610
7611#if ENABLE_FEATURE_SH_STANDALONE
7612 /* Check if the command matches any busybox applets */
7613 {
7614 int a = find_applet_by_name(argv[0]);
7615 if (a >= 0) {
Denys Vlasenko57000292018-01-12 14:41:45 +01007616 if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007617# if BB_MMU /* see above why on NOMMU it is not allowed */
7618 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenkobf1c3442017-07-31 04:54:53 +02007619 /* Do not leak open fds from opened script files etc.
7620 * Testcase: interactive "ls -l /proc/self/fd"
7621 * should not show tty fd open.
7622 */
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02007623 close_saved_fds_and_FILE_fds();
Denys Vlasenko75481d32017-07-31 05:27:09 +02007624//FIXME: should also close saved redir fds
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02007625 /* Without this, "rm -i FILE" can't be ^C'ed: */
7626 switch_off_special_sigs(G.special_sig_mask);
Denys Vlasenkoc9c1ccc2017-08-07 18:59:35 +02007627 debug_printf_exec("running applet '%s'\n", argv[0]);
Denys Vlasenko80e8e3c2017-08-07 19:24:57 +02007628 run_noexec_applet_and_exit(a, argv[0], argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007629 }
7630# endif
7631 /* Re-exec ourselves */
7632 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007633 /* Don't propagate SIG_IGN to the child */
7634 if (SPECIAL_JOBSTOP_SIGS != 0)
7635 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007636 execv(bb_busybox_exec_path, argv);
7637 /* If they called chroot or otherwise made the binary no longer
7638 * executable, fall through */
7639 }
7640 }
7641#endif
7642
7643#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7644 skip:
7645#endif
Denys Vlasenko57000292018-01-12 14:41:45 +01007646 if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007647 execvp_or_die(argv);
7648}
7649
7650/* Called after [v]fork() in run_pipe
7651 */
7652static void pseudo_exec(nommu_save_t *nommu_save,
7653 struct command *command,
7654 char **argv_expanded) NORETURN;
7655static void pseudo_exec(nommu_save_t *nommu_save,
7656 struct command *command,
7657 char **argv_expanded)
7658{
7659 if (command->argv) {
7660 pseudo_exec_argv(nommu_save, command->argv,
7661 command->assignment_cnt, argv_expanded);
7662 }
7663
7664 if (command->group) {
7665 /* Cases when we are here:
7666 * ( list )
7667 * { list } &
7668 * ... | ( list ) | ...
7669 * ... | { list } | ...
7670 */
7671#if BB_MMU
7672 int rcode;
7673 debug_printf_exec("pseudo_exec: run_list\n");
7674 reset_traps_to_defaults();
7675 rcode = run_list(command->group);
7676 /* OK to leak memory by not calling free_pipe_list,
7677 * since this process is about to exit */
7678 _exit(rcode);
7679#else
7680 re_execute_shell(&nommu_save->argv_from_re_execing,
7681 command->group_as_string,
7682 G.global_argv[0],
7683 G.global_argv + 1,
7684 NULL);
7685#endif
7686 }
7687
7688 /* Case when we are here: ... | >file */
7689 debug_printf_exec("pseudo_exec'ed null command\n");
7690 _exit(EXIT_SUCCESS);
7691}
7692
7693#if ENABLE_HUSH_JOB
7694static const char *get_cmdtext(struct pipe *pi)
7695{
7696 char **argv;
7697 char *p;
7698 int len;
7699
7700 /* This is subtle. ->cmdtext is created only on first backgrounding.
7701 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7702 * On subsequent bg argv is trashed, but we won't use it */
7703 if (pi->cmdtext)
7704 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007705
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007706 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007707 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007708 pi->cmdtext = xzalloc(1);
7709 return pi->cmdtext;
7710 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007711 len = 0;
7712 do {
7713 len += strlen(*argv) + 1;
7714 } while (*++argv);
7715 p = xmalloc(len);
7716 pi->cmdtext = p;
7717 argv = pi->cmds[0].argv;
7718 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007719 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007720 *p++ = ' ';
7721 } while (*++argv);
7722 p[-1] = '\0';
7723 return pi->cmdtext;
7724}
7725
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007726static void remove_job_from_table(struct pipe *pi)
7727{
7728 struct pipe *prev_pipe;
7729
7730 if (pi == G.job_list) {
7731 G.job_list = pi->next;
7732 } else {
7733 prev_pipe = G.job_list;
7734 while (prev_pipe->next != pi)
7735 prev_pipe = prev_pipe->next;
7736 prev_pipe->next = pi->next;
7737 }
7738 G.last_jobid = 0;
7739 if (G.job_list)
7740 G.last_jobid = G.job_list->jobid;
7741}
7742
7743static void delete_finished_job(struct pipe *pi)
7744{
7745 remove_job_from_table(pi);
7746 free_pipe(pi);
7747}
7748
7749static void clean_up_last_dead_job(void)
7750{
7751 if (G.job_list && !G.job_list->alive_cmds)
7752 delete_finished_job(G.job_list);
7753}
7754
Denys Vlasenko16096292017-07-10 10:00:28 +02007755static void insert_job_into_table(struct pipe *pi)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007756{
7757 struct pipe *job, **jobp;
7758 int i;
7759
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007760 clean_up_last_dead_job();
7761
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007762 /* Find the end of the list, and find next job ID to use */
7763 i = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007764 jobp = &G.job_list;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007765 while ((job = *jobp) != NULL) {
7766 if (job->jobid > i)
7767 i = job->jobid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007768 jobp = &job->next;
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007769 }
7770 pi->jobid = i + 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007771
Denys Vlasenko9e55a152017-07-10 10:01:12 +02007772 /* Create a new job struct at the end */
7773 job = *jobp = xmemdup(pi, sizeof(*pi));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007774 job->next = NULL;
7775 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7776 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7777 for (i = 0; i < pi->num_cmds; i++) {
7778 job->cmds[i].pid = pi->cmds[i].pid;
7779 /* all other fields are not used and stay zero */
7780 }
7781 job->cmdtext = xstrdup(get_cmdtext(pi));
7782
7783 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007784 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007785 G.last_jobid = job->jobid;
7786}
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007787#endif /* JOB */
7788
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007789static int job_exited_or_stopped(struct pipe *pi)
7790{
7791 int rcode, i;
7792
7793 if (pi->alive_cmds != pi->stopped_cmds)
7794 return -1;
7795
7796 /* All processes in fg pipe have exited or stopped */
7797 rcode = 0;
7798 i = pi->num_cmds;
7799 while (--i >= 0) {
7800 rcode = pi->cmds[i].cmd_exitcode;
7801 /* usually last process gives overall exitstatus,
7802 * but with "set -o pipefail", last *failed* process does */
7803 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7804 break;
7805 }
7806 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7807 return rcode;
7808}
7809
Denys Vlasenko7e675362016-10-28 21:57:31 +02007810static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007811{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007812#if ENABLE_HUSH_JOB
7813 struct pipe *pi;
7814#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007815 int i, dead;
7816
7817 dead = WIFEXITED(status) || WIFSIGNALED(status);
7818
7819#if DEBUG_JOBS
7820 if (WIFSTOPPED(status))
7821 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7822 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7823 if (WIFSIGNALED(status))
7824 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7825 childpid, WTERMSIG(status), WEXITSTATUS(status));
7826 if (WIFEXITED(status))
7827 debug_printf_jobs("pid %d exited, exitcode %d\n",
7828 childpid, WEXITSTATUS(status));
7829#endif
7830 /* Were we asked to wait for a fg pipe? */
7831 if (fg_pipe) {
7832 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007833
Denys Vlasenko7e675362016-10-28 21:57:31 +02007834 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007835 int rcode;
7836
Denys Vlasenko7e675362016-10-28 21:57:31 +02007837 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7838 if (fg_pipe->cmds[i].pid != childpid)
7839 continue;
7840 if (dead) {
7841 int ex;
7842 fg_pipe->cmds[i].pid = 0;
7843 fg_pipe->alive_cmds--;
7844 ex = WEXITSTATUS(status);
7845 /* bash prints killer signal's name for *last*
7846 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7847 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7848 */
7849 if (WIFSIGNALED(status)) {
7850 int sig = WTERMSIG(status);
7851 if (i == fg_pipe->num_cmds-1)
7852 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7853 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7854 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7855 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7856 * Maybe we need to use sig | 128? */
7857 ex = sig + 128;
7858 }
7859 fg_pipe->cmds[i].cmd_exitcode = ex;
7860 } else {
7861 fg_pipe->stopped_cmds++;
7862 }
7863 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7864 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007865 rcode = job_exited_or_stopped(fg_pipe);
7866 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007867/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7868 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7869 * and "killall -STOP cat" */
7870 if (G_interactive_fd) {
7871#if ENABLE_HUSH_JOB
7872 if (fg_pipe->alive_cmds != 0)
Denys Vlasenko16096292017-07-10 10:00:28 +02007873 insert_job_into_table(fg_pipe);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007874#endif
7875 return rcode;
7876 }
7877 if (fg_pipe->alive_cmds == 0)
7878 return rcode;
7879 }
7880 /* There are still running processes in the fg_pipe */
7881 return -1;
7882 }
Denys Vlasenko10ad6222017-04-17 16:13:32 +02007883 /* It wasn't in fg_pipe, look for process in bg pipes */
Denys Vlasenko7e675362016-10-28 21:57:31 +02007884 }
7885
7886#if ENABLE_HUSH_JOB
7887 /* We were asked to wait for bg or orphaned children */
7888 /* No need to remember exitcode in this case */
7889 for (pi = G.job_list; pi; pi = pi->next) {
7890 for (i = 0; i < pi->num_cmds; i++) {
7891 if (pi->cmds[i].pid == childpid)
7892 goto found_pi_and_prognum;
7893 }
7894 }
7895 /* Happens when shell is used as init process (init=/bin/sh) */
7896 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7897 return -1; /* this wasn't a process from fg_pipe */
7898
7899 found_pi_and_prognum:
7900 if (dead) {
7901 /* child exited */
Denys Vlasenko840a4352017-07-07 22:56:02 +02007902 int rcode = WEXITSTATUS(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007903 if (WIFSIGNALED(status))
Denys Vlasenko840a4352017-07-07 22:56:02 +02007904 rcode = 128 + WTERMSIG(status);
7905 pi->cmds[i].cmd_exitcode = rcode;
7906 if (G.last_bg_pid == pi->cmds[i].pid)
7907 G.last_bg_pid_exitcode = rcode;
7908 pi->cmds[i].pid = 0;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007909 pi->alive_cmds--;
7910 if (!pi->alive_cmds) {
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007911 if (G_interactive_fd) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007912 printf(JOB_STATUS_FORMAT, pi->jobid,
7913 "Done", pi->cmdtext);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +02007914 delete_finished_job(pi);
7915 } else {
7916/*
7917 * bash deletes finished jobs from job table only in interactive mode,
7918 * after "jobs" cmd, or if pid of a new process matches one of the old ones
7919 * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
7920 * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
7921 * We only retain one "dead" job, if it's the single job on the list.
7922 * This covers most of real-world scenarios where this is useful.
7923 */
7924 if (pi != G.job_list)
7925 delete_finished_job(pi);
7926 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007927 }
7928 } else {
7929 /* child stopped */
7930 pi->stopped_cmds++;
7931 }
7932#endif
7933 return -1; /* this wasn't a process from fg_pipe */
7934}
7935
7936/* Check to see if any processes have exited -- if they have,
7937 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007938 *
7939 * If non-NULL fg_pipe: wait for its completion or stop.
7940 * Return its exitcode or zero if stopped.
7941 *
7942 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7943 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7944 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7945 * or 0 if no children changed status.
7946 *
7947 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7948 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7949 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02007950 */
7951static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7952{
7953 int attributes;
7954 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007955 int rcode = 0;
7956
7957 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7958
7959 attributes = WUNTRACED;
7960 if (fg_pipe == NULL)
7961 attributes |= WNOHANG;
7962
7963 errno = 0;
7964#if ENABLE_HUSH_FAST
7965 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7966//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7967//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7968 /* There was neither fork nor SIGCHLD since last waitpid */
7969 /* Avoid doing waitpid syscall if possible */
7970 if (!G.we_have_children) {
7971 errno = ECHILD;
7972 return -1;
7973 }
7974 if (fg_pipe == NULL) { /* is WNOHANG set? */
7975 /* We have children, but they did not exit
7976 * or stop yet (we saw no SIGCHLD) */
7977 return 0;
7978 }
7979 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7980 }
7981#endif
7982
7983/* Do we do this right?
7984 * bash-3.00# sleep 20 | false
7985 * <ctrl-Z pressed>
7986 * [3]+ Stopped sleep 20 | false
7987 * bash-3.00# echo $?
7988 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7989 * [hush 1.14.0: yes we do it right]
7990 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007991 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007992 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007993#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02007994 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007995 i = G.count_SIGCHLD;
7996#endif
7997 childpid = waitpid(-1, &status, attributes);
7998 if (childpid <= 0) {
7999 if (childpid && errno != ECHILD)
8000 bb_perror_msg("waitpid");
8001#if ENABLE_HUSH_FAST
8002 else { /* Until next SIGCHLD, waitpid's are useless */
8003 G.we_have_children = (childpid == 0);
8004 G.handled_SIGCHLD = i;
8005//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8006 }
8007#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02008008 /* ECHILD (no children), or 0 (no change in children status) */
8009 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008010 break;
8011 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008012 rcode = process_wait_result(fg_pipe, childpid, status);
8013 if (rcode >= 0) {
8014 /* fg_pipe exited or stopped */
8015 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008016 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008017 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008018 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008019 rcode = WEXITSTATUS(status);
8020 if (WIFSIGNALED(status))
8021 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01008022 if (WIFSTOPPED(status))
8023 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
8024 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02008025 rcode++;
8026 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008027 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02008028 /* This wasn't one of our processes, or */
8029 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008030 } /* while (waitpid succeeds)... */
8031
8032 return rcode;
8033}
8034
8035#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02008036static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008037{
8038 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02008039 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008040 if (G_saved_tty_pgrp) {
8041 /* Job finished, move the shell to the foreground */
8042 p = getpgrp(); /* our process group id */
8043 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
8044 tcsetpgrp(G_interactive_fd, p);
8045 }
8046 return rcode;
8047}
8048#endif
8049
8050/* Start all the jobs, but don't wait for anything to finish.
8051 * See checkjobs().
8052 *
8053 * Return code is normally -1, when the caller has to wait for children
8054 * to finish to determine the exit status of the pipe. If the pipe
8055 * is a simple builtin command, however, the action is done by the
8056 * time run_pipe returns, and the exit code is provided as the
8057 * return value.
8058 *
8059 * Returns -1 only if started some children. IOW: we have to
8060 * mask out retvals of builtins etc with 0xff!
8061 *
8062 * The only case when we do not need to [v]fork is when the pipe
8063 * is single, non-backgrounded, non-subshell command. Examples:
8064 * cmd ; ... { list } ; ...
8065 * cmd && ... { list } && ...
8066 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008067 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008068 * or (if SH_STANDALONE) an applet, and we can run the { list }
8069 * with run_list. If it isn't one of these, we fork and exec cmd.
8070 *
8071 * Cases when we must fork:
8072 * non-single: cmd | cmd
8073 * backgrounded: cmd & { list } &
8074 * subshell: ( list ) [&]
8075 */
8076#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01008077#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008078 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
8079#endif
8080static int redirect_and_varexp_helper(char ***new_env_p,
8081 struct variable **old_vars_p,
8082 struct command *command,
Denys Vlasenko2db74612017-07-07 22:07:28 +02008083 struct squirrel **sqp,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008084 char **argv_expanded)
8085{
8086 /* setup_redirects acts on file descriptors, not FILEs.
8087 * This is perfect for work that comes after exec().
8088 * Is it really safe for inline use? Experimentally,
8089 * things seem to work. */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008090 int rcode = setup_redirects(command, sqp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008091 if (rcode == 0) {
8092 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
8093 *new_env_p = new_env;
8094 dump_cmd_in_x_mode(new_env);
8095 dump_cmd_in_x_mode(argv_expanded);
8096 if (old_vars_p)
8097 *old_vars_p = set_vars_and_save_old(new_env);
8098 }
8099 return rcode;
8100}
8101static NOINLINE int run_pipe(struct pipe *pi)
8102{
8103 static const char *const null_ptr = NULL;
8104
8105 int cmd_no;
8106 int next_infd;
8107 struct command *command;
8108 char **argv_expanded;
8109 char **argv;
Denys Vlasenko2db74612017-07-07 22:07:28 +02008110 struct squirrel *squirrel = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008111 int rcode;
8112
8113 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
8114 debug_enter();
8115
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02008116 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
8117 * Result should be 3 lines: q w e, qwe, q w e
8118 */
8119 G.ifs = get_local_var_value("IFS");
8120 if (!G.ifs)
8121 G.ifs = defifs;
8122
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008123 IF_HUSH_JOB(pi->pgrp = -1;)
8124 pi->stopped_cmds = 0;
8125 command = &pi->cmds[0];
8126 argv_expanded = NULL;
8127
8128 if (pi->num_cmds != 1
8129 || pi->followup == PIPE_BG
8130 || command->cmd_type == CMD_SUBSHELL
8131 ) {
8132 goto must_fork;
8133 }
8134
8135 pi->alive_cmds = 1;
8136
8137 debug_printf_exec(": group:%p argv:'%s'\n",
8138 command->group, command->argv ? command->argv[0] : "NONE");
8139
8140 if (command->group) {
8141#if ENABLE_HUSH_FUNCTIONS
8142 if (command->cmd_type == CMD_FUNCDEF) {
8143 /* "executing" func () { list } */
8144 struct function *funcp;
8145
8146 funcp = new_function(command->argv[0]);
8147 /* funcp->name is already set to argv[0] */
8148 funcp->body = command->group;
8149# if !BB_MMU
8150 funcp->body_as_string = command->group_as_string;
8151 command->group_as_string = NULL;
8152# endif
8153 command->group = NULL;
8154 command->argv[0] = NULL;
8155 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
8156 funcp->parent_cmd = command;
8157 command->child_func = funcp;
8158
8159 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
8160 debug_leave();
8161 return EXIT_SUCCESS;
8162 }
8163#endif
8164 /* { list } */
8165 debug_printf("non-subshell group\n");
8166 rcode = 1; /* exitcode if redir failed */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008167 if (setup_redirects(command, &squirrel) == 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008168 debug_printf_exec(": run_list\n");
8169 rcode = run_list(command->group) & 0xff;
8170 }
8171 restore_redirects(squirrel);
8172 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8173 debug_leave();
8174 debug_printf_exec("run_pipe: return %d\n", rcode);
8175 return rcode;
8176 }
8177
8178 argv = command->argv ? command->argv : (char **) &null_ptr;
8179 {
8180 const struct built_in_command *x;
8181#if ENABLE_HUSH_FUNCTIONS
8182 const struct function *funcp;
8183#else
8184 enum { funcp = 0 };
8185#endif
8186 char **new_env = NULL;
8187 struct variable *old_vars = NULL;
8188
Denys Vlasenko5807e182018-02-08 19:19:04 +01008189#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008190 if (G.lineno_var)
8191 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8192#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008193
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008194 if (argv[command->assignment_cnt] == NULL) {
8195 /* Assignments, but no command */
8196 /* Ensure redirects take effect (that is, create files).
8197 * Try "a=t >file" */
8198#if 0 /* A few cases in testsuite fail with this code. FIXME */
Denys Vlasenko2db74612017-07-07 22:07:28 +02008199 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, &squirrel, /*argv_expanded:*/ NULL);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008200 /* Set shell variables */
8201 if (new_env) {
8202 argv = new_env;
8203 while (*argv) {
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008204 if (set_local_var(*argv, /*flag:*/ 0)) {
8205 /* assignment to readonly var / putenv error? */
8206 rcode = 1;
8207 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008208 argv++;
8209 }
8210 }
8211 /* Redirect error sets $? to 1. Otherwise,
8212 * if evaluating assignment value set $?, retain it.
8213 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8214 if (rcode == 0)
8215 rcode = G.last_exitcode;
8216 /* Exit, _skipping_ variable restoring code: */
8217 goto clean_up_and_ret0;
8218
8219#else /* Older, bigger, but more correct code */
8220
Denys Vlasenko2db74612017-07-07 22:07:28 +02008221 rcode = setup_redirects(command, &squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008222 restore_redirects(squirrel);
8223 /* Set shell variables */
8224 if (G_x_mode)
8225 bb_putchar_stderr('+');
8226 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02008227 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008228 if (G_x_mode)
8229 fprintf(stderr, " %s", p);
8230 debug_printf_exec("set shell var:'%s'->'%s'\n",
8231 *argv, p);
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02008232 if (set_local_var(p, /*flag:*/ 0)) {
8233 /* assignment to readonly var / putenv error? */
8234 rcode = 1;
8235 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008236 argv++;
8237 }
8238 if (G_x_mode)
8239 bb_putchar_stderr('\n');
8240 /* Redirect error sets $? to 1. Otherwise,
8241 * if evaluating assignment value set $?, retain it.
8242 * Try "false; q=`exit 2`; echo $?" - should print 2: */
8243 if (rcode == 0)
8244 rcode = G.last_exitcode;
8245 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8246 debug_leave();
8247 debug_printf_exec("run_pipe: return %d\n", rcode);
8248 return rcode;
8249#endif
8250 }
8251
8252 /* Expand the rest into (possibly) many strings each */
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01008253#if BASH_TEST2
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008254 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008255 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008256 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008257#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01008258 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008259 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
8260 }
8261
8262 /* if someone gives us an empty string: `cmd with empty output` */
8263 if (!argv_expanded[0]) {
8264 free(argv_expanded);
8265 debug_leave();
8266 return G.last_exitcode;
8267 }
8268
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008269#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko75481d32017-07-31 05:27:09 +02008270 /* Check if argv[0] matches any functions (this goes before bltins) */
8271 funcp = find_function(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008272#endif
Denys Vlasenko75481d32017-07-31 05:27:09 +02008273 x = NULL;
8274 if (!funcp)
8275 x = find_builtin(argv_expanded[0]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008276 if (x || funcp) {
8277 if (!funcp) {
8278 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
8279 debug_printf("exec with redirects only\n");
8280 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008281 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008282 goto clean_up_and_ret1;
8283 }
8284 }
Denys Vlasenko2db74612017-07-07 22:07:28 +02008285 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008286 if (rcode == 0) {
8287 if (!funcp) {
8288 debug_printf_exec(": builtin '%s' '%s'...\n",
8289 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008290 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008291 rcode = x->b_function(argv_expanded) & 0xff;
8292 fflush_all();
8293 }
8294#if ENABLE_HUSH_FUNCTIONS
8295 else {
8296# if ENABLE_HUSH_LOCAL
8297 struct variable **sv;
8298 sv = G.shadowed_vars_pp;
8299 G.shadowed_vars_pp = &old_vars;
8300# endif
8301 debug_printf_exec(": function '%s' '%s'...\n",
8302 funcp->name, argv_expanded[1]);
8303 rcode = run_function(funcp, argv_expanded) & 0xff;
8304# if ENABLE_HUSH_LOCAL
8305 G.shadowed_vars_pp = sv;
8306# endif
8307 }
8308#endif
8309 }
8310 clean_up_and_ret:
8311 unset_vars(new_env);
8312 add_vars(old_vars);
8313/* clean_up_and_ret0: */
8314 restore_redirects(squirrel);
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008315 /*
8316 * Try "usleep 99999999" + ^C + "echo $?"
8317 * with FEATURE_SH_NOFORK=y.
8318 */
8319 if (!funcp) {
8320 /* It was builtin or nofork.
8321 * if this would be a real fork/execed program,
8322 * it should have died if a fatal sig was received.
8323 * But OTOH, there was no separate process,
8324 * the sig was sent to _shell_, not to non-existing
8325 * child.
8326 * Let's just handle ^C only, this one is obvious:
8327 * we aren't ok with exitcode 0 when ^C was pressed
8328 * during builtin/nofork.
8329 */
8330 if (sigismember(&G.pending_set, SIGINT))
8331 rcode = 128 + SIGINT;
8332 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008333 clean_up_and_ret1:
8334 free(argv_expanded);
8335 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
8336 debug_leave();
8337 debug_printf_exec("run_pipe return %d\n", rcode);
8338 return rcode;
8339 }
8340
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008341 if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008342 int n = find_applet_by_name(argv_expanded[0]);
8343 if (n >= 0 && APPLET_IS_NOFORK(n)) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02008344 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, &squirrel, argv_expanded);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008345 if (rcode == 0) {
8346 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
8347 argv_expanded[0], argv_expanded[1]);
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008348 /*
8349 * Note: signals (^C) can't interrupt here.
8350 * We remember them and they will be acted upon
8351 * after applet returns.
8352 * This makes applets which can run for a long time
8353 * and/or wait for user input ineligible for NOFORK:
8354 * for example, "yes" or "rm" (rm -i waits for input).
8355 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008356 rcode = run_nofork_applet(n, argv_expanded);
8357 }
8358 goto clean_up_and_ret;
8359 }
8360 }
8361 /* It is neither builtin nor applet. We must fork. */
8362 }
8363
8364 must_fork:
8365 /* NB: argv_expanded may already be created, and that
8366 * might include `cmd` runs! Do not rerun it! We *must*
8367 * use argv_expanded if it's non-NULL */
8368
8369 /* Going to fork a child per each pipe member */
8370 pi->alive_cmds = 0;
8371 next_infd = 0;
8372
8373 cmd_no = 0;
8374 while (cmd_no < pi->num_cmds) {
8375 struct fd_pair pipefds;
8376#if !BB_MMU
8377 volatile nommu_save_t nommu_save;
8378 nommu_save.new_env = NULL;
8379 nommu_save.old_vars = NULL;
8380 nommu_save.argv = NULL;
8381 nommu_save.argv_from_re_execing = NULL;
8382#endif
8383 command = &pi->cmds[cmd_no];
8384 cmd_no++;
8385 if (command->argv) {
8386 debug_printf_exec(": pipe member '%s' '%s'...\n",
8387 command->argv[0], command->argv[1]);
8388 } else {
8389 debug_printf_exec(": pipe member with no argv\n");
8390 }
8391
8392 /* pipes are inserted between pairs of commands */
8393 pipefds.rd = 0;
8394 pipefds.wr = 1;
8395 if (cmd_no < pi->num_cmds)
8396 xpiped_pair(pipefds);
8397
Denys Vlasenko5807e182018-02-08 19:19:04 +01008398#if ENABLE_HUSH_LINENO_VAR
Denys Vlasenkob8d076b2018-01-19 16:00:57 +01008399 if (G.lineno_var)
8400 strcpy(G.lineno_var + sizeof("LINENO=")-1, utoa(command->lineno));
8401#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01008402
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008403 command->pid = BB_MMU ? fork() : vfork();
8404 if (!command->pid) { /* child */
8405#if ENABLE_HUSH_JOB
8406 disable_restore_tty_pgrp_on_exit();
8407 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
8408
8409 /* Every child adds itself to new process group
8410 * with pgid == pid_of_first_child_in_pipe */
8411 if (G.run_list_level == 1 && G_interactive_fd) {
8412 pid_t pgrp;
8413 pgrp = pi->pgrp;
8414 if (pgrp < 0) /* true for 1st process only */
8415 pgrp = getpid();
8416 if (setpgid(0, pgrp) == 0
8417 && pi->followup != PIPE_BG
8418 && G_saved_tty_pgrp /* we have ctty */
8419 ) {
8420 /* We do it in *every* child, not just first,
8421 * to avoid races */
8422 tcsetpgrp(G_interactive_fd, pgrp);
8423 }
8424 }
8425#endif
8426 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
8427 /* 1st cmd in backgrounded pipe
8428 * should have its stdin /dev/null'ed */
8429 close(0);
8430 if (open(bb_dev_null, O_RDONLY))
8431 xopen("/", O_RDONLY);
8432 } else {
8433 xmove_fd(next_infd, 0);
8434 }
8435 xmove_fd(pipefds.wr, 1);
8436 if (pipefds.rd > 1)
8437 close(pipefds.rd);
8438 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02008439 * and the pipe fd (fd#1) is available for dup'ing:
8440 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
8441 * of cmd1 goes into pipe.
8442 */
8443 if (setup_redirects(command, NULL)) {
8444 /* Happens when redir file can't be opened:
8445 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
8446 * FOO
8447 * hush: can't open '/qwe/rty': No such file or directory
8448 * BAZ
8449 * (echo BAR is not executed, it hits _exit(1) below)
8450 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008451 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02008452 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008453
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008454 /* Stores to nommu_save list of env vars putenv'ed
8455 * (NOMMU, on MMU we don't need that) */
8456 /* cast away volatility... */
8457 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
8458 /* pseudo_exec() does not return */
8459 }
8460
8461 /* parent or error */
8462#if ENABLE_HUSH_FAST
8463 G.count_SIGCHLD++;
8464//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
8465#endif
8466 enable_restore_tty_pgrp_on_exit();
8467#if !BB_MMU
8468 /* Clean up after vforked child */
8469 free(nommu_save.argv);
8470 free(nommu_save.argv_from_re_execing);
8471 unset_vars(nommu_save.new_env);
8472 add_vars(nommu_save.old_vars);
8473#endif
8474 free(argv_expanded);
8475 argv_expanded = NULL;
8476 if (command->pid < 0) { /* [v]fork failed */
8477 /* Clearly indicate, was it fork or vfork */
8478 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
8479 } else {
8480 pi->alive_cmds++;
8481#if ENABLE_HUSH_JOB
8482 /* Second and next children need to know pid of first one */
8483 if (pi->pgrp < 0)
8484 pi->pgrp = command->pid;
8485#endif
8486 }
8487
8488 if (cmd_no > 1)
8489 close(next_infd);
8490 if (cmd_no < pi->num_cmds)
8491 close(pipefds.wr);
8492 /* Pass read (output) pipe end to next iteration */
8493 next_infd = pipefds.rd;
8494 }
8495
8496 if (!pi->alive_cmds) {
8497 debug_leave();
8498 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
8499 return 1;
8500 }
8501
8502 debug_leave();
8503 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
8504 return -1;
8505}
8506
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008507/* NB: called by pseudo_exec, and therefore must not modify any
8508 * global data until exec/_exit (we can be a child after vfork!) */
8509static int run_list(struct pipe *pi)
8510{
8511#if ENABLE_HUSH_CASE
8512 char *case_word = NULL;
8513#endif
8514#if ENABLE_HUSH_LOOPS
8515 struct pipe *loop_top = NULL;
8516 char **for_lcur = NULL;
8517 char **for_list = NULL;
8518#endif
8519 smallint last_followup;
8520 smalluint rcode;
8521#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
8522 smalluint cond_code = 0;
8523#else
8524 enum { cond_code = 0 };
8525#endif
8526#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02008527 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008528 smallint last_rword; /* ditto */
8529#endif
8530
8531 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
8532 debug_enter();
8533
8534#if ENABLE_HUSH_LOOPS
8535 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01008536 {
8537 struct pipe *cpipe;
8538 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
8539 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
8540 continue;
8541 /* current word is FOR or IN (BOLD in comments below) */
8542 if (cpipe->next == NULL) {
8543 syntax_error("malformed for");
8544 debug_leave();
8545 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8546 return 1;
8547 }
8548 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
8549 if (cpipe->next->res_word == RES_DO)
8550 continue;
8551 /* next word is not "do". It must be "in" then ("FOR v in ...") */
8552 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
8553 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
8554 ) {
8555 syntax_error("malformed for");
8556 debug_leave();
8557 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
8558 return 1;
8559 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008560 }
8561 }
8562#endif
8563
8564 /* Past this point, all code paths should jump to ret: label
8565 * in order to return, no direct "return" statements please.
8566 * This helps to ensure that no memory is leaked. */
8567
8568#if ENABLE_HUSH_JOB
8569 G.run_list_level++;
8570#endif
8571
8572#if HAS_KEYWORDS
8573 rword = RES_NONE;
8574 last_rword = RES_XXXX;
8575#endif
8576 last_followup = PIPE_SEQ;
8577 rcode = G.last_exitcode;
8578
8579 /* Go through list of pipes, (maybe) executing them. */
8580 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008581 int r;
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008582 int sv_errexit_depth;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008583
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008584 if (G.flag_SIGINT)
8585 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02008586 if (G_flag_return_in_progress == 1)
8587 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008588
8589 IF_HAS_KEYWORDS(rword = pi->res_word;)
8590 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
8591 rword, cond_code, last_rword);
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008592
8593 sv_errexit_depth = G.errexit_depth;
Denys Vlasenko82d1c1f2017-12-31 17:30:02 +01008594 if (
8595#if ENABLE_HUSH_IF
8596 rword == RES_IF || rword == RES_ELIF ||
8597#endif
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008598 pi->followup != PIPE_SEQ
8599 ) {
8600 G.errexit_depth++;
8601 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008602#if ENABLE_HUSH_LOOPS
8603 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
8604 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
8605 ) {
8606 /* start of a loop: remember where loop starts */
8607 loop_top = pi;
8608 G.depth_of_loop++;
8609 }
8610#endif
8611 /* Still in the same "if...", "then..." or "do..." branch? */
8612 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
8613 if ((rcode == 0 && last_followup == PIPE_OR)
8614 || (rcode != 0 && last_followup == PIPE_AND)
8615 ) {
8616 /* It is "<true> || CMD" or "<false> && CMD"
8617 * and we should not execute CMD */
8618 debug_printf_exec("skipped cmd because of || or &&\n");
8619 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02008620 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008621 }
8622 }
8623 last_followup = pi->followup;
8624 IF_HAS_KEYWORDS(last_rword = rword;)
8625#if ENABLE_HUSH_IF
8626 if (cond_code) {
8627 if (rword == RES_THEN) {
8628 /* if false; then ... fi has exitcode 0! */
8629 G.last_exitcode = rcode = EXIT_SUCCESS;
8630 /* "if <false> THEN cmd": skip cmd */
8631 continue;
8632 }
8633 } else {
8634 if (rword == RES_ELSE || rword == RES_ELIF) {
8635 /* "if <true> then ... ELSE/ELIF cmd":
8636 * skip cmd and all following ones */
8637 break;
8638 }
8639 }
8640#endif
8641#if ENABLE_HUSH_LOOPS
8642 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
8643 if (!for_lcur) {
8644 /* first loop through for */
8645
8646 static const char encoded_dollar_at[] ALIGN1 = {
8647 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8648 }; /* encoded representation of "$@" */
8649 static const char *const encoded_dollar_at_argv[] = {
8650 encoded_dollar_at, NULL
8651 }; /* argv list with one element: "$@" */
8652 char **vals;
8653
8654 vals = (char**)encoded_dollar_at_argv;
8655 if (pi->next->res_word == RES_IN) {
8656 /* if no variable values after "in" we skip "for" */
8657 if (!pi->next->cmds[0].argv) {
8658 G.last_exitcode = rcode = EXIT_SUCCESS;
8659 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8660 break;
8661 }
8662 vals = pi->next->cmds[0].argv;
8663 } /* else: "for var; do..." -> assume "$@" list */
8664 /* create list of variable values */
8665 debug_print_strings("for_list made from", vals);
8666 for_list = expand_strvec_to_strvec(vals);
8667 for_lcur = for_list;
8668 debug_print_strings("for_list", for_list);
8669 }
8670 if (!*for_lcur) {
8671 /* "for" loop is over, clean up */
8672 free(for_list);
8673 for_list = NULL;
8674 for_lcur = NULL;
8675 break;
8676 }
8677 /* Insert next value from for_lcur */
8678 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02008679 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008680 continue;
8681 }
8682 if (rword == RES_IN) {
8683 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8684 }
8685 if (rword == RES_DONE) {
8686 continue; /* "done" has no cmds too */
8687 }
8688#endif
8689#if ENABLE_HUSH_CASE
8690 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008691 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008692 case_word = expand_strvec_to_string(pi->cmds->argv);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008693 unbackslash(case_word);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008694 continue;
8695 }
8696 if (rword == RES_MATCH) {
8697 char **argv;
8698
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008699 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008700 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8701 break;
8702 /* all prev words didn't match, does this one match? */
8703 argv = pi->cmds->argv;
8704 while (*argv) {
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008705 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008706 /* TODO: which FNM_xxx flags to use? */
8707 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
Denys Vlasenkobd43c672017-07-05 23:12:15 +02008708 debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n", pattern, case_word, cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008709 free(pattern);
8710 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008711 free(case_word);
8712 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008713 break;
8714 }
8715 argv++;
8716 }
8717 continue;
8718 }
8719 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008720 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008721 if (cond_code != 0)
8722 continue; /* not matched yet, skip this pipe */
8723 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008724 if (rword == RES_ESAC) {
8725 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8726 if (case_word) {
8727 /* "case" did not match anything: still set $? (to 0) */
8728 G.last_exitcode = rcode = EXIT_SUCCESS;
8729 }
8730 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008731#endif
8732 /* Just pressing <enter> in shell should check for jobs.
8733 * OTOH, in non-interactive shell this is useless
8734 * and only leads to extra job checks */
8735 if (pi->num_cmds == 0) {
8736 if (G_interactive_fd)
8737 goto check_jobs_and_continue;
8738 continue;
8739 }
8740
8741 /* After analyzing all keywords and conditions, we decided
8742 * to execute this pipe. NB: have to do checkjobs(NULL)
8743 * after run_pipe to collect any background children,
8744 * even if list execution is to be stopped. */
8745 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008746#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008747 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008748#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008749 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8750 if (r != -1) {
8751 /* We ran a builtin, function, or group.
8752 * rcode is already known
8753 * and we don't need to wait for anything. */
8754 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8755 G.last_exitcode = rcode;
8756 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008757#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008758 /* Was it "break" or "continue"? */
8759 if (G.flag_break_continue) {
8760 smallint fbc = G.flag_break_continue;
8761 /* We might fall into outer *loop*,
8762 * don't want to break it too */
8763 if (loop_top) {
8764 G.depth_break_continue--;
8765 if (G.depth_break_continue == 0)
8766 G.flag_break_continue = 0;
8767 /* else: e.g. "continue 2" should *break* once, *then* continue */
8768 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8769 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008770 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008771 break;
8772 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008773 /* "continue": simulate end of loop */
8774 rword = RES_DONE;
8775 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008776 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008777#endif
8778 if (G_flag_return_in_progress == 1) {
8779 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8780 break;
8781 }
8782 } else if (pi->followup == PIPE_BG) {
8783 /* What does bash do with attempts to background builtins? */
8784 /* even bash 3.2 doesn't do that well with nested bg:
8785 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8786 * I'm NOT treating inner &'s as jobs */
8787#if ENABLE_HUSH_JOB
8788 if (G.run_list_level == 1)
Denys Vlasenko16096292017-07-10 10:00:28 +02008789 insert_job_into_table(pi);
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008790#endif
8791 /* Last command's pid goes to $! */
8792 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denys Vlasenko840a4352017-07-07 22:56:02 +02008793 G.last_bg_pid_exitcode = 0;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008794 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +02008795/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008796 rcode = EXIT_SUCCESS;
8797 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008798 } else {
8799#if ENABLE_HUSH_JOB
8800 if (G.run_list_level == 1 && G_interactive_fd) {
8801 /* Waits for completion, then fg's main shell */
8802 rcode = checkjobs_and_fg_shell(pi);
8803 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008804 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008805 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008806#endif
8807 /* This one just waits for completion */
8808 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8809 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8810 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008811 G.last_exitcode = rcode;
8812 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008813 }
8814
Denys Vlasenko9fda6092017-07-14 13:36:48 +02008815 /* Handle "set -e" */
8816 if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
8817 debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
8818 if (G.errexit_depth == 0)
8819 hush_exit(rcode);
8820 }
8821 G.errexit_depth = sv_errexit_depth;
8822
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008823 /* Analyze how result affects subsequent commands */
8824#if ENABLE_HUSH_IF
8825 if (rword == RES_IF || rword == RES_ELIF)
8826 cond_code = rcode;
8827#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008828 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008829 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008830 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008831#if ENABLE_HUSH_LOOPS
8832 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008833 if (pi->next
8834 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008835 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008836 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008837 if (rword == RES_WHILE) {
8838 if (rcode) {
8839 /* "while false; do...done" - exitcode 0 */
8840 G.last_exitcode = rcode = EXIT_SUCCESS;
8841 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008842 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008843 }
8844 }
8845 if (rword == RES_UNTIL) {
8846 if (!rcode) {
8847 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008848 break;
8849 }
8850 }
8851 }
8852#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008853 } /* for (pi) */
8854
8855#if ENABLE_HUSH_JOB
8856 G.run_list_level--;
8857#endif
8858#if ENABLE_HUSH_LOOPS
8859 if (loop_top)
8860 G.depth_of_loop--;
8861 free(for_list);
8862#endif
8863#if ENABLE_HUSH_CASE
8864 free(case_word);
8865#endif
8866 debug_leave();
8867 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8868 return rcode;
8869}
8870
8871/* Select which version we will use */
8872static int run_and_free_list(struct pipe *pi)
8873{
8874 int rcode = 0;
8875 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08008876 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008877 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8878 rcode = run_list(pi);
8879 }
8880 /* free_pipe_list has the side effect of clearing memory.
8881 * In the long run that function can be merged with run_list,
8882 * but doing that now would hobble the debugging effort. */
8883 free_pipe_list(pi);
8884 debug_printf_exec("run_and_free_list return %d\n", rcode);
8885 return rcode;
8886}
8887
8888
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008889static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00008890{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008891 sighandler_t old_handler;
8892 unsigned sig = 0;
8893 while ((mask >>= 1) != 0) {
8894 sig++;
8895 if (!(mask & 1))
8896 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02008897 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008898 /* POSIX allows shell to re-enable SIGCHLD
8899 * even if it was SIG_IGN on entry.
8900 * Therefore we skip IGN check for it:
8901 */
8902 if (sig == SIGCHLD)
8903 continue;
Denys Vlasenko49e6bf22017-08-04 14:28:16 +02008904 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
8905 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
8906 */
8907 //if (sig == SIGHUP) continue; - TODO?
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008908 if (old_handler == SIG_IGN) {
8909 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008910 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008911#if ENABLE_HUSH_TRAP
8912 if (!G_traps)
8913 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8914 free(G_traps[sig]);
8915 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8916#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008917 }
8918 }
8919}
8920
8921/* Called a few times only (or even once if "sh -c") */
8922static void install_special_sighandlers(void)
8923{
Denis Vlasenkof9375282009-04-05 19:13:39 +00008924 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008925
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008926 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008927 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008928 if (G_interactive_fd) {
8929 mask |= SPECIAL_INTERACTIVE_SIGS;
8930 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008931 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008932 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008933 /* Careful, do not re-install handlers we already installed */
8934 if (G.special_sig_mask != mask) {
8935 unsigned diff = mask & ~G.special_sig_mask;
8936 G.special_sig_mask = mask;
8937 install_sighandlers(diff);
8938 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008939}
8940
8941#if ENABLE_HUSH_JOB
8942/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008943/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008944static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00008945{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008946 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008947
8948 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008949 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01008950 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8951 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008952 + (1 << SIGBUS ) * HUSH_DEBUG
8953 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01008954 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008955 + (1 << SIGABRT)
8956 /* bash 3.2 seems to handle these just like 'fatal' ones */
8957 + (1 << SIGPIPE)
8958 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008959 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008960 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008961 * we never want to restore pgrp on exit, and this fn is not called
8962 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008963 /*+ (1 << SIGHUP )*/
8964 /*+ (1 << SIGTERM)*/
8965 /*+ (1 << SIGINT )*/
8966 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008967 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008968
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008969 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008970}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00008971#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00008972
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008973static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00008974{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008975 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008976 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008977 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08008978 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008979 break;
8980 case 'x':
8981 IF_HUSH_MODE_X(G_x_mode = state;)
8982 break;
8983 case 'o':
8984 if (!o_opt) {
8985 /* "set -+o" without parameter.
8986 * in bash, set -o produces this output:
8987 * pipefail off
8988 * and set +o:
8989 * set +o pipefail
8990 * We always use the second form.
8991 */
8992 const char *p = o_opt_strings;
8993 idx = 0;
8994 while (*p) {
8995 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8996 idx++;
8997 p += strlen(p) + 1;
8998 }
8999 break;
9000 }
9001 idx = index_in_strings(o_opt_strings, o_opt);
9002 if (idx >= 0) {
9003 G.o_opt[idx] = state;
9004 break;
9005 }
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009006 case 'e':
9007 G.o_opt[OPT_O_ERREXIT] = state;
9008 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009009 default:
9010 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009011 }
9012 return EXIT_SUCCESS;
9013}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009014
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00009015int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00009016int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00009017{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009018 enum {
9019 OPT_login = (1 << 0),
9020 };
9021 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00009022 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009023 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009024 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009025 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009026 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00009027
Denis Vlasenko574f2f42008-02-27 18:41:59 +00009028 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02009029 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009030 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009031
Denys Vlasenko10c01312011-05-11 11:49:21 +02009032#if ENABLE_HUSH_FAST
9033 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
9034#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009035#if !BB_MMU
9036 G.argv0_for_re_execing = argv[0];
9037#endif
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009038
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009039 /* Deal with HUSH_VERSION */
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009040 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
9041 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009042 shell_ver = xzalloc(sizeof(*shell_ver));
9043 shell_ver->flg_export = 1;
9044 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02009045 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02009046 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009047 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009048
Denys Vlasenko605067b2010-09-06 12:10:51 +02009049 /* Create shell local variables from the values
9050 * currently living in the environment */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009051 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009052 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00009053 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009054 if (e) while (*e) {
9055 char *value = strchr(*e, '=');
9056 if (value) { /* paranoia */
9057 cur_var->next = xzalloc(sizeof(*cur_var));
9058 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00009059 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009060 cur_var->max_len = strlen(*e);
9061 cur_var->flg_export = 1;
9062 }
9063 e++;
9064 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02009065 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01009066 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
9067 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02009068
9069 /* Export PWD */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009070 set_pwd_var(SETFLAG_EXPORT);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009071
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009072#if BASH_HOSTNAME_VAR
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009073 /* Set (but not export) HOSTNAME unless already set */
9074 if (!get_local_var_value("HOSTNAME")) {
9075 struct utsname uts;
9076 uname(&uts);
9077 set_local_var_from_halves("HOSTNAME", uts.nodename);
9078 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009079 /* bash also exports SHLVL and _,
9080 * and sets (but doesn't export) the following variables:
9081 * BASH=/bin/bash
9082 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
9083 * BASH_VERSION='3.2.0(1)-release'
9084 * HOSTTYPE=i386
9085 * MACHTYPE=i386-pc-linux-gnu
9086 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02009087 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02009088 * EUID=<NNNNN>
9089 * UID=<NNNNN>
9090 * GROUPS=()
9091 * LINES=<NNN>
9092 * COLUMNS=<NNN>
9093 * BASH_ARGC=()
9094 * BASH_ARGV=()
9095 * BASH_LINENO=()
9096 * BASH_SOURCE=()
9097 * DIRSTACK=()
9098 * PIPESTATUS=([0]="0")
9099 * HISTFILE=/<xxx>/.bash_history
9100 * HISTFILESIZE=500
9101 * HISTSIZE=500
9102 * MAILCHECK=60
9103 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
9104 * SHELL=/bin/bash
9105 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
9106 * TERM=dumb
9107 * OPTERR=1
9108 * OPTIND=1
9109 * IFS=$' \t\n'
9110 * PS1='\s-\v\$ '
9111 * PS2='> '
9112 * PS4='+ '
9113 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02009114#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02009115
Denys Vlasenko5807e182018-02-08 19:19:04 +01009116#if ENABLE_HUSH_LINENO_VAR
9117 if (ENABLE_HUSH_LINENO_VAR) {
Denys Vlasenko6aad1dd2018-01-19 15:37:04 +01009118 char *p = xasprintf("LINENO=%*s", (int)(sizeof(int)*3), "");
9119 set_local_var(p, /*flags*/ 0);
9120 G.lineno_var = p; /* can't assign before set_local_var("LINENO=...") */
9121 }
9122#endif
9123
Denis Vlasenko38f63192007-01-22 09:03:07 +00009124#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02009125 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009126#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02009127
Eric Andersen94ac2442001-05-22 19:05:18 +00009128 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00009129 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00009130
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02009131 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00009132
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009133 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009134 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009135 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009136 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009137 * in order to intercept (more) signals.
9138 */
9139
9140 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009141 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009142 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009143 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009144 while (1) {
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009145 opt = getopt(argc, argv, "+c:exinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009146#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00009147 "<:$:R:V:"
9148# if ENABLE_HUSH_FUNCTIONS
9149 "F:"
9150# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009151#endif
9152 );
9153 if (opt <= 0)
9154 break;
Eric Andersen25f27032001-04-26 23:22:31 +00009155 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009156 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009157 /* Possibilities:
9158 * sh ... -c 'script'
9159 * sh ... -c 'script' ARG0 [ARG1...]
9160 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01009161 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009162 * "" needs to be replaced with NULL
9163 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01009164 * Note: the form without ARG0 never happens:
9165 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009166 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02009167 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009168 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009169 G.root_ppid = getppid();
9170 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009171 G.global_argv = argv + optind;
9172 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009173 if (builtin_argc) {
9174 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
9175 const struct built_in_command *x;
9176
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009177 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009178 x = find_builtin(optarg);
9179 if (x) { /* paranoia */
9180 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
9181 G.global_argv += builtin_argc;
9182 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01009183 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01009184 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009185 }
9186 goto final_return;
9187 }
9188 if (!G.global_argv[0]) {
9189 /* -c 'script' (no params): prevent empty $0 */
9190 G.global_argv--; /* points to argv[i] of 'script' */
9191 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02009192 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009193 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009194 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009195 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009196 goto final_return;
9197 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00009198 /* Well, we cannot just declare interactiveness,
9199 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009200 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009201 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00009202 case 's':
9203 /* "-s" means "read from stdin", but this is how we always
9204 * operate, so simply do nothing here. */
9205 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009206 case 'l':
9207 flags |= OPT_login;
9208 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009209#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009210 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02009211 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00009212 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009213 case '$': {
9214 unsigned long long empty_trap_mask;
9215
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009216 G.root_pid = bb_strtou(optarg, &optarg, 16);
9217 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02009218 G.root_ppid = bb_strtou(optarg, &optarg, 16);
9219 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009220 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
9221 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009222 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009223 optarg++;
9224 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009225 optarg++;
9226 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
9227 if (empty_trap_mask != 0) {
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009228 IF_HUSH_TRAP(int sig;)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009229 install_special_sighandlers();
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009230# if ENABLE_HUSH_TRAP
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009231 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009232 for (sig = 1; sig < NSIG; sig++) {
9233 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009234 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02009235 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009236 }
9237 }
Denys Vlasenko4ee824f2017-07-03 01:22:13 +02009238# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009239 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009240# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009241 optarg++;
9242 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009243# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00009244 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009245 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009246 case 'R':
9247 case 'V':
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009248 set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009249 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00009250# if ENABLE_HUSH_FUNCTIONS
9251 case 'F': {
9252 struct function *funcp = new_function(optarg);
9253 /* funcp->name is already set to optarg */
9254 /* funcp->body is set to NULL. It's a special case. */
9255 funcp->body_as_string = argv[optind];
9256 optind++;
9257 break;
9258 }
9259# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00009260#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009261 case 'n':
9262 case 'x':
Denys Vlasenko9fda6092017-07-14 13:36:48 +02009263 case 'e':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009264 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009265 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009266 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009267#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009268 fprintf(stderr, "Usage: sh [FILE]...\n"
9269 " or: sh -c command [args]...\n\n");
9270 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009271#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00009272 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00009273#endif
Eric Andersen25f27032001-04-26 23:22:31 +00009274 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009275 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009276
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009277 /* Skip options. Try "hush -l": $1 should not be "-l"! */
9278 G.global_argc = argc - (optind - 1);
9279 G.global_argv = argv + (optind - 1);
9280 G.global_argv[0] = argv[0];
9281
Denys Vlasenkodea47882009-10-09 15:40:49 +02009282 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009283 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02009284 G.root_ppid = getppid();
9285 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009286
9287 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009288 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009289 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009290 debug_printf("sourcing /etc/profile\n");
9291 input = fopen_for_read("/etc/profile");
9292 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009293 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009294 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009295 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009296 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009297 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009298 /* bash: after sourcing /etc/profile,
9299 * tries to source (in the given order):
9300 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009301 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009302 * bash also sources ~/.bash_logout on exit.
9303 * If called as sh, skips .bash_XXX files.
9304 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00009305 }
9306
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009307 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009308 FILE *input;
9309 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00009310 * "bash <script>" (which is never interactive (unless -i?))
9311 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00009312 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02009313 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00009314 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009315 G.global_argc--;
9316 G.global_argv++;
9317 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009318 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009319 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02009320 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009321 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009322 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009323 parse_and_run_file(input);
9324#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009325 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009326#endif
9327 goto final_return;
9328 }
9329
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009330 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009331 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00009332 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00009333
Denys Vlasenko28a105d2009-06-01 11:26:30 +02009334 /* A shell is interactive if the '-i' flag was given,
9335 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00009336 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00009337 * no arguments remaining or the -s flag given
9338 * standard input is a terminal
9339 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00009340 * Refer to Posix.2, the description of the 'sh' utility.
9341 */
9342#if ENABLE_HUSH_JOB
9343 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04009344 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
9345 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
9346 if (G_saved_tty_pgrp < 0)
9347 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009348
9349 /* try to dup stdin to high fd#, >= 255 */
Denys Vlasenko2db74612017-07-07 22:07:28 +02009350 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009351 if (G_interactive_fd < 0) {
9352 /* try to dup to any fd */
9353 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009354 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009355 /* give up */
9356 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04009357 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00009358 }
9359 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009360// TODO: track & disallow any attempts of user
9361// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00009362 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009363 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009364 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009365 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009366
Mike Frysinger38478a62009-05-20 04:48:06 -04009367 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009368 /* If we were run as 'hush &', sleep until we are
9369 * in the foreground (tty pgrp == our pgrp).
9370 * If we get started under a job aware app (like bash),
9371 * make sure we are now in charge so we don't fight over
9372 * who gets the foreground */
9373 while (1) {
9374 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04009375 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
9376 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009377 break;
9378 /* send TTIN to ourself (should stop us) */
9379 kill(- shell_pgrp, SIGTTIN);
9380 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00009381 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009382
Denys Vlasenkof58f7052011-05-12 02:10:33 +02009383 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009384 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009385
Mike Frysinger38478a62009-05-20 04:48:06 -04009386 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009387 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009388 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009389 /* Put ourselves in our own process group
9390 * (bash, too, does this only if ctty is available) */
9391 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
9392 /* Grab control of the terminal */
9393 tcsetpgrp(G_interactive_fd, getpid());
9394 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02009395 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009396
9397# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
9398 {
9399 const char *hp = get_local_var_value("HISTFILE");
9400 if (!hp) {
9401 hp = get_local_var_value("HOME");
9402 if (hp)
9403 hp = concat_path_file(hp, ".hush_history");
9404 } else {
9405 hp = xstrdup(hp);
9406 }
9407 if (hp) {
9408 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02009409 //set_local_var(xasprintf("HISTFILE=%s", ...));
9410 }
9411# if ENABLE_FEATURE_SH_HISTFILESIZE
9412 hp = get_local_var_value("HISTFILESIZE");
9413 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
9414# endif
9415 }
9416# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009417 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009418 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009419 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009420#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00009421 /* No job control compiled in, only prompt/line editing */
9422 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denys Vlasenko2db74612017-07-07 22:07:28 +02009423 G_interactive_fd = fcntl_F_DUPFD(STDIN_FILENO, 254);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009424 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009425 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009426 G_interactive_fd = dup(STDIN_FILENO);
9427 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009428 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009429 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00009430 }
9431 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009432 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00009433 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00009434 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009435 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009436#else
9437 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009438 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00009439#endif
9440 /* bash:
9441 * if interactive but not a login shell, sources ~/.bashrc
9442 * (--norc turns this off, --rcfile <file> overrides)
9443 */
9444
9445 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02009446 /* note: ash and hush share this string */
9447 printf("\n\n%s %s\n"
9448 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
9449 "\n",
9450 bb_banner,
9451 "hush - the humble shell"
9452 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00009453 }
9454
Denis Vlasenkof9375282009-04-05 19:13:39 +00009455 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00009456
Denis Vlasenkod76c0492007-05-25 02:16:25 +00009457 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009458 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00009459}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00009460
9461
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009462/*
9463 * Built-ins
9464 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009465static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009466{
9467 return 0;
9468}
9469
Denys Vlasenko265062d2017-01-10 15:13:30 +01009470#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02009471static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009472{
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +02009473 int argc = string_array_len(argv);
9474 return applet_main_func(argc, argv);
Mike Frysingerccb19592009-10-15 03:31:15 -04009475}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009476#endif
Kang-Che Sung027d3ab2017-01-11 14:18:15 +01009477#if ENABLE_HUSH_TEST || BASH_TEST2
Mike Frysingerccb19592009-10-15 03:31:15 -04009478static int FAST_FUNC builtin_test(char **argv)
9479{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009480 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009481}
Denys Vlasenko265062d2017-01-10 15:13:30 +01009482#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009483#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009484static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009485{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009486 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009487}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01009488#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009489#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009490static int FAST_FUNC builtin_printf(char **argv)
9491{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009492 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04009493}
9494#endif
9495
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009496#if ENABLE_HUSH_HELP
9497static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
9498{
9499 const struct built_in_command *x;
9500
9501 printf(
9502 "Built-in commands:\n"
9503 "------------------\n");
9504 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
9505 if (x->b_descr)
9506 printf("%-10s%s\n", x->b_cmd, x->b_descr);
9507 }
9508 return EXIT_SUCCESS;
9509}
9510#endif
9511
9512#if MAX_HISTORY && ENABLE_FEATURE_EDITING
9513static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9514{
9515 show_history(G.line_input_state);
9516 return EXIT_SUCCESS;
9517}
9518#endif
9519
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009520static char **skip_dash_dash(char **argv)
9521{
9522 argv++;
9523 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
9524 argv++;
9525 return argv;
9526}
9527
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009528static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009529{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009530 const char *newdir;
9531
9532 argv = skip_dash_dash(argv);
9533 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009534 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009535 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009536 * bash says "bash: cd: HOME not set" and does nothing
9537 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009538 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02009539 const char *home = get_local_var_value("HOME");
9540 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00009541 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009542 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009543 /* Mimic bash message exactly */
9544 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009545 return EXIT_FAILURE;
9546 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02009547 /* Read current dir (get_cwd(1) is inside) and set PWD.
9548 * Note: do not enforce exporting. If PWD was unset or unexported,
9549 * set it again, but do not export. bash does the same.
9550 */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009551 set_pwd_var(/*flag:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009552 return EXIT_SUCCESS;
9553}
9554
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009555static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
9556{
9557 puts(get_cwd(0));
9558 return EXIT_SUCCESS;
9559}
9560
9561static int FAST_FUNC builtin_eval(char **argv)
9562{
9563 int rcode = EXIT_SUCCESS;
9564
9565 argv = skip_dash_dash(argv);
Denys Vlasenko1f191122018-01-11 13:17:30 +01009566 if (argv[0]) {
9567 char *str = NULL;
9568
9569 if (argv[1]) {
9570 /* "The eval utility shall construct a command by
9571 * concatenating arguments together, separating
9572 * each with a <space> character."
9573 */
9574 char *p;
9575 unsigned len = 0;
9576 char **pp = argv;
9577 do
9578 len += strlen(*pp) + 1;
9579 while (*++pp);
9580 str = p = xmalloc(len);
9581 pp = argv;
9582 do {
9583 p = stpcpy(p, *pp);
9584 *p++ = ' ';
9585 } while (*++pp);
9586 p[-1] = '\0';
9587 }
9588
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009589 /* bash:
9590 * eval "echo Hi; done" ("done" is syntax error):
9591 * "echo Hi" will not execute too.
9592 */
Denys Vlasenko1f191122018-01-11 13:17:30 +01009593 parse_and_run_string(str ? str : argv[0]);
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009594 free(str);
9595 rcode = G.last_exitcode;
9596 }
9597 return rcode;
9598}
9599
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009600static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009601{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009602 argv = skip_dash_dash(argv);
9603 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009604 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009605
Denys Vlasenkof37eb392009-10-18 11:46:35 +02009606 /* Careful: we can end up here after [v]fork. Do not restore
9607 * tty pgrp then, only top-level shell process does that */
9608 if (G_saved_tty_pgrp && getpid() == G.root_pid)
9609 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
9610
Denys Vlasenko5b3d2eb2017-07-31 18:02:28 +02009611 /* Saved-redirect fds, script fds and G_interactive_fd are still
9612 * open here. However, they are all CLOEXEC, and execv below
9613 * closes them. Try interactive "exec ls -l /proc/self/fd",
9614 * it should show no extra open fds in the "ls" process.
9615 * If we'd try to run builtins/NOEXECs, this would need improving.
9616 */
9617 //close_saved_fds_and_FILE_fds();
9618
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009619 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009620 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02009621 * and tcsetpgrp, and this is inherently racy.
9622 */
9623 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009624}
9625
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009626static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009627{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00009628 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00009629
9630 /* interactive bash:
9631 * # trap "echo EEE" EXIT
9632 * # exit
9633 * exit
9634 * There are stopped jobs.
9635 * (if there are _stopped_ jobs, running ones don't count)
9636 * # exit
9637 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01009638 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00009639 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02009640 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00009641 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00009642
9643 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009644 argv = skip_dash_dash(argv);
9645 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009646 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009647 /* mimic bash: exit 123abc == exit 255 + error msg */
9648 xfunc_error_retval = 255;
9649 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009650 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009651}
9652
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009653#if ENABLE_HUSH_TYPE
9654/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
9655static int FAST_FUNC builtin_type(char **argv)
9656{
9657 int ret = EXIT_SUCCESS;
9658
9659 while (*++argv) {
9660 const char *type;
9661 char *path = NULL;
9662
9663 if (0) {} /* make conditional compile easier below */
9664 /*else if (find_alias(*argv))
9665 type = "an alias";*/
9666#if ENABLE_HUSH_FUNCTIONS
9667 else if (find_function(*argv))
9668 type = "a function";
9669#endif
9670 else if (find_builtin(*argv))
9671 type = "a shell builtin";
9672 else if ((path = find_in_path(*argv)) != NULL)
9673 type = path;
9674 else {
9675 bb_error_msg("type: %s: not found", *argv);
9676 ret = EXIT_FAILURE;
9677 continue;
9678 }
9679
9680 printf("%s is %s\n", *argv, type);
9681 free(path);
9682 }
9683
9684 return ret;
9685}
9686#endif
9687
9688#if ENABLE_HUSH_READ
9689/* Interruptibility of read builtin in bash
9690 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9691 *
9692 * Empty trap makes read ignore corresponding signal, for any signal.
9693 *
9694 * SIGINT:
9695 * - terminates non-interactive shell;
9696 * - interrupts read in interactive shell;
9697 * if it has non-empty trap:
9698 * - executes trap and returns to command prompt in interactive shell;
9699 * - executes trap and returns to read in non-interactive shell;
9700 * SIGTERM:
9701 * - is ignored (does not interrupt) read in interactive shell;
9702 * - terminates non-interactive shell;
9703 * if it has non-empty trap:
9704 * - executes trap and returns to read;
9705 * SIGHUP:
9706 * - terminates shell (regardless of interactivity);
9707 * if it has non-empty trap:
9708 * - executes trap and returns to read;
Denys Vlasenkof5470412017-05-22 19:34:45 +02009709 * SIGCHLD from children:
9710 * - does not interrupt read regardless of interactivity:
9711 * try: sleep 1 & read x; echo $x
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009712 */
9713static int FAST_FUNC builtin_read(char **argv)
9714{
9715 const char *r;
9716 char *opt_n = NULL;
9717 char *opt_p = NULL;
9718 char *opt_t = NULL;
9719 char *opt_u = NULL;
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009720 char *opt_d = NULL; /* optimized out if !BASH */
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009721 const char *ifs;
9722 int read_flags;
9723
9724 /* "!": do not abort on errors.
9725 * Option string must start with "sr" to match BUILTIN_READ_xxx
9726 */
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009727 read_flags = getopt32(argv,
9728#if BASH_READ_D
9729 "!srn:p:t:u:d:", &opt_n, &opt_p, &opt_t, &opt_u, &opt_d
9730#else
9731 "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u
9732#endif
9733 );
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009734 if (read_flags == (uint32_t)-1)
9735 return EXIT_FAILURE;
9736 argv += optind;
9737 ifs = get_local_var_value("IFS"); /* can be NULL */
9738
9739 again:
9740 r = shell_builtin_read(set_local_var_from_halves,
9741 argv,
9742 ifs,
9743 read_flags,
9744 opt_n,
9745 opt_p,
9746 opt_t,
Denys Vlasenko1f41c882017-08-09 13:52:36 +02009747 opt_u,
9748 opt_d
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009749 );
9750
9751 if ((uintptr_t)r == 1 && errno == EINTR) {
9752 unsigned sig = check_and_run_traps();
Denys Vlasenkof5470412017-05-22 19:34:45 +02009753 if (sig != SIGINT)
Denys Vlasenkoa1184af2017-01-10 15:58:02 +01009754 goto again;
9755 }
9756
9757 if ((uintptr_t)r > 1) {
9758 bb_error_msg("%s", r);
9759 r = (char*)(uintptr_t)1;
9760 }
9761
9762 return (uintptr_t)r;
9763}
9764#endif
9765
9766#if ENABLE_HUSH_UMASK
9767static int FAST_FUNC builtin_umask(char **argv)
9768{
9769 int rc;
9770 mode_t mask;
9771
9772 rc = 1;
9773 mask = umask(0);
9774 argv = skip_dash_dash(argv);
9775 if (argv[0]) {
9776 mode_t old_mask = mask;
9777
9778 /* numeric umasks are taken as-is */
9779 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9780 if (!isdigit(argv[0][0]))
9781 mask ^= 0777;
9782 mask = bb_parse_mode(argv[0], mask);
9783 if (!isdigit(argv[0][0]))
9784 mask ^= 0777;
9785 if ((unsigned)mask > 0777) {
9786 mask = old_mask;
9787 /* bash messages:
9788 * bash: umask: 'q': invalid symbolic mode operator
9789 * bash: umask: 999: octal number out of range
9790 */
9791 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
9792 rc = 0;
9793 }
9794 } else {
9795 /* Mimic bash */
9796 printf("%04o\n", (unsigned) mask);
9797 /* fall through and restore mask which we set to 0 */
9798 }
9799 umask(mask);
9800
9801 return !rc; /* rc != 0 - success */
9802}
9803#endif
9804
Denys Vlasenko41ade052017-01-08 18:56:24 +01009805#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009806static void print_escaped(const char *s)
9807{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009808 if (*s == '\'')
9809 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009810 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009811 const char *p = strchrnul(s, '\'');
9812 /* print 'xxxx', possibly just '' */
9813 printf("'%.*s'", (int)(p - s), s);
9814 if (*p == '\0')
9815 break;
9816 s = p;
9817 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009818 /* s points to '; print "'''...'''" */
9819 putchar('"');
9820 do putchar('\''); while (*++s == '\'');
9821 putchar('"');
9822 } while (*s);
9823}
Denys Vlasenko41ade052017-01-08 18:56:24 +01009824#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009825
Denys Vlasenko1e660422017-07-17 21:10:50 +02009826#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009827static int helper_export_local(char **argv, unsigned flags)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009828{
9829 do {
9830 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009831 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02009832
9833 /* So far we do not check that name is valid (TODO?) */
9834
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009835 if (*name_end == '\0') {
9836 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009837
Denys Vlasenko27c56f12010-09-07 09:56:34 +02009838 vpp = get_ptr_to_local_var(name, name_end - name);
9839 var = vpp ? *vpp : NULL;
9840
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009841 if (flags & SETFLAG_UNEXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009842 /* export -n NAME (without =VALUE) */
9843 if (var) {
9844 var->flg_export = 0;
9845 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
9846 unsetenv(name);
9847 } /* else: export -n NOT_EXISTING_VAR: no-op */
9848 continue;
9849 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009850 if (flags & SETFLAG_EXPORT) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02009851 /* export NAME (without =VALUE) */
9852 if (var) {
9853 var->flg_export = 1;
9854 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
9855 putenv(var->varstr);
9856 continue;
9857 }
9858 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009859 if (flags & SETFLAG_MAKE_RO) {
9860 /* readonly NAME (without =VALUE) */
9861 if (var) {
9862 var->flg_read_only = 1;
9863 continue;
9864 }
9865 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009866# if ENABLE_HUSH_LOCAL
Denys Vlasenkob95ee962017-07-17 21:19:53 +02009867 /* Is this "local" bltin? */
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009868 if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
9869 unsigned lvl = flags >> SETFLAG_LOCAL_SHIFT;
Denys Vlasenkob95ee962017-07-17 21:19:53 +02009870 if (var && var->func_nest_level == lvl) {
9871 /* "local x=abc; ...; local x" - ignore second local decl */
9872 continue;
9873 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02009874 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009875# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009876 /* Exporting non-existing variable.
9877 * bash does not put it in environment,
9878 * but remembers that it is exported,
9879 * and does put it in env when it is set later.
Denys Vlasenko1e660422017-07-17 21:10:50 +02009880 * We just set it to "" and export.
9881 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02009882 /* Or, it's "local NAME" (without =VALUE).
Denys Vlasenko1e660422017-07-17 21:10:50 +02009883 * bash sets the value to "".
9884 */
9885 /* Or, it's "readonly NAME" (without =VALUE).
9886 * bash remembers NAME and disallows its creation
9887 * in the future.
9888 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02009889 name = xasprintf("%s=", name);
9890 } else {
9891 /* (Un)exporting/making local NAME=VALUE */
9892 name = xstrdup(name);
9893 }
Denys Vlasenko38ef39a2017-07-18 01:40:01 +02009894 if (set_local_var(name, flags))
9895 return EXIT_FAILURE;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009896 } while (*++argv);
Denys Vlasenko1e660422017-07-17 21:10:50 +02009897 return EXIT_SUCCESS;
Denys Vlasenko295fef82009-06-03 12:47:26 +02009898}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009899#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009900
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009901#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009902static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009903{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00009904 unsigned opt_unexport;
9905
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02009906#if ENABLE_HUSH_EXPORT_N
9907 /* "!": do not abort on errors */
9908 opt_unexport = getopt32(argv, "!n");
9909 if (opt_unexport == (uint32_t)-1)
9910 return EXIT_FAILURE;
9911 argv += optind;
9912#else
9913 opt_unexport = 0;
9914 argv++;
9915#endif
9916
9917 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009918 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009919 if (e) {
9920 while (*e) {
9921#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009922 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009923#else
9924 /* ash emits: export VAR='VAL'
9925 * bash: declare -x VAR="VAL"
9926 * we follow ash example */
9927 const char *s = *e++;
9928 const char *p = strchr(s, '=');
9929
9930 if (!p) /* wtf? take next variable */
9931 continue;
9932 /* export var= */
9933 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009934 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009935 putchar('\n');
9936#endif
9937 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009938 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009939 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009940 return EXIT_SUCCESS;
9941 }
9942
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009943 return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009944}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009945#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009946
Denys Vlasenko295fef82009-06-03 12:47:26 +02009947#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009948static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009949{
9950 if (G.func_nest_level == 0) {
9951 bb_error_msg("%s: not in a function", argv[0]);
9952 return EXIT_FAILURE; /* bash compat */
9953 }
Denys Vlasenko1e660422017-07-17 21:10:50 +02009954 argv++;
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009955 return helper_export_local(argv, G.func_nest_level << SETFLAG_LOCAL_SHIFT);
Denys Vlasenko295fef82009-06-03 12:47:26 +02009956}
9957#endif
9958
Denys Vlasenko1e660422017-07-17 21:10:50 +02009959#if ENABLE_HUSH_READONLY
9960static int FAST_FUNC builtin_readonly(char **argv)
9961{
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009962 argv++;
9963 if (*argv == NULL) {
Denys Vlasenko1e660422017-07-17 21:10:50 +02009964 /* bash: readonly [-p]: list all readonly VARs
9965 * (-p has no effect in bash)
9966 */
9967 struct variable *e;
9968 for (e = G.top_var; e; e = e->next) {
9969 if (e->flg_read_only) {
9970//TODO: quote value: readonly VAR='VAL'
9971 printf("readonly %s\n", e->varstr);
9972 }
9973 }
9974 return EXIT_SUCCESS;
9975 }
Denys Vlasenko3bab36b2017-07-18 01:05:24 +02009976 return helper_export_local(argv, SETFLAG_MAKE_RO);
Denys Vlasenko1e660422017-07-17 21:10:50 +02009977}
9978#endif
9979
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009980#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009981/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9982static int FAST_FUNC builtin_unset(char **argv)
9983{
9984 int ret;
9985 unsigned opts;
9986
9987 /* "!": do not abort on errors */
9988 /* "+": stop at 1st non-option */
9989 opts = getopt32(argv, "!+vf");
9990 if (opts == (unsigned)-1)
9991 return EXIT_FAILURE;
9992 if (opts == 3) {
9993 bb_error_msg("unset: -v and -f are exclusive");
9994 return EXIT_FAILURE;
9995 }
9996 argv += optind;
9997
9998 ret = EXIT_SUCCESS;
9999 while (*argv) {
10000 if (!(opts & 2)) { /* not -f */
10001 if (unset_local_var(*argv)) {
10002 /* unset <nonexistent_var> doesn't fail.
10003 * Error is when one tries to unset RO var.
10004 * Message was printed by unset_local_var. */
10005 ret = EXIT_FAILURE;
10006 }
10007 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010008# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +020010009 else {
10010 unset_func(*argv);
10011 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010012# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010013 argv++;
10014 }
10015 return ret;
10016}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010017#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010018
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010019#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +020010020/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
10021 * built-in 'set' handler
10022 * SUSv3 says:
10023 * set [-abCefhmnuvx] [-o option] [argument...]
10024 * set [+abCefhmnuvx] [+o option] [argument...]
10025 * set -- [argument...]
10026 * set -o
10027 * set +o
10028 * Implementations shall support the options in both their hyphen and
10029 * plus-sign forms. These options can also be specified as options to sh.
10030 * Examples:
10031 * Write out all variables and their values: set
10032 * Set $1, $2, and $3 and set "$#" to 3: set c a b
10033 * Turn on the -x and -v options: set -xv
10034 * Unset all positional parameters: set --
10035 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
10036 * Set the positional parameters to the expansion of x, even if x expands
10037 * with a leading '-' or '+': set -- $x
10038 *
10039 * So far, we only support "set -- [argument...]" and some of the short names.
10040 */
10041static int FAST_FUNC builtin_set(char **argv)
10042{
10043 int n;
10044 char **pp, **g_argv;
10045 char *arg = *++argv;
10046
10047 if (arg == NULL) {
10048 struct variable *e;
10049 for (e = G.top_var; e; e = e->next)
10050 puts(e->varstr);
10051 return EXIT_SUCCESS;
10052 }
10053
10054 do {
10055 if (strcmp(arg, "--") == 0) {
10056 ++argv;
10057 goto set_argv;
10058 }
10059 if (arg[0] != '+' && arg[0] != '-')
10060 break;
10061 for (n = 1; arg[n]; ++n) {
10062 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
10063 goto error;
10064 if (arg[n] == 'o' && argv[1])
10065 argv++;
10066 }
10067 } while ((arg = *++argv) != NULL);
10068 /* Now argv[0] is 1st argument */
10069
10070 if (arg == NULL)
10071 return EXIT_SUCCESS;
10072 set_argv:
10073
10074 /* NB: G.global_argv[0] ($0) is never freed/changed */
10075 g_argv = G.global_argv;
10076 if (G.global_args_malloced) {
10077 pp = g_argv;
10078 while (*++pp)
10079 free(*pp);
10080 g_argv[1] = NULL;
10081 } else {
10082 G.global_args_malloced = 1;
10083 pp = xzalloc(sizeof(pp[0]) * 2);
10084 pp[0] = g_argv[0]; /* retain $0 */
10085 g_argv = pp;
10086 }
10087 /* This realloc's G.global_argv */
10088 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
10089
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +020010090 G.global_argc = 1 + string_array_len(pp + 1);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010091
10092 return EXIT_SUCCESS;
10093
10094 /* Nothing known, so abort */
10095 error:
Denys Vlasenko57000292018-01-12 14:41:45 +010010096 bb_error_msg("%s: %s: invalid option", "set", arg);
Denys Vlasenko61508d92016-10-02 21:12:02 +020010097 return EXIT_FAILURE;
10098}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +010010099#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010100
10101static int FAST_FUNC builtin_shift(char **argv)
10102{
10103 int n = 1;
10104 argv = skip_dash_dash(argv);
10105 if (argv[0]) {
Denys Vlasenkoe59591a2017-07-06 20:12:44 +020010106 n = bb_strtou(argv[0], NULL, 10);
10107 if (errno || n < 0) {
10108 /* shared string with ash.c */
10109 bb_error_msg("Illegal number: %s", argv[0]);
10110 /*
10111 * ash aborts in this case.
10112 * bash prints error message and set $? to 1.
10113 * Interestingly, for "shift 99999" bash does not
10114 * print error message, but does set $? to 1
10115 * (and does no shifting at all).
10116 */
10117 }
Denys Vlasenko61508d92016-10-02 21:12:02 +020010118 }
10119 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +010010120 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +020010121 int m = 1;
10122 while (m <= n)
10123 free(G.global_argv[m++]);
10124 }
10125 G.global_argc -= n;
10126 memmove(&G.global_argv[1], &G.global_argv[n+1],
10127 G.global_argc * sizeof(G.global_argv[0]));
10128 return EXIT_SUCCESS;
10129 }
10130 return EXIT_FAILURE;
10131}
10132
Denys Vlasenko74d40582017-08-11 01:32:46 +020010133#if ENABLE_HUSH_GETOPTS
10134static int FAST_FUNC builtin_getopts(char **argv)
10135{
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010136/* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
10137
Denys Vlasenko74d40582017-08-11 01:32:46 +020010138TODO:
Denys Vlasenko74d40582017-08-11 01:32:46 +020010139If a required argument is not found, and getopts is not silent,
10140a question mark (?) is placed in VAR, OPTARG is unset, and a
10141diagnostic message is printed. If getopts is silent, then a
10142colon (:) is placed in VAR and OPTARG is set to the option
10143character found.
10144
10145Test that VAR is a valid variable name?
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010146
10147"Whenever the shell is invoked, OPTIND shall be initialized to 1"
Denys Vlasenko74d40582017-08-11 01:32:46 +020010148*/
10149 char cbuf[2];
10150 const char *cp, *optstring, *var;
Denys Vlasenko238ff982017-08-29 13:38:30 +020010151 int c, n, exitcode, my_opterr;
10152 unsigned count;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010153
10154 optstring = *++argv;
10155 if (!optstring || !(var = *++argv)) {
10156 bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
10157 return EXIT_FAILURE;
10158 }
10159
Denys Vlasenko238ff982017-08-29 13:38:30 +020010160 if (argv[1])
10161 argv[0] = G.global_argv[0]; /* for error messages in getopt() */
10162 else
10163 argv = G.global_argv;
10164 cbuf[1] = '\0';
10165
10166 my_opterr = 0;
Denys Vlasenko048491f2017-08-17 12:36:39 +020010167 if (optstring[0] != ':') {
Denys Vlasenko419db032017-08-11 17:21:14 +020010168 cp = get_local_var_value("OPTERR");
Denys Vlasenko048491f2017-08-17 12:36:39 +020010169 /* 0 if "OPTERR=0", 1 otherwise */
Denys Vlasenko238ff982017-08-29 13:38:30 +020010170 my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
Denys Vlasenko419db032017-08-11 17:21:14 +020010171 }
Denys Vlasenko74d40582017-08-11 01:32:46 +020010172
10173 /* getopts stops on first non-option. Add "+" to force that */
10174 /*if (optstring[0] != '+')*/ {
10175 char *s = alloca(strlen(optstring) + 2);
10176 sprintf(s, "+%s", optstring);
10177 optstring = s;
10178 }
10179
Denys Vlasenko238ff982017-08-29 13:38:30 +020010180 /* Naively, now we should just
10181 * cp = get_local_var_value("OPTIND");
10182 * optind = cp ? atoi(cp) : 0;
10183 * optarg = NULL;
10184 * opterr = my_opterr;
10185 * c = getopt(string_array_len(argv), argv, optstring);
10186 * and be done? Not so fast...
10187 * Unlike normal getopt() usage in C programs, here
10188 * each successive call will (usually) have the same argv[] CONTENTS,
10189 * but not the ADDRESSES. Worse yet, it's possible that between
10190 * invocations of "getopts", there will be calls to shell builtins
10191 * which use getopt() internally. Example:
10192 * while getopts "abc" RES -a -bc -abc de; do
10193 * unset -ff func
10194 * done
10195 * This would not work correctly: getopt() call inside "unset"
10196 * modifies internal libc state which is tracking position in
10197 * multi-option strings ("-abc"). At best, it can skip options
10198 * or return the same option infinitely. With glibc implementation
10199 * of getopt(), it would use outright invalid pointers and return
10200 * garbage even _without_ "unset" mangling internal state.
10201 *
10202 * We resort to resetting getopt() state and calling it N times,
10203 * until we get Nth result (or failure).
10204 * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
10205 */
Denys Vlasenko60161812017-08-29 14:32:17 +020010206 GETOPT_RESET();
Denys Vlasenko238ff982017-08-29 13:38:30 +020010207 count = 0;
10208 n = string_array_len(argv);
10209 do {
10210 optarg = NULL;
10211 opterr = (count < G.getopt_count) ? 0 : my_opterr;
10212 c = getopt(n, argv, optstring);
10213 if (c < 0)
10214 break;
10215 count++;
10216 } while (count <= G.getopt_count);
10217
10218 /* Set OPTIND. Prevent resetting of the magic counter! */
10219 set_local_var_from_halves("OPTIND", utoa(optind));
10220 G.getopt_count = count; /* "next time, give me N+1'th result" */
Denys Vlasenko60161812017-08-29 14:32:17 +020010221 GETOPT_RESET(); /* just in case */
Denys Vlasenko419db032017-08-11 17:21:14 +020010222
10223 /* Set OPTARG */
10224 /* Always set or unset, never left as-is, even on exit/error:
10225 * "If no option was found, or if the option that was found
10226 * does not have an option-argument, OPTARG shall be unset."
10227 */
10228 cp = optarg;
10229 if (c == '?') {
10230 /* If ":optstring" and unknown option is seen,
10231 * it is stored to OPTARG.
10232 */
10233 if (optstring[1] == ':') {
10234 cbuf[0] = optopt;
10235 cp = cbuf;
10236 }
10237 }
10238 if (cp)
10239 set_local_var_from_halves("OPTARG", cp);
10240 else
10241 unset_local_var("OPTARG");
10242
10243 /* Convert -1 to "?" */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010244 exitcode = EXIT_SUCCESS;
10245 if (c < 0) { /* -1: end of options */
10246 exitcode = EXIT_FAILURE;
10247 c = '?';
10248 }
Denys Vlasenko419db032017-08-11 17:21:14 +020010249
Denys Vlasenko238ff982017-08-29 13:38:30 +020010250 /* Set VAR */
Denys Vlasenko74d40582017-08-11 01:32:46 +020010251 cbuf[0] = c;
Denys Vlasenko74d40582017-08-11 01:32:46 +020010252 set_local_var_from_halves(var, cbuf);
Denys Vlasenko9a7d0a02017-08-11 02:37:48 +020010253
Denys Vlasenko74d40582017-08-11 01:32:46 +020010254 return exitcode;
10255}
10256#endif
10257
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010258static int FAST_FUNC builtin_source(char **argv)
Denys Vlasenko61508d92016-10-02 21:12:02 +020010259{
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010260 char *arg_path, *filename;
10261 FILE *input;
10262 save_arg_t sv;
10263 char *args_need_save;
10264#if ENABLE_HUSH_FUNCTIONS
10265 smallint sv_flg;
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010266#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +020010267
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010268 argv = skip_dash_dash(argv);
10269 filename = argv[0];
10270 if (!filename) {
10271 /* bash says: "bash: .: filename argument required" */
10272 return 2; /* bash compat */
10273 }
10274 arg_path = NULL;
10275 if (!strchr(filename, '/')) {
10276 arg_path = find_in_path(filename);
10277 if (arg_path)
10278 filename = arg_path;
Denys Vlasenko54c21112018-01-27 20:46:45 +010010279 else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
Denys Vlasenkof7e0fea2018-01-27 19:05:59 +010010280 errno = ENOENT;
10281 bb_simple_perror_msg(filename);
10282 return EXIT_FAILURE;
10283 }
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010284 }
10285 input = remember_FILE(fopen_or_warn(filename, "r"));
10286 free(arg_path);
10287 if (!input) {
10288 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
10289 /* POSIX: non-interactive shell should abort here,
10290 * not merely fail. So far no one complained :)
10291 */
10292 return EXIT_FAILURE;
10293 }
10294
10295#if ENABLE_HUSH_FUNCTIONS
10296 sv_flg = G_flag_return_in_progress;
10297 /* "we are inside sourced file, ok to use return" */
10298 G_flag_return_in_progress = -1;
10299#endif
10300 args_need_save = argv[1]; /* used as a boolean variable */
10301 if (args_need_save)
10302 save_and_replace_G_args(&sv, argv);
10303
10304 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
10305 G.last_exitcode = 0;
10306 parse_and_run_file(input);
10307 fclose_and_forget(input);
10308
10309 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
10310 restore_G_args(&sv, argv);
10311#if ENABLE_HUSH_FUNCTIONS
10312 G_flag_return_in_progress = sv_flg;
10313#endif
10314
10315 return G.last_exitcode;
10316}
10317
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010318#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010319static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010320{
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010321 int sig;
10322 char *new_cmd;
10323
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010324 if (!G_traps)
10325 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010326
10327 argv++;
10328 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +000010329 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010330 /* No args: print all trapped */
10331 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010332 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010333 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010334 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020010335 /* note: bash adds "SIG", but only if invoked
10336 * as "bash". If called as "sh", or if set -o posix,
10337 * then it prints short signal names.
10338 * We are printing short names: */
10339 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010340 }
10341 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +010010342 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010343 return EXIT_SUCCESS;
10344 }
10345
10346 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010347 /* If first arg is a number: reset all specified signals */
10348 sig = bb_strtou(*argv, NULL, 10);
10349 if (errno == 0) {
10350 int ret;
10351 process_sig_list:
10352 ret = EXIT_SUCCESS;
10353 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010354 sighandler_t handler;
10355
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010356 sig = get_signum(*argv++);
Denys Vlasenko86981e32017-07-25 20:06:17 +020010357 if (sig < 0) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010358 ret = EXIT_FAILURE;
10359 /* Mimic bash message exactly */
Denys Vlasenko74562982017-07-06 18:40:45 +020010360 bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010361 continue;
10362 }
10363
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010364 free(G_traps[sig]);
10365 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010366
Denys Vlasenkoe89a2412010-01-12 15:19:31 +010010367 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010368 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010369
10370 /* There is no signal for 0 (EXIT) */
10371 if (sig == 0)
10372 continue;
10373
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010374 if (new_cmd)
10375 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
10376 else
10377 /* We are removing trap handler */
10378 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +020010379 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010380 }
10381 return ret;
10382 }
10383
10384 if (!argv[1]) { /* no second arg */
10385 bb_error_msg("trap: invalid arguments");
10386 return EXIT_FAILURE;
10387 }
10388
10389 /* First arg is "-": reset all specified to default */
10390 /* First arg is "--": skip it, the rest is "handler SIGs..." */
10391 /* Everything else: set arg as signal handler
10392 * (includes "" case, which ignores signal) */
10393 if (argv[0][0] == '-') {
10394 if (argv[0][1] == '\0') { /* "-" */
10395 /* new_cmd remains NULL: "reset these sigs" */
10396 goto reset_traps;
10397 }
10398 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
10399 argv++;
10400 }
10401 /* else: "-something", no special meaning */
10402 }
10403 new_cmd = *argv;
10404 reset_traps:
10405 argv++;
10406 goto process_sig_list;
10407}
Denys Vlasenko7a85c602017-01-08 17:40:18 +010010408#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +000010409
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010410#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010411static struct pipe *parse_jobspec(const char *str)
10412{
10413 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010414 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010415
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010416 if (sscanf(str, "%%%u", &jobnum) != 1) {
10417 if (str[0] != '%'
10418 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
10419 ) {
10420 bb_error_msg("bad argument '%s'", str);
10421 return NULL;
10422 }
10423 /* It is "%%", "%+" or "%" - current job */
10424 jobnum = G.last_jobid;
10425 if (jobnum == 0) {
10426 bb_error_msg("no current job");
10427 return NULL;
10428 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010429 }
10430 for (pi = G.job_list; pi; pi = pi->next) {
10431 if (pi->jobid == jobnum) {
10432 return pi;
10433 }
10434 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010435 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010436 return NULL;
10437}
10438
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010439static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
10440{
10441 struct pipe *job;
10442 const char *status_string;
10443
10444 checkjobs(NULL, 0 /*(no pid to wait for)*/);
10445 for (job = G.job_list; job; job = job->next) {
10446 if (job->alive_cmds == job->stopped_cmds)
10447 status_string = "Stopped";
10448 else
10449 status_string = "Running";
10450
10451 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
10452 }
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010453
10454 clean_up_last_dead_job();
10455
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010456 return EXIT_SUCCESS;
10457}
10458
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010459/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010460static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010461{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010462 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010463 struct pipe *pi;
10464
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010465 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010466 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +000010467
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010468 /* If they gave us no args, assume they want the last backgrounded task */
10469 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +000010470 for (pi = G.job_list; pi; pi = pi->next) {
10471 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010472 goto found;
10473 }
10474 }
10475 bb_error_msg("%s: no current job", argv[0]);
10476 return EXIT_FAILURE;
10477 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +010010478
10479 pi = parse_jobspec(argv[1]);
10480 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010481 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010482 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000010483 /* TODO: bash prints a string representation
10484 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -040010485 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010486 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +000010487 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010488 }
10489
10490 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010491 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
10492 for (i = 0; i < pi->num_cmds; i++) {
10493 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010494 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +000010495 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010496
10497 i = kill(- pi->pgrp, SIGCONT);
10498 if (i < 0) {
10499 if (errno == ESRCH) {
Denys Vlasenko16096292017-07-10 10:00:28 +020010500 delete_finished_job(pi);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010501 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010502 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010503 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010504 }
10505
Denis Vlasenko34d4d892009-04-04 20:24:37 +000010506 if (argv[0][0] == 'f') {
Denys Vlasenko16096292017-07-10 10:00:28 +020010507 remove_job_from_table(pi); /* FG job shouldn't be in job table */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +000010508 return checkjobs_and_fg_shell(pi);
10509 }
10510 return EXIT_SUCCESS;
10511}
10512#endif
10513
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010514#if ENABLE_HUSH_KILL
10515static int FAST_FUNC builtin_kill(char **argv)
10516{
10517 int ret = 0;
10518
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010519# if ENABLE_HUSH_JOB
10520 if (argv[1] && strcmp(argv[1], "-l") != 0) {
10521 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010522
10523 do {
10524 struct pipe *pi;
10525 char *dst;
10526 int j, n;
10527
10528 if (argv[i][0] != '%')
10529 continue;
10530 /*
10531 * "kill %N" - job kill
10532 * Converting to pgrp / pid kill
10533 */
10534 pi = parse_jobspec(argv[i]);
10535 if (!pi) {
10536 /* Eat bad jobspec */
10537 j = i;
10538 do {
10539 j++;
10540 argv[j - 1] = argv[j];
10541 } while (argv[j]);
10542 ret = 1;
10543 i--;
10544 continue;
10545 }
10546 /*
10547 * In jobs started under job control, we signal
10548 * entire process group by kill -PGRP_ID.
10549 * This happens, f.e., in interactive shell.
10550 *
10551 * Otherwise, we signal each child via
10552 * kill PID1 PID2 PID3.
10553 * Testcases:
10554 * sh -c 'sleep 1|sleep 1 & kill %1'
10555 * sh -c 'true|sleep 2 & sleep 1; kill %1'
10556 * sh -c 'true|sleep 1 & sleep 2; kill %1'
10557 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +010010558 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010559 dst = alloca(n * sizeof(int)*4);
10560 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010561 if (G_interactive_fd)
10562 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010563 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010564 struct command *cmd = &pi->cmds[j];
10565 /* Skip exited members of the job */
10566 if (cmd->pid == 0)
10567 continue;
10568 /*
10569 * kill_main has matching code to expect
10570 * leading space. Needed to not confuse
10571 * negative pids with "kill -SIGNAL_NO" syntax
10572 */
10573 dst += sprintf(dst, " %u", (int)cmd->pid);
10574 }
10575 *dst = '\0';
10576 } while (argv[++i]);
10577 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010578# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010579
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010580 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010581 ret = run_applet_main(argv, kill_main);
10582 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +010010583 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010584 return ret;
10585}
10586#endif
10587
10588#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +000010589/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010590#if !ENABLE_HUSH_JOB
10591# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
10592#endif
10593static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +020010594{
10595 int ret = 0;
10596 for (;;) {
10597 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010598 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010599
Denys Vlasenko830ea352016-11-08 04:59:11 +010010600 if (!sigisemptyset(&G.pending_set))
10601 goto check_sig;
10602
Denys Vlasenko7e675362016-10-28 21:57:31 +020010603 /* waitpid is not interruptible by SA_RESTARTed
10604 * signals which we use. Thus, this ugly dance:
10605 */
10606
10607 /* Make sure possible SIGCHLD is stored in kernel's
10608 * pending signal mask before we call waitpid.
10609 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010610 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +020010611 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010612 sigfillset(&oldset); /* block all signals, remember old set */
10613 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010614
10615 if (!sigisemptyset(&G.pending_set)) {
10616 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010617 goto restore;
10618 }
10619
10620 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010621/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010622 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010623 debug_printf_exec("checkjobs:%d\n", ret);
10624#if ENABLE_HUSH_JOB
10625 if (waitfor_pipe) {
10626 int rcode = job_exited_or_stopped(waitfor_pipe);
10627 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
10628 if (rcode >= 0) {
10629 ret = rcode;
10630 sigprocmask(SIG_SETMASK, &oldset, NULL);
10631 break;
10632 }
10633 }
10634#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +020010635 /* if ECHILD, there are no children (ret is -1 or 0) */
10636 /* if ret == 0, no children changed state */
10637 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010638 if (errno == ECHILD || ret) {
10639 ret--;
10640 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010641 ret = 0;
10642 sigprocmask(SIG_SETMASK, &oldset, NULL);
10643 break;
10644 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010645 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010646 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
10647 /* Note: sigsuspend invokes signal handler */
10648 sigsuspend(&oldset);
10649 restore:
10650 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +010010651 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +020010652 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010653 sig = check_and_run_traps();
10654 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7c40ddd2017-08-02 16:37:39 +020010655 /* Do this for any (non-ignored) signal, not only for ^C */
Denys Vlasenko7e675362016-10-28 21:57:31 +020010656 ret = 128 + sig;
10657 break;
10658 }
10659 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
10660 }
10661 return ret;
10662}
10663
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010664static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +000010665{
Denys Vlasenko7e675362016-10-28 21:57:31 +020010666 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +020010667 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +000010668
Denys Vlasenkob131cce2010-05-20 03:39:43 +020010669 argv = skip_dash_dash(argv);
10670 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010671 /* Don't care about wait results */
10672 /* Note 1: must wait until there are no more children */
10673 /* Note 2: must be interruptible */
10674 /* Examples:
10675 * $ sleep 3 & sleep 6 & wait
10676 * [1] 30934 sleep 3
10677 * [2] 30935 sleep 6
10678 * [1] Done sleep 3
10679 * [2] Done sleep 6
10680 * $ sleep 3 & sleep 6 & wait
10681 * [1] 30936 sleep 3
10682 * [2] 30937 sleep 6
10683 * [1] Done sleep 3
10684 * ^C <-- after ~4 sec from keyboard
10685 * $
10686 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010687 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +000010688 }
Mike Frysinger56bdea12009-03-28 20:01:58 +000010689
Denys Vlasenko7e675362016-10-28 21:57:31 +020010690 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +000010691 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010692 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010693#if ENABLE_HUSH_JOB
10694 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010695 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010696 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010697 wait_pipe = parse_jobspec(*argv);
10698 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010699 ret = job_exited_or_stopped(wait_pipe);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010700 if (ret < 0) {
Denys Vlasenko02affb42016-11-08 00:59:29 +010010701 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko2ed74e22017-07-14 19:58:46 +020010702 } else {
10703 /* waiting on "last dead job" removes it */
10704 clean_up_last_dead_job();
Denys Vlasenko13102632017-07-08 00:24:32 +020010705 }
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010706 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +010010707 /* else: parse_jobspec() already emitted error msg */
10708 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +010010709 }
10710#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +000010711 /* mimic bash message */
10712 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010713 ret = EXIT_FAILURE;
10714 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +000010715 }
Denys Vlasenko02affb42016-11-08 00:59:29 +010010716
Denys Vlasenko7e675362016-10-28 21:57:31 +020010717 /* Do we have such child? */
10718 ret = waitpid(pid, &status, WNOHANG);
10719 if (ret < 0) {
10720 /* No */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010721 ret = 127;
Denys Vlasenko7e675362016-10-28 21:57:31 +020010722 if (errno == ECHILD) {
Denys Vlasenko0c5657e2017-07-14 19:27:03 +020010723 if (pid == G.last_bg_pid) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010724 /* "wait $!" but last bg task has already exited. Try:
10725 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
10726 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010727 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010728 */
Denys Vlasenko840a4352017-07-07 22:56:02 +020010729 ret = G.last_bg_pid_exitcode;
Denys Vlasenko26ad94b2016-11-07 23:07:21 +010010730 } else {
10731 /* Example: "wait 1". mimic bash message */
10732 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010733 }
Denys Vlasenko7e675362016-10-28 21:57:31 +020010734 } else {
10735 /* ??? */
10736 bb_perror_msg("wait %s", *argv);
10737 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010738 continue; /* bash checks all argv[] */
10739 }
10740 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +020010741 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010742 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +020010743 } else {
10744 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +010010745 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +020010746 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010747 if (WIFSIGNALED(status))
10748 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010749 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +020010750 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +000010751
10752 return ret;
10753}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +010010754#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +000010755
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010756#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
10757static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
10758{
10759 if (argv[1]) {
10760 def = bb_strtou(argv[1], NULL, 10);
10761 if (errno || def < def_min || argv[2]) {
10762 bb_error_msg("%s: bad arguments", argv[0]);
10763 def = UINT_MAX;
10764 }
10765 }
10766 return def;
10767}
10768#endif
10769
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010770#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010771static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010772{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010773 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +000010774 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010775 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +020010776 /* if we came from builtin_continue(), need to undo "= 1" */
10777 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +000010778 return EXIT_SUCCESS; /* bash compat */
10779 }
Denys Vlasenko49117b42016-07-21 14:40:08 +020010780 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010781
10782 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
10783 if (depth == UINT_MAX)
10784 G.flag_break_continue = BC_BREAK;
10785 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +000010786 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010787
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010788 return EXIT_SUCCESS;
10789}
10790
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010791static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010792{
Denis Vlasenko4f504a92008-07-29 19:48:30 +000010793 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
10794 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +000010795}
Denis Vlasenkodadfb492008-07-29 10:16:05 +000010796#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010797
10798#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010799static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010800{
10801 int rc;
10802
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010803 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010804 bb_error_msg("%s: not in a function or sourced script", argv[0]);
10805 return EXIT_FAILURE; /* bash compat */
10806 }
10807
Denys Vlasenko04b46bc2016-10-01 22:28:03 +020010808 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +000010809
10810 /* bash:
10811 * out of range: wraps around at 256, does not error out
10812 * non-numeric param:
10813 * f() { false; return qwe; }; f; echo $?
10814 * bash: return: qwe: numeric argument required <== we do this
10815 * 255 <== we also do this
10816 */
10817 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
10818 return rc;
10819}
10820#endif
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010821
Denys Vlasenko11f2e992017-08-10 16:34:03 +020010822#if ENABLE_HUSH_TIMES
10823static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
10824{
10825 static const uint8_t times_tbl[] ALIGN1 = {
10826 ' ', offsetof(struct tms, tms_utime),
10827 '\n', offsetof(struct tms, tms_stime),
10828 ' ', offsetof(struct tms, tms_cutime),
10829 '\n', offsetof(struct tms, tms_cstime),
10830 0
10831 };
10832 const uint8_t *p;
10833 unsigned clk_tck;
10834 struct tms buf;
10835
10836 clk_tck = bb_clk_tck();
10837
10838 times(&buf);
10839 p = times_tbl;
10840 do {
10841 unsigned sec, frac;
10842 unsigned long t;
10843 t = *(clock_t *)(((char *) &buf) + p[1]);
10844 sec = t / clk_tck;
10845 frac = t % clk_tck;
10846 printf("%um%u.%03us%c",
10847 sec / 60, sec % 60,
10848 (frac * 1000) / clk_tck,
10849 p[0]);
10850 p += 2;
10851 } while (*p);
10852
10853 return EXIT_SUCCESS;
10854}
10855#endif
10856
Denys Vlasenkoa1184af2017-01-10 15:58:02 +010010857#if ENABLE_HUSH_MEMLEAK
10858static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
10859{
10860 void *p;
10861 unsigned long l;
10862
10863# ifdef M_TRIM_THRESHOLD
10864 /* Optional. Reduces probability of false positives */
10865 malloc_trim(0);
10866# endif
10867 /* Crude attempt to find where "free memory" starts,
10868 * sans fragmentation. */
10869 p = malloc(240);
10870 l = (unsigned long)p;
10871 free(p);
10872 p = malloc(3400);
10873 if (l < (unsigned long)p) l = (unsigned long)p;
10874 free(p);
10875
10876
10877# if 0 /* debug */
10878 {
10879 struct mallinfo mi = mallinfo();
10880 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
10881 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
10882 }
10883# endif
10884
10885 if (!G.memleak_value)
10886 G.memleak_value = l;
10887
10888 l -= G.memleak_value;
10889 if ((long)l < 0)
10890 l = 0;
10891 l /= 1024;
10892 if (l > 127)
10893 l = 127;
10894
10895 /* Exitcode is "how many kilobytes we leaked since 1st call" */
10896 return l;
10897}
10898#endif