blob: c0325cf5e416901c684ea9d3547b57d3846e938d [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)
44 * special variables (done: PWD, PPID, RANDOM)
45 * tilde expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000046 * aliases
Denys Vlasenko349ef962010-05-21 15:46:24 +020047 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020050 * make complex ${var%...} constructs support optional
51 * make here documents optional
Mike Frysinger25a6ca02009-03-28 13:59:26 +000052 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020053 * Bash compat TODO:
54 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020055 * reserved words: function select
56 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020057 * process substitution: <(list) and >(list)
58 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020059 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020060 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020063 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020064 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020066 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenkobbecd742010-10-03 17:22:52 +020067 *
68 * Won't do:
69 * In bash, export builtin is special, its arguments are assignments
Denys Vlasenko08218012009-06-03 14:43:56 +020070 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
72 * compare with:
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020076 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020077 * Note2: bash 3.2.33(1) does this only if export word itself
78 * is not quoted:
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
80 * aaa bbb
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
82 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000083 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020084//config:config HUSH
85//config: bool "hush"
86//config: default y
87//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +020088//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +020089//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
90//config: case/esac. Redirections, here documents, $((arithmetic))
91//config: and functions are supported.
92//config:
93//config: It will compile and work on no-mmu systems.
94//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +020095//config: It does not handle select, aliases, tilde expansion,
96//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config:
98//config:config HUSH_BASH_COMPAT
99//config: bool "bash-compatible extensions"
100//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100101//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200102//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200103//config:config HUSH_BRACE_EXPANSION
104//config: bool "Brace expansion"
105//config: default y
106//config: depends on HUSH_BASH_COMPAT
107//config: help
108//config: Enable {abc,def} extension.
109//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200110//config:config HUSH_INTERACTIVE
111//config: bool "Interactive mode"
112//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100113//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200114//config: help
115//config: Enable interactive mode (prompt and command editing).
116//config: Without this, hush simply reads and executes commands
117//config: from stdin just like a shell script from a file.
118//config: No prompt, no PS1/PS2 magic shell variables.
119//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200120//config:config HUSH_SAVEHISTORY
121//config: bool "Save command history to .hush_history"
122//config: default y
123//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200124//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200125//config:config HUSH_JOB
126//config: bool "Job control"
127//config: default y
128//config: depends on HUSH_INTERACTIVE
129//config: help
130//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
131//config: command (not entire shell), fg/bg builtins work. Without this option,
132//config: "cmd &" still works by simply spawning a process and immediately
133//config: prompting for next command (or executing next command in a script),
134//config: but no separate process group is formed.
135//config:
136//config:config HUSH_TICK
Denys Vlasenkof5604222017-01-10 14:58:54 +0100137//config: bool "Support process substitution"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200138//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100139//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200140//config: help
Denys Vlasenkof5604222017-01-10 14:58:54 +0100141//config: Enable `command` and $(command).
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:
143//config:config HUSH_IF
144//config: bool "Support if/then/elif/else/fi"
145//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100146//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200147//config:
148//config:config HUSH_LOOPS
149//config: bool "Support for, while and until loops"
150//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100151//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200152//config:
153//config:config HUSH_CASE
154//config: bool "Support case ... esac statement"
155//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100156//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200157//config: help
Denys Vlasenkof5604222017-01-10 14:58:54 +0100158//config: Enable case ... esac statement. +400 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200159//config:
160//config:config HUSH_FUNCTIONS
161//config: bool "Support funcname() { commands; } syntax"
162//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100163//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200164//config: help
Denys Vlasenkof5604222017-01-10 14:58:54 +0100165//config: Enable support for shell functions. +800 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200166//config:
167//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100168//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200169//config: default y
170//config: depends on HUSH_FUNCTIONS
171//config: help
172//config: Enable support for local variables in functions.
173//config:
174//config:config HUSH_RANDOM_SUPPORT
175//config: bool "Pseudorandom generator and $RANDOM variable"
176//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100177//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200178//config: help
179//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
180//config: Each read of "$RANDOM" will generate a new pseudorandom value.
181//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200182//config:config HUSH_MODE_X
183//config: bool "Support 'hush -x' option and 'set -x' command"
184//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100185//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200186//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200187//config: This instructs hush to print commands before execution.
188//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200189//config:
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100190//config:config HUSH_ECHO
191//config: bool "echo builtin"
192//config: default y
193//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100194//config:
195//config:config HUSH_PRINTF
196//config: bool "printf builtin"
197//config: default y
198//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100199//config:
Denys Vlasenko265062d2017-01-10 15:13:30 +0100200//config:config HUSH_TEST
201//config: bool "test builtin"
202//config: default y
203//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
204//config:
Denys Vlasenkof5604222017-01-10 14:58:54 +0100205//config:config HUSH_HELP
206//config: bool "help builtin"
207//config: default y
208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100209//config:
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100210//config:config HUSH_EXPORT
211//config: bool "export builtin"
212//config: default y
213//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100214//config:
215//config:config HUSH_EXPORT_N
216//config: bool "Support 'export -n' option"
217//config: default y
218//config: depends on HUSH_EXPORT
219//config: help
220//config: export -n unexports variables. It is a bash extension.
221//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100222//config:config HUSH_KILL
Denys Vlasenkof5604222017-01-10 14:58:54 +0100223//config: bool "kill builtin (supports kill %jobspec)"
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100224//config: default y
225//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100226//config:
227//config:config HUSH_WAIT
228//config: bool "wait builtin"
229//config: default y
230//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100231//config:
232//config:config HUSH_TRAP
233//config: bool "trap builtin"
234//config: default y
235//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100236//config:
237//config:config HUSH_TYPE
238//config: bool "type builtin"
239//config: default y
240//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100241//config:
242//config:config HUSH_READ
243//config: bool "read builtin"
244//config: default y
245//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100246//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100247//config:config HUSH_SET
248//config: bool "set builtin"
249//config: default y
250//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100251//config:
252//config:config HUSH_UNSET
253//config: bool "unset builtin"
254//config: default y
255//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkof5604222017-01-10 14:58:54 +0100256//config:
257//config:config HUSH_ULIMIT
258//config: bool "ulimit builtin"
259//config: default y
260//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100261//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100262//config:config HUSH_UMASK
263//config: bool "umask builtin"
264//config: default y
265//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100266//config:
Denys Vlasenko44719692017-01-08 18:44:41 +0100267//config:config HUSH_MEMLEAK
268//config: bool "memleak builtin (debugging)"
269//config: default n
270//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko44719692017-01-08 18:44:41 +0100271//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200272//config:config MSH
273//config: bool "msh (deprecated: aliased to hush)"
274//config: default n
275//config: select HUSH
276//config: help
277//config: msh is deprecated and will be removed, please migrate to hush.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200278
Denys Vlasenko20704f02011-03-23 17:59:27 +0100279//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100280//applet:IF_MSH(APPLET_ODDNAME(msh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
281//applet:IF_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
282//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100283
284//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100285//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
286//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100287//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
288
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100289/* -i (interactive) and -s (read stdin) are also accepted,
290 * but currently do nothing, therefore aren't shown in help.
291 * NOMMU-specific options are not meant to be used by users,
292 * therefore we don't show them either.
293 */
294//usage:#define hush_trivial_usage
Denys Vlasenkof58f7052011-05-12 02:10:33 +0200295//usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100296//usage:#define hush_full_usage "\n\n"
297//usage: "Unix shell interpreter"
298
Denys Vlasenko67047462016-12-22 15:21:58 +0100299#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
300 || defined(__APPLE__) \
301 )
302# include <malloc.h> /* for malloc_trim */
303#endif
304#include <glob.h>
305/* #include <dmalloc.h> */
306#if ENABLE_HUSH_CASE
307# include <fnmatch.h>
308#endif
309#include <sys/utsname.h> /* for setting $HOSTNAME */
310
311#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
312#include "unicode.h"
313#include "shell_common.h"
314#include "math.h"
315#include "match.h"
316#if ENABLE_HUSH_RANDOM_SUPPORT
317# include "random.h"
318#else
319# define CLEAR_RANDOM_T(rnd) ((void)0)
320#endif
321#ifndef F_DUPFD_CLOEXEC
322# define F_DUPFD_CLOEXEC F_DUPFD
323#endif
324#ifndef PIPE_BUF
325# define PIPE_BUF 4096 /* amount of buffering in a pipe */
326#endif
327
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000328
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200329/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000330#define LEAK_HUNTING 0
331#define BUILD_AS_NOMMU 0
332/* Enable/disable sanity checks. Ok to enable in production,
333 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
334 * Keeping 1 for now even in released versions.
335 */
336#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200337/* Slightly bigger (+200 bytes), but faster hush.
338 * So far it only enables a trick with counting SIGCHLDs and forks,
339 * which allows us to do fewer waitpid's.
340 * (we can detect a case where neither forks were done nor SIGCHLDs happened
341 * and therefore waitpid will return the same result as last time)
342 */
343#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200344/* TODO: implement simplified code for users which do not need ${var%...} ops
345 * So far ${var%...} ops are always enabled:
346 */
347#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000348
349
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000350#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000351# undef BB_MMU
352# undef USE_FOR_NOMMU
353# undef USE_FOR_MMU
354# define BB_MMU 0
355# define USE_FOR_NOMMU(...) __VA_ARGS__
356# define USE_FOR_MMU(...)
357#endif
358
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200359#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100360#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000361/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000362# undef CONFIG_FEATURE_SH_STANDALONE
363# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000364# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100365# undef IF_NOT_FEATURE_SH_STANDALONE
366# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000367# define IF_FEATURE_SH_STANDALONE(...)
368# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000369#endif
370
Denis Vlasenko05743d72008-02-10 12:10:08 +0000371#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000372# undef ENABLE_FEATURE_EDITING
373# define ENABLE_FEATURE_EDITING 0
374# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
375# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200376# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
377# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000378#endif
379
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000380/* Do we support ANY keywords? */
381#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000382# define HAS_KEYWORDS 1
383# define IF_HAS_KEYWORDS(...) __VA_ARGS__
384# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000385#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000386# define HAS_KEYWORDS 0
387# define IF_HAS_KEYWORDS(...)
388# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000389#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000390
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000391/* If you comment out one of these below, it will be #defined later
392 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000393#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000394/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000395#define debug_printf_parse(...) do {} while (0)
396#define debug_print_tree(a, b) do {} while (0)
397#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000398#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000399#define debug_printf_jobs(...) do {} while (0)
400#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200401#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000402#define debug_printf_glob(...) do {} while (0)
403#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000404#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000405#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000406
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000407#define ERR_PTR ((void*)(long)1)
408
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100409#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000410
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200411#define _SPECIAL_VARS_STR "_*@$!?#"
412#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
413#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200414#if ENABLE_HUSH_BASH_COMPAT
415/* Support / and // replace ops */
416/* Note that // is stored as \ in "encoded" string representation */
417# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
418# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
419# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
420#else
421# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
422# define VAR_SUBST_OPS "%#:-=+?"
423# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
424#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200425
426#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000427
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200428struct variable;
429
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000430static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
431
432/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000433 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000434 */
435#if !BB_MMU
436typedef struct nommu_save_t {
437 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200438 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000439 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000440 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000441} nommu_save_t;
442#endif
443
Denys Vlasenko9b782552010-09-08 13:33:26 +0200444enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000445 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000446#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000447 RES_IF ,
448 RES_THEN ,
449 RES_ELIF ,
450 RES_ELSE ,
451 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000452#endif
453#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000454 RES_FOR ,
455 RES_WHILE ,
456 RES_UNTIL ,
457 RES_DO ,
458 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000459#endif
460#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000461 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000462#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000463#if ENABLE_HUSH_CASE
464 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200465 /* three pseudo-keywords support contrived "case" syntax: */
466 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
467 RES_MATCH , /* "word)" */
468 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000469 RES_ESAC ,
470#endif
471 RES_XXXX ,
472 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200473};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000474
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000475typedef struct o_string {
476 char *data;
477 int length; /* position where data is appended */
478 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200479 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000480 /* At least some part of the string was inside '' or "",
481 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200482 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000483 smallint has_empty_slot;
484 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
485} o_string;
486enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200487 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
488 EXP_FLAG_GLOB = 0x2,
489 /* Protect newly added chars against globbing
490 * by prepending \ to *, ?, [, \ */
491 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
492};
493enum {
494 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000495 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200496 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200497 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200498 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000499};
500/* Used for initialization: o_string foo = NULL_O_STRING; */
501#define NULL_O_STRING { NULL }
502
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200503#ifndef debug_printf_parse
504static const char *const assignment_flag[] = {
505 "MAYBE_ASSIGNMENT",
506 "DEFINITELY_ASSIGNMENT",
507 "NOT_ASSIGNMENT",
508 "WORD_IS_KEYWORD",
509};
510#endif
511
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000512typedef struct in_str {
513 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000514#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000515 smallint promptmode; /* 0: PS1, 1: PS2 */
516#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200517 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200518 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000519 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000520} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000521
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200522/* The descrip member of this structure is only used to make
523 * debugging output pretty */
524static const struct {
525 int mode;
526 signed char default_fd;
527 char descrip[3];
528} redir_table[] = {
529 { O_RDONLY, 0, "<" },
530 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
531 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
532 { O_CREAT|O_RDWR, 1, "<>" },
533 { O_RDONLY, 0, "<<" },
534/* Should not be needed. Bogus default_fd helps in debugging */
535/* { O_RDONLY, 77, "<<" }, */
536};
537
Eric Andersen25f27032001-04-26 23:22:31 +0000538struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000539 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000540 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000541 int rd_fd; /* fd to redirect */
542 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
543 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000544 smallint rd_type; /* (enum redir_type) */
545 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000546 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200547 * bit 0: do we need to trim leading tabs?
548 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000549 */
Eric Andersen25f27032001-04-26 23:22:31 +0000550};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000551typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200552 REDIRECT_INPUT = 0,
553 REDIRECT_OVERWRITE = 1,
554 REDIRECT_APPEND = 2,
555 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000556 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200557 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000558
559 REDIRFD_CLOSE = -3,
560 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000561 REDIRFD_TO_FILE = -1,
562 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000563
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000564 HEREDOC_SKIPTABS = 1,
565 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000566} redir_type;
567
Eric Andersen25f27032001-04-26 23:22:31 +0000568
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000569struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000570 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000571 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200572 smallint cmd_type; /* CMD_xxx */
573#define CMD_NORMAL 0
574#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200575#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200576/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200577# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000578#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200579#if ENABLE_HUSH_FUNCTIONS
580# define CMD_FUNCDEF 3
581#endif
582
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100583 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200584 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
585 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000586#if !BB_MMU
587 char *group_as_string;
588#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000589#if ENABLE_HUSH_FUNCTIONS
590 struct function *child_func;
591/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200592 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000593 * When we execute "f1() {a;}" cmd, we create new function and clear
594 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200595 * When we execute "f1() {b;}", we notice that f1 exists,
596 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000597 * we put those fields back into cmd->xxx
598 * (struct function has ->parent_cmd ptr to facilitate that).
599 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
600 * Without this trick, loop would execute a;b;b;b;...
601 * instead of correct sequence a;b;a;b;...
602 * When command is freed, it severs the link
603 * (sets ->child_func->parent_cmd to NULL).
604 */
605#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000606 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000607/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
608 * and on execution these are substituted with their values.
609 * Substitution can make _several_ words out of one argv[n]!
610 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000611 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000612 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000613 struct redir_struct *redirects; /* I/O redirections */
614};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000615/* Is there anything in this command at all? */
616#define IS_NULL_CMD(cmd) \
617 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
618
Eric Andersen25f27032001-04-26 23:22:31 +0000619struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000620 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000621 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000622 int alive_cmds; /* number of commands running (not exited) */
623 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000624#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100625 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000626 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000627 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000628#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000629 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000630 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000631 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
632 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000633};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000634typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100635 PIPE_SEQ = 0,
636 PIPE_AND = 1,
637 PIPE_OR = 2,
638 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000639} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000640/* Is there anything in this pipe at all? */
641#define IS_NULL_PIPE(pi) \
642 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000643
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000644/* This holds pointers to the various results of parsing */
645struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000646 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000647 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000648 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000649 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000650 /* last command in pipe (being constructed right now) */
651 struct command *command;
652 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000653 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000654#if !BB_MMU
655 o_string as_string;
656#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000657#if HAS_KEYWORDS
658 smallint ctx_res_w;
659 smallint ctx_inverted; /* "! cmd | cmd" */
660#if ENABLE_HUSH_CASE
661 smallint ctx_dsemicolon; /* ";;" seen */
662#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000663 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
664 int old_flag;
665 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000666 * example: "if pipe1; pipe2; then pipe3; fi"
667 * when we see "if" or "then", we malloc and copy current context,
668 * and make ->stack point to it. then we parse pipeN.
669 * when closing "then" / fi" / whatever is found,
670 * we move list_head into ->stack->command->group,
671 * copy ->stack into current context, and delete ->stack.
672 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000673 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000674 struct parse_context *stack;
675#endif
676};
677
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000678/* On program start, environ points to initial environment.
679 * putenv adds new pointers into it, unsetenv removes them.
680 * Neither of these (de)allocates the strings.
681 * setenv allocates new strings in malloc space and does putenv,
682 * and thus setenv is unusable (leaky) for shell's purposes */
683#define setenv(...) setenv_is_leaky_dont_use()
684struct variable {
685 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000686 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200687#if ENABLE_HUSH_LOCAL
688 unsigned func_nest_level;
689#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000690 int max_len; /* if > 0, name is part of initial env; else name is malloced */
691 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000692 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000693};
694
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000695enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000696 BC_BREAK = 1,
697 BC_CONTINUE = 2,
698};
699
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000700#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000701struct function {
702 struct function *next;
703 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000704 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000705 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200706# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000707 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200708# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000709};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000710#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000711
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000712
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100713/* set -/+o OPT support. (TODO: make it optional)
714 * bash supports the following opts:
715 * allexport off
716 * braceexpand on
717 * emacs on
718 * errexit off
719 * errtrace off
720 * functrace off
721 * hashall on
722 * histexpand off
723 * history on
724 * ignoreeof off
725 * interactive-comments on
726 * keyword off
727 * monitor on
728 * noclobber off
729 * noexec off
730 * noglob off
731 * nolog off
732 * notify off
733 * nounset off
734 * onecmd off
735 * physical off
736 * pipefail off
737 * posix off
738 * privileged off
739 * verbose off
740 * vi off
741 * xtrace off
742 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800743static const char o_opt_strings[] ALIGN1 =
744 "pipefail\0"
745 "noexec\0"
746#if ENABLE_HUSH_MODE_X
747 "xtrace\0"
748#endif
749 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100750enum {
751 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800752 OPT_O_NOEXEC,
753#if ENABLE_HUSH_MODE_X
754 OPT_O_XTRACE,
755#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100756 NUM_OPT_O
757};
758
759
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200760struct FILE_list {
761 struct FILE_list *next;
762 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200763 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200764};
765
766
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000767/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000768/* Sorted roughly by size (smaller offsets == smaller code) */
769struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000770 /* interactive_fd != 0 means we are an interactive shell.
771 * If we are, then saved_tty_pgrp can also be != 0, meaning
772 * that controlling tty is available. With saved_tty_pgrp == 0,
773 * job control still works, but terminal signals
774 * (^C, ^Z, ^Y, ^\) won't work at all, and background
775 * process groups can only be created with "cmd &".
776 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
777 * to give tty to the foreground process group,
778 * and will take it back when the group is stopped (^Z)
779 * or killed (^C).
780 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000781#if ENABLE_HUSH_INTERACTIVE
782 /* 'interactive_fd' is a fd# open to ctty, if we have one
783 * _AND_ if we decided to act interactively */
784 int interactive_fd;
785 const char *PS1;
786 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000787# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000788#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000789# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000790#endif
791#if ENABLE_FEATURE_EDITING
792 line_input_t *line_input_state;
793#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000794 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200795 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000796 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200797#if ENABLE_HUSH_RANDOM_SUPPORT
798 random_t random_gen;
799#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000800#if ENABLE_HUSH_JOB
801 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100802 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000803 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000804 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400805# define G_saved_tty_pgrp (G.saved_tty_pgrp)
806#else
807# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000808#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100809 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100810#if ENABLE_HUSH_MODE_X
811# define G_x_mode (G.o_opt[OPT_O_XTRACE])
812#else
813# define G_x_mode 0
814#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000815 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000816#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000817 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000818#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000819#if ENABLE_HUSH_FUNCTIONS
820 /* 0: outside of a function (or sourced file)
821 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000822 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000823 */
824 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200825# define G_flag_return_in_progress (G.flag_return_in_progress)
826#else
827# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000828#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000829 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000830 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000831 smalluint last_exitcode;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100832#if ENABLE_HUSH_SET
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000833 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000834 smalluint global_args_malloced;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100835# define G_global_args_malloced (G.global_args_malloced)
836#else
837# define G_global_args_malloced 0
838#endif
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000839 /* how many non-NULL argv's we have. NB: $# + 1 */
840 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000841 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000842#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000843 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000844#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000845#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000846 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000847 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000848#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000849 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000850 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200851 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200852 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000853#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000854 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200855# if ENABLE_HUSH_LOCAL
856 struct variable **shadowed_vars_pp;
857 unsigned func_nest_level;
858# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000859#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000860 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200861#if ENABLE_HUSH_FAST
862 unsigned count_SIGCHLD;
863 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200864 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200865#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200866 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200867 /* Which signals have non-DFL handler (even with no traps set)?
868 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200869 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200870 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200871 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200872 * Other than these two times, never modified.
873 */
874 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200875#if ENABLE_HUSH_JOB
876 unsigned fatal_sig_mask;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +0100877# define G_fatal_sig_mask (G.fatal_sig_mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200878#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200879# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200880#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100881#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000882 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100883# define G_traps G.traps
884#else
885# define G_traps ((char**)NULL)
886#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200887 sigset_t pending_set;
Denys Vlasenko44719692017-01-08 18:44:41 +0100888#if ENABLE_HUSH_MEMLEAK
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000889 unsigned long memleak_value;
Denys Vlasenko44719692017-01-08 18:44:41 +0100890#endif
891#if HUSH_DEBUG
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000892 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000893#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200894 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200895#if ENABLE_FEATURE_EDITING
896 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
897#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000898};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000899#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000900/* Not #defining name to G.name - this quickly gets unwieldy
901 * (too many defines). Also, I actually prefer to see when a variable
902 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000903#define INIT_G() do { \
904 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200905 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
906 sigfillset(&G.sa.sa_mask); \
907 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000908} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000909
910
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000911/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200912static int builtin_cd(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100913#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200914static int builtin_echo(char **argv) FAST_FUNC;
Denys Vlasenko1cc68042017-01-09 17:10:04 +0100915#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200916static int builtin_eval(char **argv) FAST_FUNC;
917static int builtin_exec(char **argv) FAST_FUNC;
918static int builtin_exit(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100919#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200920static int builtin_export(char **argv) FAST_FUNC;
Denys Vlasenko6ec76d82017-01-08 18:40:41 +0100921#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000922#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200923static int builtin_fg_bg(char **argv) FAST_FUNC;
924static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000925#endif
926#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200927static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000928#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200929#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200930static int builtin_history(char **argv) FAST_FUNC;
931#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200932#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200933static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200934#endif
Denys Vlasenko44719692017-01-08 18:44:41 +0100935#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200936static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000937#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +0100938#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400939static int builtin_printf(char **argv) FAST_FUNC;
940#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200941static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100942#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200943static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100944#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100945#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200946static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100947#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200948static int builtin_shift(char **argv) FAST_FUNC;
949static int builtin_source(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +0100950#if ENABLE_HUSH_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200951static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko265062d2017-01-10 15:13:30 +0100952#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100953#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200954static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100955#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +0100956#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200957static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +0100958#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200959static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100960#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200961static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100962#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100963#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200964static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100965#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +0100966#if ENABLE_HUSH_KILL
967static int builtin_kill(char **argv) FAST_FUNC;
968#endif
969#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200970static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +0100971#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000972#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200973static int builtin_break(char **argv) FAST_FUNC;
974static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000975#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000976#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200977static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000978#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000979
980/* Table of built-in functions. They can be forked or not, depending on
981 * context: within pipes, they fork. As simple commands, they do not.
982 * When used in non-forking context, they can change global variables
983 * in the parent shell process. If forked, of course they cannot.
984 * For example, 'unset foo | whatever' will parse and run, but foo will
985 * still be set at the end. */
986struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100987 const char *b_cmd;
988 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000989#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100990 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200991# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000992#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200993# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000994#endif
995};
996
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200997static const struct built_in_command bltins1[] = {
998 BLTIN("." , builtin_source , "Run commands in a file"),
999 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001000#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001001 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001002#endif
1003#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001004 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001005#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001006 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001007#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001008 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001009#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001010 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1011 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1012 BLTIN("exit" , builtin_exit , "Exit"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001013#if ENABLE_HUSH_EXPORT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001014 BLTIN("export" , builtin_export , "Set environment variables"),
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01001015#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001016#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001017 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001018#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001019#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001020 BLTIN("help" , builtin_help , NULL),
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 +02001023 BLTIN("history" , builtin_history , "Show command history"),
1024#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001025#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001026 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001027#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001028#if ENABLE_HUSH_KILL
1029 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1030#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001031#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001032 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001033#endif
Denys Vlasenko44719692017-01-08 18:44:41 +01001034#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001035 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001036#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001037#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001038 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001039#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001040#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001041 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001042#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001043#if ENABLE_HUSH_SET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001044 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001045#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001046 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001047#if ENABLE_HUSH_BASH_COMPAT
1048 BLTIN("source" , builtin_source , "Run commands in a file"),
1049#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001050#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001051 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001052#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001053 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001054#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001055 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001056#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001057#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001058 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001059#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001060#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001061 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001062#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001063#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001064 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001065#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001066#if ENABLE_HUSH_WAIT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001067 BLTIN("wait" , builtin_wait , "Wait for process"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001068#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001069};
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001070static const struct built_in_command bltins2[] = {
Denys Vlasenko265062d2017-01-10 15:13:30 +01001071#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001072 BLTIN("[" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001073#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001074#if ENABLE_HUSH_ECHO
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001075 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1cc68042017-01-09 17:10:04 +01001076#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001077#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001078 BLTIN("printf" , builtin_printf , NULL),
1079#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001080 BLTIN("pwd" , builtin_pwd , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001081#if ENABLE_HUSH_TEST
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001082 BLTIN("test" , builtin_test , NULL),
Denys Vlasenko265062d2017-01-10 15:13:30 +01001083#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001084};
1085
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001086
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001087/* Debug printouts.
1088 */
1089#if HUSH_DEBUG
1090/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001091# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001092# define debug_enter() (G.debug_indent++)
1093# define debug_leave() (G.debug_indent--)
1094#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001095# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001096# define debug_enter() ((void)0)
1097# define debug_leave() ((void)0)
1098#endif
1099
1100#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001101# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001102#endif
1103
1104#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001105# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001106#endif
1107
1108#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001109#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001110#endif
1111
1112#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001113# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001114#endif
1115
1116#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001117# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001118# define DEBUG_JOBS 1
1119#else
1120# define DEBUG_JOBS 0
1121#endif
1122
1123#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001124# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001125# define DEBUG_EXPAND 1
1126#else
1127# define DEBUG_EXPAND 0
1128#endif
1129
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001130#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001131# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001132#endif
1133
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001134#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001135# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001136# define DEBUG_GLOB 1
1137#else
1138# define DEBUG_GLOB 0
1139#endif
1140
1141#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001142# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001143#endif
1144
1145#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001146# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001147#endif
1148
1149#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001150# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001151# define DEBUG_CLEAN 1
1152#else
1153# define DEBUG_CLEAN 0
1154#endif
1155
1156#if DEBUG_EXPAND
1157static void debug_print_strings(const char *prefix, char **vv)
1158{
1159 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001160 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001161 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001162 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001163}
1164#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001165# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001166#endif
1167
1168
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001169/* Leak hunting. Use hush_leaktool.sh for post-processing.
1170 */
1171#if LEAK_HUNTING
1172static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001173{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001174 void *ptr = xmalloc((size + 0xff) & ~0xff);
1175 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1176 return ptr;
1177}
1178static void *xxrealloc(int lineno, void *ptr, size_t size)
1179{
1180 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1181 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1182 return ptr;
1183}
1184static char *xxstrdup(int lineno, const char *str)
1185{
1186 char *ptr = xstrdup(str);
1187 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1188 return ptr;
1189}
1190static void xxfree(void *ptr)
1191{
1192 fdprintf(2, "free %p\n", ptr);
1193 free(ptr);
1194}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001195# define xmalloc(s) xxmalloc(__LINE__, s)
1196# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1197# define xstrdup(s) xxstrdup(__LINE__, s)
1198# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001199#endif
1200
1201
1202/* Syntax and runtime errors. They always abort scripts.
1203 * In interactive use they usually discard unparsed and/or unexecuted commands
1204 * and return to the prompt.
1205 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1206 */
1207#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001208# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001209# define syntax_error(lineno, msg) syntax_error(msg)
1210# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1211# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1212# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1213# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001214#endif
1215
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001216static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001217{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001218 va_list p;
1219
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001220#if HUSH_DEBUG >= 2
1221 bb_error_msg("hush.c:%u", lineno);
1222#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001223 va_start(p, fmt);
1224 bb_verror_msg(fmt, p, NULL);
1225 va_end(p);
1226 if (!G_interactive_fd)
1227 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001228}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001229
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001230static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001231{
1232 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001233 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001234 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001235 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001236}
1237
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001238static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001239{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001240 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001241}
1242
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001243static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001244{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001245 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001246}
1247
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001248static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001249{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001250 char msg[2] = { ch, '\0' };
1251 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001252}
1253
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001254static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001255{
1256 char msg[2];
1257 msg[0] = ch;
1258 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001259#if HUSH_DEBUG >= 2
1260 bb_error_msg("hush.c:%u", lineno);
1261#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001262 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001263}
1264
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001265#if HUSH_DEBUG < 2
1266# undef die_if_script
1267# undef syntax_error
1268# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001269# undef syntax_error_unterm_ch
1270# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001271# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001272#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001273# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001274# define syntax_error(msg) syntax_error(__LINE__, msg)
1275# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1276# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1277# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1278# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001279#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001280
Denis Vlasenko552433b2009-04-04 19:29:21 +00001281
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001282#if ENABLE_HUSH_INTERACTIVE
1283static void cmdedit_update_prompt(void);
1284#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001285# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001286#endif
1287
1288
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001289/* Utility functions
1290 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001291/* Replace each \x with x in place, return ptr past NUL. */
1292static char *unbackslash(char *src)
1293{
Denys Vlasenko71885402009-09-24 01:44:13 +02001294 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001295 while (1) {
1296 if (*src == '\\')
1297 src++;
1298 if ((*dst++ = *src++) == '\0')
1299 break;
1300 }
1301 return dst;
1302}
1303
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001304static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001305{
1306 int i;
1307 unsigned count1;
1308 unsigned count2;
1309 char **v;
1310
1311 v = strings;
1312 count1 = 0;
1313 if (v) {
1314 while (*v) {
1315 count1++;
1316 v++;
1317 }
1318 }
1319 count2 = 0;
1320 v = add;
1321 while (*v) {
1322 count2++;
1323 v++;
1324 }
1325 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1326 v[count1 + count2] = NULL;
1327 i = count2;
1328 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001329 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001330 return v;
1331}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001332#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001333static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1334{
1335 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1336 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1337 return ptr;
1338}
1339#define add_strings_to_strings(strings, add, need_to_dup) \
1340 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1341#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001342
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001343/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001344static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001345{
1346 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001347 v[0] = add;
1348 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001349 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001350}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001351#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001352static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1353{
1354 char **ptr = add_string_to_strings(strings, add);
1355 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1356 return ptr;
1357}
1358#define add_string_to_strings(strings, add) \
1359 xx_add_string_to_strings(__LINE__, strings, add)
1360#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001361
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001362static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001363{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001364 char **v;
1365
1366 if (!strings)
1367 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001368 v = strings;
1369 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001370 free(*v);
1371 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001372 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001373 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001374}
1375
Denis Vlasenko76d50412008-06-10 16:19:39 +00001376
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001377static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1378{
1379 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1380 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1381 if (newfd < 0) {
1382 /* fd was not open? */
1383 if (errno == EBADF)
1384 return fd;
1385 xfunc_die();
1386 }
1387 close(fd);
1388 return newfd;
1389}
1390
1391
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001392/* Manipulating the list of open FILEs */
1393static FILE *remember_FILE(FILE *fp)
1394{
1395 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001396 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001397 n->next = G.FILE_list;
1398 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001399 n->fp = fp;
1400 n->fd = fileno(fp);
1401 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001402 }
1403 return fp;
1404}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001405static void fclose_and_forget(FILE *fp)
1406{
1407 struct FILE_list **pp = &G.FILE_list;
1408 while (*pp) {
1409 struct FILE_list *cur = *pp;
1410 if (cur->fp == fp) {
1411 *pp = cur->next;
1412 free(cur);
1413 break;
1414 }
1415 pp = &cur->next;
1416 }
1417 fclose(fp);
1418}
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001419static int save_FILEs_on_redirect(int fd)
1420{
1421 struct FILE_list *fl = G.FILE_list;
1422 while (fl) {
1423 if (fd == fl->fd) {
1424 /* We use it only on script files, they are all CLOEXEC */
1425 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1426 return 1;
1427 }
1428 fl = fl->next;
1429 }
1430 return 0;
1431}
1432static void restore_redirected_FILEs(void)
1433{
1434 struct FILE_list *fl = G.FILE_list;
1435 while (fl) {
1436 int should_be = fileno(fl->fp);
1437 if (fl->fd != should_be) {
1438 xmove_fd(fl->fd, should_be);
1439 fl->fd = should_be;
1440 }
1441 fl = fl->next;
1442 }
1443}
1444#if ENABLE_FEATURE_SH_STANDALONE
1445static void close_all_FILE_list(void)
1446{
1447 struct FILE_list *fl = G.FILE_list;
1448 while (fl) {
1449 /* fclose would also free FILE object.
1450 * It is disastrous if we share memory with a vforked parent.
1451 * I'm not sure we never come here after vfork.
1452 * Therefore just close fd, nothing more.
1453 */
1454 /*fclose(fl->fp); - unsafe */
1455 close(fl->fd);
1456 fl = fl->next;
1457 }
1458}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001459#endif
1460
1461
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001462/* Helpers for setting new $n and restoring them back
1463 */
1464typedef struct save_arg_t {
1465 char *sv_argv0;
1466 char **sv_g_argv;
1467 int sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001468 IF_HUSH_SET(smallint sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001469} save_arg_t;
1470
1471static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1472{
1473 int n;
1474
1475 sv->sv_argv0 = argv[0];
1476 sv->sv_g_argv = G.global_argv;
1477 sv->sv_g_argc = G.global_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001478 IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001479
1480 argv[0] = G.global_argv[0]; /* retain $0 */
1481 G.global_argv = argv;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001482 IF_HUSH_SET(G.global_args_malloced = 0;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001483
1484 n = 1;
1485 while (*++argv)
1486 n++;
1487 G.global_argc = n;
1488}
1489
1490static void restore_G_args(save_arg_t *sv, char **argv)
1491{
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001492#if ENABLE_HUSH_SET
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001493 if (G.global_args_malloced) {
1494 /* someone ran "set -- arg1 arg2 ...", undo */
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001495 char **pp = G.global_argv;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001496 while (*++pp) /* note: does not free $0 */
1497 free(*pp);
1498 free(G.global_argv);
1499 }
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001500#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001501 argv[0] = sv->sv_argv0;
1502 G.global_argv = sv->sv_g_argv;
1503 G.global_argc = sv->sv_g_argc;
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01001504 IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001505}
1506
1507
Denis Vlasenkod5762932009-03-31 11:22:57 +00001508/* Basic theory of signal handling in shell
1509 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001510 * This does not describe what hush does, rather, it is current understanding
1511 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001512 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1513 *
1514 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1515 * is finished or backgrounded. It is the same in interactive and
1516 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001517 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001518 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001519 * backgrounds (i.e. stops) or kills all members of currently running
1520 * pipe.
1521 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001522 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001523 * or by SIGINT in interactive shell.
1524 *
1525 * Trap handlers will execute even within trap handlers. (right?)
1526 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001527 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1528 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001529 *
1530 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001531 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001532 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001533 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001534 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001535 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001536 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001537 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001538 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001539 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001540 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001541 *
1542 * SIGQUIT: ignore
1543 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001544 * SIGHUP (interactive):
1545 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001546 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001547 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1548 * that all pipe members are stopped. Try this in bash:
1549 * while :; do :; done - ^Z does not background it
1550 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001551 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001552 * of the command line, show prompt. NB: ^C does not send SIGINT
1553 * to interactive shell while shell is waiting for a pipe,
1554 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001555 * Example 1: this waits 5 sec, but does not execute ls:
1556 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1557 * Example 2: this does not wait and does not execute ls:
1558 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1559 * Example 3: this does not wait 5 sec, but executes ls:
1560 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001561 * Example 4: this does not wait and does not execute ls:
1562 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001563 *
1564 * (What happens to signals which are IGN on shell start?)
1565 * (What happens with signal mask on shell start?)
1566 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001567 * Old implementation
1568 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001569 * We use in-kernel pending signal mask to determine which signals were sent.
1570 * We block all signals which we don't want to take action immediately,
1571 * i.e. we block all signals which need to have special handling as described
1572 * above, and all signals which have traps set.
1573 * After each pipe execution, we extract any pending signals via sigtimedwait()
1574 * and act on them.
1575 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001576 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001577 * sigset_t blocked_set: current blocked signal set
1578 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001579 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001580 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001581 * "trap 'cmd' SIGxxx":
1582 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001583 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001584 * unblock signals with special interactive handling
1585 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001586 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001587 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001588 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001589 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001590 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001591 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001592 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001593 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001594 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001595 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001596 * Standard says "When a subshell is entered, traps that are not being ignored
1597 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001598 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001599 *
1600 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001601 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001602 * masked signals are not visible!
1603 *
1604 * New implementation
1605 * ==================
1606 * We record each signal we are interested in by installing signal handler
1607 * for them - a bit like emulating kernel pending signal mask in userspace.
1608 * We are interested in: signals which need to have special handling
1609 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001610 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001611 * After each pipe execution, we extract any pending signals
1612 * and act on them.
1613 *
1614 * unsigned special_sig_mask: a mask of shell-special signals.
1615 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1616 * char *traps[sig] if trap for sig is set (even if it's '').
1617 * sigset_t pending_set: set of sigs we received.
1618 *
1619 * "trap - SIGxxx":
1620 * if sig is in special_sig_mask, set handler back to:
1621 * record_pending_signo, or to IGN if it's a tty stop signal
1622 * if sig is in fatal_sig_mask, set handler back to sigexit.
1623 * else: set handler back to SIG_DFL
1624 * "trap 'cmd' SIGxxx":
1625 * set handler to record_pending_signo.
1626 * "trap '' SIGxxx":
1627 * set handler to SIG_IGN.
1628 * after [v]fork, if we plan to be a shell:
1629 * set signals with special interactive handling to SIG_DFL
1630 * (because child shell is not interactive),
1631 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1632 * after [v]fork, if we plan to exec:
1633 * POSIX says fork clears pending signal mask in child - no need to clear it.
1634 *
1635 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1636 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1637 *
1638 * Note (compat):
1639 * Standard says "When a subshell is entered, traps that are not being ignored
1640 * are set to the default actions". bash interprets it so that traps which
1641 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001642 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001643enum {
1644 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001645 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001646 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001647 | (1 << SIGHUP)
1648 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001649 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001650#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001651 | (1 << SIGTTIN)
1652 | (1 << SIGTTOU)
1653 | (1 << SIGTSTP)
1654#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001655 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001656};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001657
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001658static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001659{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001660 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001661#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001662 if (sig == SIGCHLD) {
1663 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001664//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 +02001665 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001666#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001667}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001668
Denys Vlasenko0806e402011-05-12 23:06:20 +02001669static sighandler_t install_sighandler(int sig, sighandler_t handler)
1670{
1671 struct sigaction old_sa;
1672
1673 /* We could use signal() to install handlers... almost:
1674 * except that we need to mask ALL signals while handlers run.
1675 * I saw signal nesting in strace, race window isn't small.
1676 * SA_RESTART is also needed, but in Linux, signal()
1677 * sets SA_RESTART too.
1678 */
1679 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1680 /* sigfillset(&G.sa.sa_mask); - already done */
1681 /* G.sa.sa_flags = SA_RESTART; - already done */
1682 G.sa.sa_handler = handler;
1683 sigaction(sig, &G.sa, &old_sa);
1684 return old_sa.sa_handler;
1685}
1686
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001687static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001688
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001689static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001690static void restore_ttypgrp_and__exit(void)
1691{
1692 /* xfunc has failed! die die die */
1693 /* no EXIT traps, this is an escape hatch! */
1694 G.exiting = 1;
1695 hush_exit(xfunc_error_retval);
1696}
1697
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001698#if ENABLE_HUSH_JOB
1699
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001700/* Needed only on some libc:
1701 * It was observed that on exit(), fgetc'ed buffered data
1702 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1703 * With the net effect that even after fork(), not vfork(),
1704 * exit() in NOEXECed applet in "sh SCRIPT":
1705 * noexec_applet_here
1706 * echo END_OF_SCRIPT
1707 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1708 * This makes "echo END_OF_SCRIPT" executed twice.
1709 * Similar problems can be seen with die_if_script() -> xfunc_die()
1710 * and in `cmd` handling.
1711 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1712 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001713static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001714static void fflush_and__exit(void)
1715{
1716 fflush_all();
1717 _exit(xfunc_error_retval);
1718}
1719
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001720/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001721# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001722/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001723# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001724
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001725/* Restores tty foreground process group, and exits.
1726 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001727 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001728 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001729 * We also call it if xfunc is exiting.
1730 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001731static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001732static void sigexit(int sig)
1733{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001734 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001735 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001736 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1737 /* Disable all signals: job control, SIGPIPE, etc.
1738 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1739 */
1740 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001741 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001742 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001743
1744 /* Not a signal, just exit */
1745 if (sig <= 0)
1746 _exit(- sig);
1747
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001748 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001749}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001750#else
1751
Denys Vlasenko8391c482010-05-22 17:50:43 +02001752# define disable_restore_tty_pgrp_on_exit() ((void)0)
1753# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001754
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001755#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001756
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001757static sighandler_t pick_sighandler(unsigned sig)
1758{
1759 sighandler_t handler = SIG_DFL;
1760 if (sig < sizeof(unsigned)*8) {
1761 unsigned sigmask = (1 << sig);
1762
1763#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001764 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001765 if (G_fatal_sig_mask & sigmask)
1766 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001767 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001768#endif
1769 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001770 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001771 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001772 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001773 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001774 * in an endless loop when we try to do some
1775 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001776 */
1777 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1778 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001779 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001780 }
1781 return handler;
1782}
1783
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001784/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001785static void hush_exit(int exitcode)
1786{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001787#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1788 save_history(G.line_input_state);
1789#endif
1790
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001791 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001792 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001793 char *argv[3];
1794 /* argv[0] is unused */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001795 argv[1] = G_traps[0];
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001796 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001797 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001798 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001799 * "trap" will still show it, if executed
1800 * in the handler */
1801 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001802 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001803
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001804#if ENABLE_FEATURE_CLEAN_UP
1805 {
1806 struct variable *cur_var;
1807 if (G.cwd != bb_msg_unknown)
1808 free((char*)G.cwd);
1809 cur_var = G.top_var;
1810 while (cur_var) {
1811 struct variable *tmp = cur_var;
1812 if (!cur_var->max_len)
1813 free(cur_var->varstr);
1814 cur_var = cur_var->next;
1815 free(tmp);
1816 }
1817 }
1818#endif
1819
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001820 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001821#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001822 sigexit(- (exitcode & 0xff));
1823#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001824 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001825#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001826}
1827
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001828
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001829//TODO: return a mask of ALL handled sigs?
1830static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001831{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001832 int last_sig = 0;
1833
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001834 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001835 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001836
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001837 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001838 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001839 sig = 0;
1840 do {
1841 sig++;
1842 if (sigismember(&G.pending_set, sig)) {
1843 sigdelset(&G.pending_set, sig);
1844 goto got_sig;
1845 }
1846 } while (sig < NSIG);
1847 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001848 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001849 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001850 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001851 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001852 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001853 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001854 char *argv[3];
1855 /* argv[0] is unused */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001856 argv[1] = G_traps[sig];
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001857 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001858 save_rcode = G.last_exitcode;
1859 builtin_eval(argv);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01001860//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001861 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001862 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001863 } /* else: "" trap, ignoring signal */
1864 continue;
1865 }
1866 /* not a trap: special action */
1867 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001868 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001869 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001870 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001871 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001872 break;
1873#if ENABLE_HUSH_JOB
1874 case SIGHUP: {
1875 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001876 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001877 /* bash is observed to signal whole process groups,
1878 * not individual processes */
1879 for (job = G.job_list; job; job = job->next) {
1880 if (job->pgrp <= 0)
1881 continue;
1882 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1883 if (kill(- job->pgrp, SIGHUP) == 0)
1884 kill(- job->pgrp, SIGCONT);
1885 }
1886 sigexit(SIGHUP);
1887 }
1888#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001889#if ENABLE_HUSH_FAST
1890 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001891 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001892 G.count_SIGCHLD++;
1893//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1894 /* Note:
1895 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1896 * This simplifies wait builtin a bit.
1897 */
1898 break;
1899#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001900 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001901 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001902 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001903 /* Note:
1904 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1905 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001906 * in interactive shell, because TERM is ignored.
1907 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001908 break;
1909 }
1910 }
1911 return last_sig;
1912}
1913
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001914
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001915static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001916{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001917 if (force || G.cwd == NULL) {
1918 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1919 * we must not try to free(bb_msg_unknown) */
1920 if (G.cwd == bb_msg_unknown)
1921 G.cwd = NULL;
1922 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1923 if (!G.cwd)
1924 G.cwd = bb_msg_unknown;
1925 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001926 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001927}
1928
Denis Vlasenko83506862007-11-23 13:11:42 +00001929
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001930/*
1931 * Shell and environment variable support
1932 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001933static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001934{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001935 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001936 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001937
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001938 pp = &G.top_var;
1939 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001940 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001941 return pp;
1942 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001943 }
1944 return NULL;
1945}
1946
Denys Vlasenko03dad222010-01-12 23:29:57 +01001947static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001948{
Denys Vlasenko29082232010-07-16 13:52:32 +02001949 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001950 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001951
1952 if (G.expanded_assignments) {
1953 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001954 while (*cpp) {
1955 char *cp = *cpp;
1956 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1957 return cp + len + 1;
1958 cpp++;
1959 }
1960 }
1961
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001962 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001963 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001964 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001965
Denys Vlasenkodea47882009-10-09 15:40:49 +02001966 if (strcmp(name, "PPID") == 0)
1967 return utoa(G.root_ppid);
1968 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001969#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001970 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001971 return utoa(next_random(&G.random_gen));
1972#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001973 return NULL;
1974}
1975
1976/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001977 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001978 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001979 * 0: do not change export flag
1980 * (if creating new variable, flag will be 0)
1981 * 1: set export flag and putenv the variable
1982 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001983 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001984 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001985#if !BB_MMU && ENABLE_HUSH_LOCAL
1986/* all params are used */
1987#elif BB_MMU && ENABLE_HUSH_LOCAL
1988#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1989 set_local_var(str, flg_export, local_lvl)
1990#elif BB_MMU && !ENABLE_HUSH_LOCAL
1991#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001992 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001993#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1994#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1995 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001996#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001997static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001998{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001999 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002000 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002001 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00002002 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002003 int name_len;
2004
Denis Vlasenko950bd722009-04-21 11:23:56 +00002005 eq_sign = strchr(str, '=');
2006 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002007 free(str);
2008 return -1;
2009 }
2010
Denis Vlasenko950bd722009-04-21 11:23:56 +00002011 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002012 var_pp = &G.top_var;
2013 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002014 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002015 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002016 continue;
2017 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002018
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002019 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002020 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002021#if !BB_MMU
2022 if (!flg_read_only)
2023#endif
2024 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002025 free(str);
2026 return -1;
2027 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002028 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002029 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2030 *eq_sign = '\0';
2031 unsetenv(str);
2032 *eq_sign = '=';
2033 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002034#if ENABLE_HUSH_LOCAL
2035 if (cur->func_nest_level < local_lvl) {
2036 /* New variable is declared as local,
2037 * and existing one is global, or local
2038 * from enclosing function.
2039 * Remove and save old one: */
2040 *var_pp = cur->next;
2041 cur->next = *G.shadowed_vars_pp;
2042 *G.shadowed_vars_pp = cur;
2043 /* bash 3.2.33(1) and exported vars:
2044 * # export z=z
2045 * # f() { local z=a; env | grep ^z; }
2046 * # f
2047 * z=a
2048 * # env | grep ^z
2049 * z=z
2050 */
2051 if (cur->flg_export)
2052 flg_export = 1;
2053 break;
2054 }
2055#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00002056 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002057 free_and_exp:
2058 free(str);
2059 goto exp;
2060 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002061 if (cur->max_len != 0) {
2062 if (cur->max_len >= strlen(str)) {
2063 /* This one is from startup env, reuse space */
2064 strcpy(cur->varstr, str);
2065 goto free_and_exp;
2066 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002067 /* Can't reuse */
2068 cur->max_len = 0;
2069 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002070 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002071 /* max_len == 0 signifies "malloced" var, which we can
2072 * (and have to) free. But we can't free(cur->varstr) here:
2073 * if cur->flg_export is 1, it is in the environment.
2074 * We should either unsetenv+free, or wait until putenv,
2075 * then putenv(new)+free(old).
2076 */
2077 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002078 goto set_str_and_exp;
2079 }
2080
Denys Vlasenko295fef82009-06-03 12:47:26 +02002081 /* Not found - create new variable struct */
2082 cur = xzalloc(sizeof(*cur));
2083#if ENABLE_HUSH_LOCAL
2084 cur->func_nest_level = local_lvl;
2085#endif
2086 cur->next = *var_pp;
2087 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002088
2089 set_str_and_exp:
2090 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002091#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002092 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002093#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002094 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00002095 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002096 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002097 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2098 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002099 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002100 if (flg_export == -1) {
2101 cur->flg_export = 0;
2102 /* unsetenv was already done */
2103 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002104 int i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002105 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002106 i = putenv(cur->varstr);
2107 /* only now we can free old exported malloced string */
2108 free(free_me);
2109 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002110 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002111 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002112 free(free_me);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002113 return 0;
2114}
2115
Denys Vlasenko6db47842009-09-05 20:15:17 +02002116/* Used at startup and after each cd */
2117static void set_pwd_var(int exp)
2118{
2119 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2120 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2121}
2122
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002123static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002124{
2125 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002126 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002127
2128 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002129 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002130 var_pp = &G.top_var;
2131 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002132 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2133 if (cur->flg_read_only) {
2134 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002135 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002136 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002137 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002138 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2139 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002140 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2141 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002142 if (!cur->max_len)
2143 free(cur->varstr);
2144 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002145 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002146 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002147 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002148 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002149 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002150}
2151
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002152#if ENABLE_HUSH_UNSET
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002153static int unset_local_var(const char *name)
2154{
2155 return unset_local_var_len(name, strlen(name));
2156}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002157#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002158
2159static void unset_vars(char **strings)
2160{
2161 char **v;
2162
2163 if (!strings)
2164 return;
2165 v = strings;
2166 while (*v) {
2167 const char *eq = strchrnul(*v, '=');
2168 unset_local_var_len(*v, (int)(eq - *v));
2169 v++;
2170 }
2171 free(strings);
2172}
2173
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002174#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_BASH_COMPAT || ENABLE_HUSH_READ
Denys Vlasenko03dad222010-01-12 23:29:57 +01002175static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002176{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002177 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01002178 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002179}
Denys Vlasenkocc2fd5a2017-01-09 06:19:55 +01002180#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002181
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002182
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002183/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002184 * Helpers for "var1=val1 var2=val2 cmd" feature
2185 */
2186static void add_vars(struct variable *var)
2187{
2188 struct variable *next;
2189
2190 while (var) {
2191 next = var->next;
2192 var->next = G.top_var;
2193 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002194 if (var->flg_export) {
2195 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002196 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002197 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002198 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002199 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002200 var = next;
2201 }
2202}
2203
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002204static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002205{
2206 char **s;
2207 struct variable *old = NULL;
2208
2209 if (!strings)
2210 return old;
2211 s = strings;
2212 while (*s) {
2213 struct variable *var_p;
2214 struct variable **var_pp;
2215 char *eq;
2216
2217 eq = strchr(*s, '=');
2218 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002219 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002220 if (var_pp) {
2221 /* Remove variable from global linked list */
2222 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002223 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002224 *var_pp = var_p->next;
2225 /* Add it to returned list */
2226 var_p->next = old;
2227 old = var_p;
2228 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002229 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002230 }
2231 s++;
2232 }
2233 return old;
2234}
2235
2236
2237/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002238 * Unicode helper
2239 */
2240static void reinit_unicode_for_hush(void)
2241{
2242 /* Unicode support should be activated even if LANG is set
2243 * _during_ shell execution, not only if it was set when
2244 * shell was started. Therefore, re-check LANG every time:
2245 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002246 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2247 || ENABLE_UNICODE_USING_LOCALE
2248 ) {
2249 const char *s = get_local_var_value("LC_ALL");
2250 if (!s) s = get_local_var_value("LC_CTYPE");
2251 if (!s) s = get_local_var_value("LANG");
2252 reinit_unicode(s);
2253 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002254}
2255
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002256/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002257 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002258 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002259
2260#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002261/* To test correct lineedit/interactive behavior, type from command line:
2262 * echo $P\
2263 * \
2264 * AT\
2265 * H\
2266 * \
2267 * It excercises a lot of corner cases.
2268 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002269static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002270{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002271 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002272 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002273 if (G.PS1 == NULL)
2274 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002275 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002276 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002277 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002278 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002279 if (G.PS2 == NULL)
2280 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002281}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002282static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002283{
2284 const char *prompt_str;
2285 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002286 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2287 /* Set up the prompt */
2288 if (promptmode == 0) { /* PS1 */
2289 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002290 /* bash uses $PWD value, even if it is set by user.
2291 * It uses current dir only if PWD is unset.
2292 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002293 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002294 prompt_str = G.PS1;
2295 } else
2296 prompt_str = G.PS2;
2297 } else
2298 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002299 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002300 return prompt_str;
2301}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002302static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002303{
2304 int r;
2305 const char *prompt_str;
2306
2307 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002308# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002309 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002310 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002311 if (G.flag_SIGINT) {
2312 /* There was ^C'ed, make it look prettier: */
2313 bb_putchar('\n');
2314 G.flag_SIGINT = 0;
2315 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002316 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002317 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002318 r = read_line_input(G.line_input_state, prompt_str,
2319 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2320 /*timeout*/ -1
2321 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002322 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2323 if (r == 0) {
2324 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002325 raise(SIGINT);
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002326 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002327 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002328 if (r != 0 && !G.flag_SIGINT)
2329 break;
2330 /* ^C or SIGINT: repeat */
2331 G.last_exitcode = 128 + SIGINT;
2332 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002333 if (r < 0) {
2334 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002335 i->p = NULL;
2336 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002337 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002338 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002339 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002340 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002341# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002342 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002343 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002344 if (i->last_char == '\0' || i->last_char == '\n') {
2345 /* Why check_and_run_traps here? Try this interactively:
2346 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2347 * $ <[enter], repeatedly...>
2348 * Without check_and_run_traps, handler never runs.
2349 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002350 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002351 fputs(prompt_str, stdout);
2352 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002353 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002354//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002355 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002356 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2357 * no ^C masking happens during fgetc, no special code for ^C:
2358 * it generates SIGINT as usual.
2359 */
2360 check_and_run_traps();
2361 if (G.flag_SIGINT)
2362 G.last_exitcode = 128 + SIGINT;
2363 if (r != '\0')
2364 break;
2365 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002366 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002367# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002368}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002369/* This is the magic location that prints prompts
2370 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002371static int fgetc_interactive(struct in_str *i)
2372{
2373 int ch;
2374 /* If it's interactive stdin, get new line. */
2375 if (G_interactive_fd && i->file == stdin) {
2376 /* Returns first char (or EOF), the rest is in i->p[] */
2377 ch = get_user_input(i);
2378 i->promptmode = 1; /* PS2 */
2379 } else {
2380 /* Not stdin: script file, sourced file, etc */
2381 do ch = fgetc(i->file); while (ch == '\0');
2382 }
2383 return ch;
2384}
2385#else
2386static inline int fgetc_interactive(struct in_str *i)
2387{
2388 int ch;
2389 do ch = fgetc(i->file); while (ch == '\0');
2390 return ch;
2391}
2392#endif /* INTERACTIVE */
2393
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002394static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002395{
2396 int ch;
2397
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002398 if (!i->file) {
2399 /* string-based in_str */
2400 ch = (unsigned char)*i->p;
2401 if (ch != '\0') {
2402 i->p++;
2403 i->last_char = ch;
2404 return ch;
2405 }
2406 return EOF;
2407 }
2408
2409 /* FILE-based in_str */
2410
Denys Vlasenko4074d492016-09-30 01:49:53 +02002411#if ENABLE_FEATURE_EDITING
2412 /* This can be stdin, check line editing char[] buffer */
2413 if (i->p && *i->p != '\0') {
2414 ch = (unsigned char)*i->p++;
2415 goto out;
2416 }
2417#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002418 /* peek_buf[] is an int array, not char. Can contain EOF. */
2419 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002420 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002421 int ch2 = i->peek_buf[1];
2422 i->peek_buf[0] = ch2;
2423 if (ch2 == 0) /* very likely, avoid redundant write */
2424 goto out;
2425 i->peek_buf[1] = 0;
2426 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002427 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002428
Denys Vlasenko4074d492016-09-30 01:49:53 +02002429 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002430 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002431 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002432 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002433 return ch;
2434}
2435
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002436static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002437{
2438 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002439
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002440 if (!i->file) {
2441 /* string-based in_str */
2442 /* Doesn't report EOF on NUL. None of the callers care. */
2443 return (unsigned char)*i->p;
2444 }
2445
2446 /* FILE-based in_str */
2447
Denys Vlasenko4074d492016-09-30 01:49:53 +02002448#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002449 /* This can be stdin, check line editing char[] buffer */
2450 if (i->p && *i->p != '\0')
2451 return (unsigned char)*i->p;
2452#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002453 /* peek_buf[] is an int array, not char. Can contain EOF. */
2454 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002455 if (ch != 0)
2456 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002457
Denys Vlasenko4074d492016-09-30 01:49:53 +02002458 /* Need to get a new char */
2459 ch = fgetc_interactive(i);
2460 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2461
2462 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2463#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2464 if (i->p) {
2465 i->p -= 1;
2466 return ch;
2467 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002468#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002469 i->peek_buf[0] = ch;
2470 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002471 return ch;
2472}
2473
Denys Vlasenko4074d492016-09-30 01:49:53 +02002474/* Only ever called if i_peek() was called, and did not return EOF.
2475 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2476 * not end-of-line. Therefore we never need to read a new editing line here.
2477 */
2478static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002479{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002480 int ch;
2481
2482 /* There are two cases when i->p[] buffer exists.
2483 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002484 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002485 * In both cases, we know that i->p[0] exists and not NUL, and
2486 * the peek2 result is in i->p[1].
2487 */
2488 if (i->p)
2489 return (unsigned char)i->p[1];
2490
2491 /* Now we know it is a file-based in_str. */
2492
2493 /* peek_buf[] is an int array, not char. Can contain EOF. */
2494 /* Is there 2nd char? */
2495 ch = i->peek_buf[1];
2496 if (ch == 0) {
2497 /* We did not read it yet, get it now */
2498 do ch = fgetc(i->file); while (ch == '\0');
2499 i->peek_buf[1] = ch;
2500 }
2501
2502 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2503 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002504}
2505
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002506static void setup_file_in_str(struct in_str *i, FILE *f)
2507{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002508 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002509 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002510 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002511 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002512}
2513
2514static void setup_string_in_str(struct in_str *i, const char *s)
2515{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002516 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002517 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002518 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002519 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002520}
2521
2522
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002523/*
2524 * o_string support
2525 */
2526#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002527
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002528static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002529{
2530 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002531 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002532 if (o->data)
2533 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002534}
2535
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002536static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002537{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002538 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002539 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002540}
2541
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002542static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2543{
2544 free(o->data);
2545}
2546
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002547static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002548{
2549 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002550 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002551 o->data = xrealloc(o->data, 1 + o->maxlen);
2552 }
2553}
2554
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002555static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002556{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002557 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002558 if (o->length < o->maxlen) {
2559 /* likely. avoid o_grow_by() call */
2560 add:
2561 o->data[o->length] = ch;
2562 o->length++;
2563 o->data[o->length] = '\0';
2564 return;
2565 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002566 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002567 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002568}
2569
Denys Vlasenko657086a2016-09-29 18:07:42 +02002570#if 0
2571/* Valid only if we know o_string is not empty */
2572static void o_delchr(o_string *o)
2573{
2574 o->length--;
2575 o->data[o->length] = '\0';
2576}
2577#endif
2578
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002579static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002580{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002581 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002582 memcpy(&o->data[o->length], str, len);
2583 o->length += len;
2584 o->data[o->length] = '\0';
2585}
2586
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002587static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002588{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002589 o_addblock(o, str, strlen(str));
2590}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002591
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002592#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002593static void nommu_addchr(o_string *o, int ch)
2594{
2595 if (o)
2596 o_addchr(o, ch);
2597}
2598#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002599# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002600#endif
2601
2602static void o_addstr_with_NUL(o_string *o, const char *str)
2603{
2604 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002605}
2606
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002607/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002608 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002609 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2610 * Apparently, on unquoted $v bash still does globbing
2611 * ("v='*.txt'; echo $v" prints all .txt files),
2612 * but NOT brace expansion! Thus, there should be TWO independent
2613 * quoting mechanisms on $v expansion side: one protects
2614 * $v from brace expansion, and other additionally protects "$v" against globbing.
2615 * We have only second one.
2616 */
2617
Denys Vlasenko9e800222010-10-03 14:28:04 +02002618#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002619# define MAYBE_BRACES "{}"
2620#else
2621# define MAYBE_BRACES ""
2622#endif
2623
Eric Andersen25f27032001-04-26 23:22:31 +00002624/* My analysis of quoting semantics tells me that state information
2625 * is associated with a destination, not a source.
2626 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002627static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002628{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002629 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002630 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002631 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002632 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002633 o_grow_by(o, sz);
2634 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002635 o->data[o->length] = '\\';
2636 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002637 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002638 o->data[o->length] = ch;
2639 o->length++;
2640 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002641}
2642
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002643static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002644{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002645 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002646 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2647 && strchr("*?[\\" MAYBE_BRACES, ch)
2648 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002649 sz++;
2650 o->data[o->length] = '\\';
2651 o->length++;
2652 }
2653 o_grow_by(o, sz);
2654 o->data[o->length] = ch;
2655 o->length++;
2656 o->data[o->length] = '\0';
2657}
2658
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002659static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002660{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002661 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002662 char ch;
2663 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002664 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002665 if (ordinary_cnt > len) /* paranoia */
2666 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002667 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002668 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002669 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002670 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002671 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002672
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002673 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002674 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002675 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002676 sz++;
2677 o->data[o->length] = '\\';
2678 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002679 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002680 o_grow_by(o, sz);
2681 o->data[o->length] = ch;
2682 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002683 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002684 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002685}
2686
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002687static void o_addQblock(o_string *o, const char *str, int len)
2688{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002689 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002690 o_addblock(o, str, len);
2691 return;
2692 }
2693 o_addqblock(o, str, len);
2694}
2695
Denys Vlasenko38292b62010-09-05 14:49:40 +02002696static void o_addQstr(o_string *o, const char *str)
2697{
2698 o_addQblock(o, str, strlen(str));
2699}
2700
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002701/* A special kind of o_string for $VAR and `cmd` expansion.
2702 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002703 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002704 * list[i] contains an INDEX (int!) into this string data.
2705 * It means that if list[] needs to grow, data needs to be moved higher up
2706 * but list[i]'s need not be modified.
2707 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002708 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002709 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2710 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002711#if DEBUG_EXPAND || DEBUG_GLOB
2712static void debug_print_list(const char *prefix, o_string *o, int n)
2713{
2714 char **list = (char**)o->data;
2715 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2716 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002717
2718 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002719 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 +02002720 prefix, list, n, string_start, o->length, o->maxlen,
2721 !!(o->o_expflags & EXP_FLAG_GLOB),
2722 o->has_quoted_part,
2723 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002724 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002725 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002726 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2727 o->data + (int)(uintptr_t)list[i] + string_start,
2728 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002729 i++;
2730 }
2731 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002732 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002733 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002734 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002735 }
2736}
2737#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002738# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002739#endif
2740
2741/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2742 * in list[n] so that it points past last stored byte so far.
2743 * It returns n+1. */
2744static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002745{
2746 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002747 int string_start;
2748 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002749
2750 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002751 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2752 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002753 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002754 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002755 /* list[n] points to string_start, make space for 16 more pointers */
2756 o->maxlen += 0x10 * sizeof(list[0]);
2757 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002758 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002759 memmove(list + n + 0x10, list + n, string_len);
2760 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002761 } else {
2762 debug_printf_list("list[%d]=%d string_start=%d\n",
2763 n, string_len, string_start);
2764 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002765 } else {
2766 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002767 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2768 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002769 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2770 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002771 o->has_empty_slot = 0;
2772 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002773 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002774 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002775 return n + 1;
2776}
2777
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002778/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002779static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002780{
2781 char **list = (char**)o->data;
2782 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2783
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002784 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002785}
2786
Denys Vlasenko9e800222010-10-03 14:28:04 +02002787#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002788/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2789 * first, it processes even {a} (no commas), second,
2790 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002791 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002792 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002793
2794/* Helper */
2795static int glob_needed(const char *s)
2796{
2797 while (*s) {
2798 if (*s == '\\') {
2799 if (!s[1])
2800 return 0;
2801 s += 2;
2802 continue;
2803 }
2804 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2805 return 1;
2806 s++;
2807 }
2808 return 0;
2809}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002810/* Return pointer to next closing brace or to comma */
2811static const char *next_brace_sub(const char *cp)
2812{
2813 unsigned depth = 0;
2814 cp++;
2815 while (*cp != '\0') {
2816 if (*cp == '\\') {
2817 if (*++cp == '\0')
2818 break;
2819 cp++;
2820 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002821 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002822 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002823 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002824 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002825 depth++;
2826 }
2827
2828 return *cp != '\0' ? cp : NULL;
2829}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002830/* Recursive brace globber. Note: may garble pattern[]. */
2831static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002832{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002833 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002834 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002835 const char *next;
2836 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002837 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002838 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002839
2840 debug_printf_glob("glob_brace('%s')\n", pattern);
2841
2842 begin = pattern;
2843 while (1) {
2844 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002845 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002846 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002847 /* Find the first sub-pattern and at the same time
2848 * find the rest after the closing brace */
2849 next = next_brace_sub(begin);
2850 if (next == NULL) {
2851 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002852 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002853 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002854 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002855 /* "{abc}" with no commas - illegal
2856 * brace expr, disregard and skip it */
2857 begin = next + 1;
2858 continue;
2859 }
2860 break;
2861 }
2862 if (*begin == '\\' && begin[1] != '\0')
2863 begin++;
2864 begin++;
2865 }
2866 debug_printf_glob("begin:%s\n", begin);
2867 debug_printf_glob("next:%s\n", next);
2868
2869 /* Now find the end of the whole brace expression */
2870 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002871 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002872 rest = next_brace_sub(rest);
2873 if (rest == NULL) {
2874 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002875 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002876 }
2877 debug_printf_glob("rest:%s\n", rest);
2878 }
2879 rest_len = strlen(++rest) + 1;
2880
2881 /* We are sure the brace expression is well-formed */
2882
2883 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002884 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002885
2886 /* We have a brace expression. BEGIN points to the opening {,
2887 * NEXT points past the terminator of the first element, and REST
2888 * points past the final }. We will accumulate result names from
2889 * recursive runs for each brace alternative in the buffer using
2890 * GLOB_APPEND. */
2891
2892 p = begin + 1;
2893 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002894 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002895 memcpy(
2896 mempcpy(
2897 mempcpy(new_pattern_buf,
2898 /* We know the prefix for all sub-patterns */
2899 pattern, begin - pattern),
2900 p, next - p),
2901 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002902
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002903 /* Note: glob_brace() may garble new_pattern_buf[].
2904 * That's why we re-copy prefix every time (1st memcpy above).
2905 */
2906 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002907 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002908 /* We saw the last entry */
2909 break;
2910 }
2911 p = next + 1;
2912 next = next_brace_sub(next);
2913 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002914 free(new_pattern_buf);
2915 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002916
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002917 simple_glob:
2918 {
2919 int gr;
2920 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002921
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002922 memset(&globdata, 0, sizeof(globdata));
2923 gr = glob(pattern, 0, NULL, &globdata);
2924 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2925 if (gr != 0) {
2926 if (gr == GLOB_NOMATCH) {
2927 globfree(&globdata);
2928 /* NB: garbles parameter */
2929 unbackslash(pattern);
2930 o_addstr_with_NUL(o, pattern);
2931 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2932 return o_save_ptr_helper(o, n);
2933 }
2934 if (gr == GLOB_NOSPACE)
2935 bb_error_msg_and_die(bb_msg_memory_exhausted);
2936 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2937 * but we didn't specify it. Paranoia again. */
2938 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2939 }
2940 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2941 char **argv = globdata.gl_pathv;
2942 while (1) {
2943 o_addstr_with_NUL(o, *argv);
2944 n = o_save_ptr_helper(o, n);
2945 argv++;
2946 if (!*argv)
2947 break;
2948 }
2949 }
2950 globfree(&globdata);
2951 }
2952 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002953}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002954/* Performs globbing on last list[],
2955 * saving each result as a new list[].
2956 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002957static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002958{
2959 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002960
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002961 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002962 if (!o->data)
2963 return o_save_ptr_helper(o, n);
2964 pattern = o->data + o_get_last_ptr(o, n);
2965 debug_printf_glob("glob pattern '%s'\n", pattern);
2966 if (!glob_needed(pattern)) {
2967 /* unbackslash last string in o in place, fix length */
2968 o->length = unbackslash(pattern) - o->data;
2969 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2970 return o_save_ptr_helper(o, n);
2971 }
2972
2973 copy = xstrdup(pattern);
2974 /* "forget" pattern in o */
2975 o->length = pattern - o->data;
2976 n = glob_brace(copy, o, n);
2977 free(copy);
2978 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002979 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002980 return n;
2981}
2982
Denys Vlasenko238081f2010-10-03 14:26:26 +02002983#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002984
2985/* Helper */
2986static int glob_needed(const char *s)
2987{
2988 while (*s) {
2989 if (*s == '\\') {
2990 if (!s[1])
2991 return 0;
2992 s += 2;
2993 continue;
2994 }
2995 if (*s == '*' || *s == '[' || *s == '?')
2996 return 1;
2997 s++;
2998 }
2999 return 0;
3000}
3001/* Performs globbing on last list[],
3002 * saving each result as a new list[].
3003 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003004static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003005{
3006 glob_t globdata;
3007 int gr;
3008 char *pattern;
3009
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003010 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003011 if (!o->data)
3012 return o_save_ptr_helper(o, n);
3013 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003014 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003015 if (!glob_needed(pattern)) {
3016 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003017 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003018 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003019 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003020 return o_save_ptr_helper(o, n);
3021 }
3022
3023 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003024 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3025 * If we glob "*.\*" and don't find anything, we need
3026 * to fall back to using literal "*.*", but GLOB_NOCHECK
3027 * will return "*.\*"!
3028 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003029 gr = glob(pattern, 0, NULL, &globdata);
3030 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003031 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003032 if (gr == GLOB_NOMATCH) {
3033 globfree(&globdata);
3034 goto literal;
3035 }
3036 if (gr == GLOB_NOSPACE)
3037 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003038 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3039 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003040 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003041 }
3042 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3043 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003044 /* "forget" pattern in o */
3045 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003046 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003047 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003048 n = o_save_ptr_helper(o, n);
3049 argv++;
3050 if (!*argv)
3051 break;
3052 }
3053 }
3054 globfree(&globdata);
3055 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003056 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003057 return n;
3058}
3059
Denys Vlasenko238081f2010-10-03 14:26:26 +02003060#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003061
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003062/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003063 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003064static int o_save_ptr(o_string *o, int n)
3065{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003066 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003067 /* If o->has_empty_slot, list[n] was already globbed
3068 * (if it was requested back then when it was filled)
3069 * so don't do that again! */
3070 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003071 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003072 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003073 return o_save_ptr_helper(o, n);
3074}
3075
3076/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003077static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003078{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003079 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003080 int string_start;
3081
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003082 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3083 if (DEBUG_EXPAND)
3084 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003085 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003086 list = (char**)o->data;
3087 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3088 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003089 while (n) {
3090 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003091 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003092 }
3093 return list;
3094}
3095
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003096static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003097
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003098/* Returns pi->next - next pipe in the list */
3099static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003100{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003101 struct pipe *next;
3102 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003103
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003104 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003105 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003106 struct command *command;
3107 struct redir_struct *r, *rnext;
3108
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003109 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003110 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003111 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003112 if (DEBUG_CLEAN) {
3113 int a;
3114 char **p;
3115 for (a = 0, p = command->argv; *p; a++, p++) {
3116 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3117 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003118 }
3119 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003120 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003121 }
3122 /* not "else if": on syntax error, we may have both! */
3123 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003124 debug_printf_clean(" begin group (cmd_type:%d)\n",
3125 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003126 free_pipe_list(command->group);
3127 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003128 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003129 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003130 /* else is crucial here.
3131 * If group != NULL, child_func is meaningless */
3132#if ENABLE_HUSH_FUNCTIONS
3133 else if (command->child_func) {
3134 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3135 command->child_func->parent_cmd = NULL;
3136 }
3137#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003138#if !BB_MMU
3139 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003140 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003141#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003142 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003143 debug_printf_clean(" redirect %d%s",
3144 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003145 /* guard against the case >$FOO, where foo is unset or blank */
3146 if (r->rd_filename) {
3147 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3148 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003149 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003150 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003151 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003152 rnext = r->next;
3153 free(r);
3154 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003155 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003156 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003157 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003158 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003159#if ENABLE_HUSH_JOB
3160 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003161 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003162#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003163
3164 next = pi->next;
3165 free(pi);
3166 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003167}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003168
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003169static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003170{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003171 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003172#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003173 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003174#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003175 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003176 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003177 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003178}
3179
3180
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003181/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003182
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003183#ifndef debug_print_tree
3184static void debug_print_tree(struct pipe *pi, int lvl)
3185{
3186 static const char *const PIPE[] = {
3187 [PIPE_SEQ] = "SEQ",
3188 [PIPE_AND] = "AND",
3189 [PIPE_OR ] = "OR" ,
3190 [PIPE_BG ] = "BG" ,
3191 };
3192 static const char *RES[] = {
3193 [RES_NONE ] = "NONE" ,
3194# if ENABLE_HUSH_IF
3195 [RES_IF ] = "IF" ,
3196 [RES_THEN ] = "THEN" ,
3197 [RES_ELIF ] = "ELIF" ,
3198 [RES_ELSE ] = "ELSE" ,
3199 [RES_FI ] = "FI" ,
3200# endif
3201# if ENABLE_HUSH_LOOPS
3202 [RES_FOR ] = "FOR" ,
3203 [RES_WHILE] = "WHILE",
3204 [RES_UNTIL] = "UNTIL",
3205 [RES_DO ] = "DO" ,
3206 [RES_DONE ] = "DONE" ,
3207# endif
3208# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3209 [RES_IN ] = "IN" ,
3210# endif
3211# if ENABLE_HUSH_CASE
3212 [RES_CASE ] = "CASE" ,
3213 [RES_CASE_IN ] = "CASE_IN" ,
3214 [RES_MATCH] = "MATCH",
3215 [RES_CASE_BODY] = "CASE_BODY",
3216 [RES_ESAC ] = "ESAC" ,
3217# endif
3218 [RES_XXXX ] = "XXXX" ,
3219 [RES_SNTX ] = "SNTX" ,
3220 };
3221 static const char *const CMDTYPE[] = {
3222 "{}",
3223 "()",
3224 "[noglob]",
3225# if ENABLE_HUSH_FUNCTIONS
3226 "func()",
3227# endif
3228 };
3229
3230 int pin, prn;
3231
3232 pin = 0;
3233 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003234 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003235 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3236 prn = 0;
3237 while (prn < pi->num_cmds) {
3238 struct command *command = &pi->cmds[prn];
3239 char **argv = command->argv;
3240
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003241 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003242 lvl*2, "", prn,
3243 command->assignment_cnt);
3244 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003245 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003246 CMDTYPE[command->cmd_type],
3247 argv
3248# if !BB_MMU
3249 , " group_as_string:", command->group_as_string
3250# else
3251 , "", ""
3252# endif
3253 );
3254 debug_print_tree(command->group, lvl+1);
3255 prn++;
3256 continue;
3257 }
3258 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003259 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003260 argv++;
3261 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003262 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003263 prn++;
3264 }
3265 pi = pi->next;
3266 pin++;
3267 }
3268}
3269#endif /* debug_print_tree */
3270
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003271static struct pipe *new_pipe(void)
3272{
Eric Andersen25f27032001-04-26 23:22:31 +00003273 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003274 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003275 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003276 return pi;
3277}
3278
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003279/* Command (member of a pipe) is complete, or we start a new pipe
3280 * if ctx->command is NULL.
3281 * No errors possible here.
3282 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003283static int done_command(struct parse_context *ctx)
3284{
3285 /* The command is really already in the pipe structure, so
3286 * advance the pipe counter and make a new, null command. */
3287 struct pipe *pi = ctx->pipe;
3288 struct command *command = ctx->command;
3289
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003290#if 0 /* Instead we emit error message at run time */
3291 if (ctx->pending_redirect) {
3292 /* For example, "cmd >" (no filename to redirect to) */
3293 die_if_script("syntax error: %s", "invalid redirect");
3294 ctx->pending_redirect = NULL;
3295 }
3296#endif
3297
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003298 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003299 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003300 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003301 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003302 }
3303 pi->num_cmds++;
3304 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003305 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003306 } else {
3307 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3308 }
3309
3310 /* Only real trickiness here is that the uncommitted
3311 * command structure is not counted in pi->num_cmds. */
3312 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003313 ctx->command = command = &pi->cmds[pi->num_cmds];
3314 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003315 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003316 return pi->num_cmds; /* used only for 0/nonzero check */
3317}
3318
3319static void done_pipe(struct parse_context *ctx, pipe_style type)
3320{
3321 int not_null;
3322
3323 debug_printf_parse("done_pipe entered, followup %d\n", type);
3324 /* Close previous command */
3325 not_null = done_command(ctx);
3326 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003327#if HAS_KEYWORDS
3328 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3329 ctx->ctx_inverted = 0;
3330 ctx->pipe->res_word = ctx->ctx_res_w;
3331#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003332
3333 /* Without this check, even just <enter> on command line generates
3334 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003335 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003336 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003337#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003338 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003339#endif
3340#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003341 || ctx->ctx_res_w == RES_DONE
3342 || ctx->ctx_res_w == RES_FOR
3343 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003344#endif
3345#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003346 || ctx->ctx_res_w == RES_ESAC
3347#endif
3348 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003349 struct pipe *new_p;
3350 debug_printf_parse("done_pipe: adding new pipe: "
3351 "not_null:%d ctx->ctx_res_w:%d\n",
3352 not_null, ctx->ctx_res_w);
3353 new_p = new_pipe();
3354 ctx->pipe->next = new_p;
3355 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003356 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003357 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003358 * This is used to control execution.
3359 * RES_FOR and RES_IN are NOT sticky (needed to support
3360 * cases where variable or value happens to match a keyword):
3361 */
3362#if ENABLE_HUSH_LOOPS
3363 if (ctx->ctx_res_w == RES_FOR
3364 || ctx->ctx_res_w == RES_IN)
3365 ctx->ctx_res_w = RES_NONE;
3366#endif
3367#if ENABLE_HUSH_CASE
3368 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003369 ctx->ctx_res_w = RES_CASE_BODY;
3370 if (ctx->ctx_res_w == RES_CASE)
3371 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003372#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003373 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003374 /* Create the memory for command, roughly:
3375 * ctx->pipe->cmds = new struct command;
3376 * ctx->command = &ctx->pipe->cmds[0];
3377 */
3378 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003379 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003380 }
3381 debug_printf_parse("done_pipe return\n");
3382}
3383
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003384static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003385{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003386 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003387 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003388 /* Create the memory for command, roughly:
3389 * ctx->pipe->cmds = new struct command;
3390 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003391 */
3392 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003393}
3394
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003395/* If a reserved word is found and processed, parse context is modified
3396 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003397 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003398#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003399struct reserved_combo {
3400 char literal[6];
3401 unsigned char res;
3402 unsigned char assignment_flag;
3403 int flag;
3404};
3405enum {
3406 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003407# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003408 FLAG_IF = (1 << RES_IF ),
3409 FLAG_THEN = (1 << RES_THEN ),
3410 FLAG_ELIF = (1 << RES_ELIF ),
3411 FLAG_ELSE = (1 << RES_ELSE ),
3412 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003413# endif
3414# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003415 FLAG_FOR = (1 << RES_FOR ),
3416 FLAG_WHILE = (1 << RES_WHILE),
3417 FLAG_UNTIL = (1 << RES_UNTIL),
3418 FLAG_DO = (1 << RES_DO ),
3419 FLAG_DONE = (1 << RES_DONE ),
3420 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003421# endif
3422# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003423 FLAG_MATCH = (1 << RES_MATCH),
3424 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003425# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003426 FLAG_START = (1 << RES_XXXX ),
3427};
3428
3429static const struct reserved_combo* match_reserved_word(o_string *word)
3430{
Eric Andersen25f27032001-04-26 23:22:31 +00003431 /* Mostly a list of accepted follow-up reserved words.
3432 * FLAG_END means we are done with the sequence, and are ready
3433 * to turn the compound list into a command.
3434 * FLAG_START means the word must start a new compound list.
3435 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003436 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003437# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003438 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3439 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3440 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3441 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3442 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3443 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003444# endif
3445# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003446 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3447 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3448 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3449 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3450 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3451 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003452# endif
3453# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003454 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3455 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003456# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003457 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003458 const struct reserved_combo *r;
3459
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003460 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003461 if (strcmp(word->data, r->literal) == 0)
3462 return r;
3463 }
3464 return NULL;
3465}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003466/* Return 0: not a keyword, 1: keyword
3467 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003468static int reserved_word(o_string *word, struct parse_context *ctx)
3469{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003470# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003471 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003472 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003473 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003474# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003475 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003476
Denys Vlasenko38292b62010-09-05 14:49:40 +02003477 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003478 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003479 r = match_reserved_word(word);
3480 if (!r)
3481 return 0;
3482
3483 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003484# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003485 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3486 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003487 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003488 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003489# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003490 if (r->flag == 0) { /* '!' */
3491 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003492 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003493 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003494 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003495 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003496 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003497 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003498 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003499 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003500
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003501 old = xmalloc(sizeof(*old));
3502 debug_printf_parse("push stack %p\n", old);
3503 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003504 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003505 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003506 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003507 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003508 ctx->ctx_res_w = RES_SNTX;
3509 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003510 } else {
3511 /* "{...} fi" is ok. "{...} if" is not
3512 * Example:
3513 * if { echo foo; } then { echo bar; } fi */
3514 if (ctx->command->group)
3515 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003516 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003517
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003518 ctx->ctx_res_w = r->res;
3519 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003520 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003521 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003522
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003523 if (ctx->old_flag & FLAG_END) {
3524 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003525
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003526 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003527 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003528 old = ctx->stack;
3529 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003530 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003531# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003532 /* At this point, the compound command's string is in
3533 * ctx->as_string... except for the leading keyword!
3534 * Consider this example: "echo a | if true; then echo a; fi"
3535 * ctx->as_string will contain "true; then echo a; fi",
3536 * with "if " remaining in old->as_string!
3537 */
3538 {
3539 char *str;
3540 int len = old->as_string.length;
3541 /* Concatenate halves */
3542 o_addstr(&old->as_string, ctx->as_string.data);
3543 o_free_unsafe(&ctx->as_string);
3544 /* Find where leading keyword starts in first half */
3545 str = old->as_string.data + len;
3546 if (str > old->as_string.data)
3547 str--; /* skip whitespace after keyword */
3548 while (str > old->as_string.data && isalpha(str[-1]))
3549 str--;
3550 /* Ugh, we're done with this horrid hack */
3551 old->command->group_as_string = xstrdup(str);
3552 debug_printf_parse("pop, remembering as:'%s'\n",
3553 old->command->group_as_string);
3554 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003555# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003556 *ctx = *old; /* physical copy */
3557 free(old);
3558 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003559 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003560}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003561#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003562
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003563/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003564 * Normal return is 0. Syntax errors return 1.
3565 * Note: on return, word is reset, but not o_free'd!
3566 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003567static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003568{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003569 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003570
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003571 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003572 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003573 debug_printf_parse("done_word return 0: true null, ignored\n");
3574 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003575 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003576
Eric Andersen25f27032001-04-26 23:22:31 +00003577 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003578 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3579 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003580 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3581 * "2.7 Redirection
3582 * ...the word that follows the redirection operator
3583 * shall be subjected to tilde expansion, parameter expansion,
3584 * command substitution, arithmetic expansion, and quote
3585 * removal. Pathname expansion shall not be performed
3586 * on the word by a non-interactive shell; an interactive
3587 * shell may perform it, but shall do so only when
3588 * the expansion would result in one word."
3589 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003590 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003591 /* Cater for >\file case:
3592 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3593 * Same with heredocs:
3594 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3595 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003596 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3597 unbackslash(ctx->pending_redirect->rd_filename);
3598 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003599 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003600 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3601 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003602 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003603 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003604 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003605 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003606#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003607# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003608 if (ctx->ctx_dsemicolon
3609 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3610 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003611 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003612 /* ctx->ctx_res_w = RES_MATCH; */
3613 ctx->ctx_dsemicolon = 0;
3614 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003615# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003616 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003617# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003618 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3619 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003620# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003621# if ENABLE_HUSH_CASE
3622 && ctx->ctx_res_w != RES_CASE
3623# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003624 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003625 int reserved = reserved_word(word, ctx);
3626 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3627 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003628 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003629 debug_printf_parse("done_word return %d\n",
3630 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003631 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003632 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003633# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003634 if (strcmp(word->data, "[[") == 0) {
3635 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3636 }
3637 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003638# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003639 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003640#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003641 if (command->group) {
3642 /* "{ echo foo; } echo bar" - bad */
3643 syntax_error_at(word->data);
3644 debug_printf_parse("done_word return 1: syntax error, "
3645 "groups and arglists don't mix\n");
3646 return 1;
3647 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003648
3649 /* If this word wasn't an assignment, next ones definitely
3650 * can't be assignments. Even if they look like ones. */
3651 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3652 && word->o_assignment != WORD_IS_KEYWORD
3653 ) {
3654 word->o_assignment = NOT_ASSIGNMENT;
3655 } else {
3656 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3657 command->assignment_cnt++;
3658 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3659 }
3660 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3661 word->o_assignment = MAYBE_ASSIGNMENT;
3662 }
3663 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3664
Denys Vlasenko38292b62010-09-05 14:49:40 +02003665 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003666 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3667 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003668 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003669 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003670 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003671 char *p = word->data;
3672 while (p[0] == SPECIAL_VAR_SYMBOL
3673 && (p[1] & 0x7f) == '@'
3674 && p[2] == SPECIAL_VAR_SYMBOL
3675 ) {
3676 p += 3;
3677 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003678 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003679 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003680 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003681 }
Eric Andersen25f27032001-04-26 23:22:31 +00003682
Denis Vlasenko06810332007-05-21 23:30:54 +00003683#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003684 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003685 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003686 || !is_well_formed_var_name(command->argv[0], '\0')
3687 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003688 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003689 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003690 return 1;
3691 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003692 /* Force FOR to have just one word (variable name) */
3693 /* NB: basically, this makes hush see "for v in ..."
3694 * syntax as if it is "for v; in ...". FOR and IN become
3695 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003696 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003697 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003698#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003699#if ENABLE_HUSH_CASE
3700 /* Force CASE to have just one word */
3701 if (ctx->ctx_res_w == RES_CASE) {
3702 done_pipe(ctx, PIPE_SEQ);
3703 }
3704#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003705
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003706 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003707
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003708 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003709 return 0;
3710}
3711
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003712
3713/* Peek ahead in the input to find out if we have a "&n" construct,
3714 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003715 * Return:
3716 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3717 * REDIRFD_SYNTAX_ERR if syntax error,
3718 * REDIRFD_TO_FILE if no & was seen,
3719 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003720 */
3721#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003722#define parse_redir_right_fd(as_string, input) \
3723 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003724#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003725static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003726{
3727 int ch, d, ok;
3728
3729 ch = i_peek(input);
3730 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003731 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003732
3733 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003734 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003735 ch = i_peek(input);
3736 if (ch == '-') {
3737 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003738 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003739 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003740 }
3741 d = 0;
3742 ok = 0;
3743 while (ch != EOF && isdigit(ch)) {
3744 d = d*10 + (ch-'0');
3745 ok = 1;
3746 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003747 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003748 ch = i_peek(input);
3749 }
3750 if (ok) return d;
3751
3752//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3753
3754 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003755 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003756}
3757
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003758/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003759 */
3760static int parse_redirect(struct parse_context *ctx,
3761 int fd,
3762 redir_type style,
3763 struct in_str *input)
3764{
3765 struct command *command = ctx->command;
3766 struct redir_struct *redir;
3767 struct redir_struct **redirp;
3768 int dup_num;
3769
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003770 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003771 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003772 /* Check for a '>&1' type redirect */
3773 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3774 if (dup_num == REDIRFD_SYNTAX_ERR)
3775 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003776 } else {
3777 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003778 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003779 if (dup_num) { /* <<-... */
3780 ch = i_getch(input);
3781 nommu_addchr(&ctx->as_string, ch);
3782 ch = i_peek(input);
3783 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003784 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003785
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003786 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003787 int ch = i_peek(input);
3788 if (ch == '|') {
3789 /* >|FILE redirect ("clobbering" >).
3790 * Since we do not support "set -o noclobber" yet,
3791 * >| and > are the same for now. Just eat |.
3792 */
3793 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003794 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003795 }
3796 }
3797
3798 /* Create a new redir_struct and append it to the linked list */
3799 redirp = &command->redirects;
3800 while ((redir = *redirp) != NULL) {
3801 redirp = &(redir->next);
3802 }
3803 *redirp = redir = xzalloc(sizeof(*redir));
3804 /* redir->next = NULL; */
3805 /* redir->rd_filename = NULL; */
3806 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003807 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003808
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003809 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3810 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003811
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003812 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003813 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003814 /* Erik had a check here that the file descriptor in question
3815 * is legit; I postpone that to "run time"
3816 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003817 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3818 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003819 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003820#if 0 /* Instead we emit error message at run time */
3821 if (ctx->pending_redirect) {
3822 /* For example, "cmd > <file" */
3823 die_if_script("syntax error: %s", "invalid redirect");
3824 }
3825#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003826 /* Set ctx->pending_redirect, so we know what to do at the
3827 * end of the next parsed word. */
3828 ctx->pending_redirect = redir;
3829 }
3830 return 0;
3831}
3832
Eric Andersen25f27032001-04-26 23:22:31 +00003833/* If a redirect is immediately preceded by a number, that number is
3834 * supposed to tell which file descriptor to redirect. This routine
3835 * looks for such preceding numbers. In an ideal world this routine
3836 * needs to handle all the following classes of redirects...
3837 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3838 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3839 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3840 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003841 *
3842 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3843 * "2.7 Redirection
3844 * ... If n is quoted, the number shall not be recognized as part of
3845 * the redirection expression. For example:
3846 * echo \2>a
3847 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003848 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003849 *
3850 * A -1 return means no valid number was found,
3851 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003852 */
3853static int redirect_opt_num(o_string *o)
3854{
3855 int num;
3856
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003857 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003858 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003859 num = bb_strtou(o->data, NULL, 10);
3860 if (errno || num < 0)
3861 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003862 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003863 return num;
3864}
3865
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003866#if BB_MMU
3867#define fetch_till_str(as_string, input, word, skip_tabs) \
3868 fetch_till_str(input, word, skip_tabs)
3869#endif
3870static char *fetch_till_str(o_string *as_string,
3871 struct in_str *input,
3872 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003873 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003874{
3875 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003876 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003877 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003878 int ch;
3879
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003880 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003881
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003882 while (1) {
3883 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003884 if (ch != EOF)
3885 nommu_addchr(as_string, ch);
3886 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003887 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3888 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003889 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3890 heredoc.data[past_EOL] = '\0';
3891 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3892 return heredoc.data;
3893 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003894 while (ch == '\n') {
3895 o_addchr(&heredoc, ch);
3896 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003897 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003898 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003899 do {
3900 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003901 if (ch != EOF)
3902 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003903 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003904 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003905 }
3906 if (ch == EOF) {
3907 o_free_unsafe(&heredoc);
3908 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003909 }
3910 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003911 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003912 if (prev == '\\' && ch == '\\')
3913 /* Correctly handle foo\\<eol> (not a line cont.) */
3914 prev = 0; /* not \ */
3915 else
3916 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003917 }
3918}
3919
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003920/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3921 * and load them all. There should be exactly heredoc_cnt of them.
3922 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003923static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3924{
3925 struct pipe *pi = ctx->list_head;
3926
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003927 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003928 int i;
3929 struct command *cmd = pi->cmds;
3930
3931 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3932 pi->num_cmds,
3933 cmd->argv ? cmd->argv[0] : "NONE");
3934 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003935 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003936
3937 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3938 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003939 while (redir) {
3940 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003941 char *p;
3942
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003943 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003944 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003945 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003946 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003947 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003948 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003949 return 1;
3950 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003951 free(redir->rd_filename);
3952 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003953 heredoc_cnt--;
3954 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003955 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003956 }
3957 cmd++;
3958 }
3959 pi = pi->next;
3960 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003961#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003962 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003963 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003964 bb_error_msg_and_die("heredoc BUG 2");
3965#endif
3966 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003967}
3968
3969
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003970static int run_list(struct pipe *pi);
3971#if BB_MMU
3972#define parse_stream(pstring, input, end_trigger) \
3973 parse_stream(input, end_trigger)
3974#endif
3975static struct pipe *parse_stream(char **pstring,
3976 struct in_str *input,
3977 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003978
Eric Andersen25f27032001-04-26 23:22:31 +00003979
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003980#if !ENABLE_HUSH_FUNCTIONS
3981#define parse_group(dest, ctx, input, ch) \
3982 parse_group(ctx, input, ch)
3983#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003984static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003985 struct in_str *input, int ch)
3986{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003987 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003988 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003989 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003990 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003991 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003992 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003993
3994 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003995#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003996 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003997 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003998 if (done_word(dest, ctx))
3999 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004000 if (!command->argv)
4001 goto skip; /* (... */
4002 if (command->argv[1]) { /* word word ... (... */
4003 syntax_error_unexpected_ch('(');
4004 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004005 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004006 /* it is "word(..." or "word (..." */
4007 do
4008 ch = i_getch(input);
4009 while (ch == ' ' || ch == '\t');
4010 if (ch != ')') {
4011 syntax_error_unexpected_ch(ch);
4012 return 1;
4013 }
4014 nommu_addchr(&ctx->as_string, ch);
4015 do
4016 ch = i_getch(input);
4017 while (ch == ' ' || ch == '\t' || ch == '\n');
4018 if (ch != '{') {
4019 syntax_error_unexpected_ch(ch);
4020 return 1;
4021 }
4022 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004023 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004024 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004025 }
4026#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004027
4028#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004029 if (command->argv /* word [word]{... */
4030 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004031 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004032 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004033 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004034 debug_printf_parse("parse_group return 1: "
4035 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004036 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004037 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004038#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004039
4040#if ENABLE_HUSH_FUNCTIONS
4041 skip:
4042#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004043 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004044 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004045 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004046 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004047 } else {
4048 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004049 ch = i_peek(input);
4050 if (ch != ' ' && ch != '\t' && ch != '\n'
4051 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4052 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004053 syntax_error_unexpected_ch(ch);
4054 return 1;
4055 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004056 if (ch != '(') {
4057 ch = i_getch(input);
4058 nommu_addchr(&ctx->as_string, ch);
4059 }
Eric Andersen25f27032001-04-26 23:22:31 +00004060 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004061
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004062 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004063#if BB_MMU
4064# define as_string NULL
4065#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004066 char *as_string = NULL;
4067#endif
4068 pipe_list = parse_stream(&as_string, input, endch);
4069#if !BB_MMU
4070 if (as_string)
4071 o_addstr(&ctx->as_string, as_string);
4072#endif
4073 /* empty ()/{} or parse error? */
4074 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00004075 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004076 if (!BB_MMU)
4077 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004078 debug_printf_parse("parse_group return 1: "
4079 "parse_stream returned %p\n", pipe_list);
4080 return 1;
4081 }
4082 command->group = pipe_list;
4083#if !BB_MMU
4084 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4085 command->group_as_string = as_string;
4086 debug_printf_parse("end of group, remembering as:'%s'\n",
4087 command->group_as_string);
4088#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004089#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004090 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004091 debug_printf_parse("parse_group return 0\n");
4092 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004093 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004094}
4095
Denys Vlasenko46e64982016-09-29 19:50:55 +02004096static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4097{
4098 for (;;) {
4099 int ch, ch2;
4100
4101 ch = i_getch(input);
4102 if (ch != '\\')
4103 return ch;
4104 ch2 = i_peek(input);
4105 if (ch2 != '\n')
4106 return ch;
4107 /* backslash+newline, skip it */
4108 i_getch(input);
4109 }
4110}
4111
Denys Vlasenko657086a2016-09-29 18:07:42 +02004112static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4113{
4114 for (;;) {
4115 int ch, ch2;
4116
4117 ch = i_peek(input);
4118 if (ch != '\\')
4119 return ch;
4120 ch2 = i_peek2(input);
4121 if (ch2 != '\n')
4122 return ch;
4123 /* backslash+newline, skip it */
4124 i_getch(input);
4125 i_getch(input);
4126 }
4127}
4128
Denys Vlasenko0b883582016-12-23 16:49:07 +01004129#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004130/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004131static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004132/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004133static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004134{
4135 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004136 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004137 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004138 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004139 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004140 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004141 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004142 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004143 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004144 }
4145}
4146/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004147static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004148{
4149 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004150 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004151 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004152 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004153 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004154 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004155 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004156 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004157 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004158 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004159 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004160 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004161 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004162 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004163 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4164 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004165 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004166 continue;
4167 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004168 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004169 }
4170}
4171/* Process `cmd` - copy contents until "`" is seen. Complicated by
4172 * \` quoting.
4173 * "Within the backquoted style of command substitution, backslash
4174 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4175 * The search for the matching backquote shall be satisfied by the first
4176 * backquote found without a preceding backslash; during this search,
4177 * if a non-escaped backquote is encountered within a shell comment,
4178 * a here-document, an embedded command substitution of the $(command)
4179 * form, or a quoted string, undefined results occur. A single-quoted
4180 * or double-quoted string that begins, but does not end, within the
4181 * "`...`" sequence produces undefined results."
4182 * Example Output
4183 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4184 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004185static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004186{
4187 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004188 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004189 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004190 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004191 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004192 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4193 ch = i_getch(input);
4194 if (ch != '`'
4195 && ch != '$'
4196 && ch != '\\'
4197 && (!in_dquote || ch != '"')
4198 ) {
4199 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004200 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004201 }
4202 if (ch == EOF) {
4203 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004204 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004205 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004206 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004207 }
4208}
4209/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4210 * quoting and nested ()s.
4211 * "With the $(command) style of command substitution, all characters
4212 * following the open parenthesis to the matching closing parenthesis
4213 * constitute the command. Any valid shell script can be used for command,
4214 * except a script consisting solely of redirections which produces
4215 * unspecified results."
4216 * Example Output
4217 * echo $(echo '(TEST)' BEST) (TEST) BEST
4218 * echo $(echo 'TEST)' BEST) TEST) BEST
4219 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004220 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004221 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004222 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004223 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4224 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004225 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004226#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004227static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004228{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004229 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004230 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004231# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004232 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004233# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004234 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4235
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004236 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004237 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004238 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004239 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004240 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004241 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004242 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004243 if (!dbl)
4244 break;
4245 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004246 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004247 i_getch(input); /* eat second ')' */
4248 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004249 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004250 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004251 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004252 if (ch == '(' || ch == '{') {
4253 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004254 if (!add_till_closing_bracket(dest, input, ch))
4255 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004256 o_addchr(dest, ch);
4257 continue;
4258 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004259 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004260 if (!add_till_single_quote(dest, input))
4261 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004262 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004263 continue;
4264 }
4265 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004266 if (!add_till_double_quote(dest, input))
4267 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004268 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004269 continue;
4270 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004271 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004272 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4273 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004274 o_addchr(dest, ch);
4275 continue;
4276 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004277 if (ch == '\\') {
4278 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004279 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004280 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004281 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004282 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004283 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004284#if 0
4285 if (ch == '\n') {
4286 /* "backslash+newline", ignore both */
4287 o_delchr(dest); /* undo insertion of '\' */
4288 continue;
4289 }
4290#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004291 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004292 continue;
4293 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004294 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004295 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004296}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004297#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004298
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004299/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004300#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004301#define parse_dollar(as_string, dest, input, quote_mask) \
4302 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004303#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004304#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004305static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004306 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004307 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004308{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004309 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004310
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004311 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004312 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004313 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004314 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004315 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004316 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004317 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004318 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004319 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004320 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004321 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004322 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004323 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004324 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004325 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004326 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004327 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004328 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004329 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004330 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004331 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004332 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004333 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004334 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004335 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004336 o_addchr(dest, ch | quote_mask);
4337 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004338 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004339 case '$': /* pid */
4340 case '!': /* last bg pid */
4341 case '?': /* last exit code */
4342 case '#': /* number of args */
4343 case '*': /* args */
4344 case '@': /* args */
4345 goto make_one_char_var;
4346 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004347 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4348
Denys Vlasenko74369502010-05-21 19:52:01 +02004349 ch = i_getch(input); /* eat '{' */
4350 nommu_addchr(as_string, ch);
4351
Denys Vlasenko46e64982016-09-29 19:50:55 +02004352 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004353 /* It should be ${?}, or ${#var},
4354 * or even ${?+subst} - operator acting on a special variable,
4355 * or the beginning of variable name.
4356 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004357 if (ch == EOF
4358 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4359 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004360 bad_dollar_syntax:
4361 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004362 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4363 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004364 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004365 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004366 ch |= quote_mask;
4367
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004368 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004369 * However, this regresses some of our testsuite cases
4370 * which check invalid constructs like ${%}.
4371 * Oh well... let's check that the var name part is fine... */
4372
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004373 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004374 unsigned pos;
4375
Denys Vlasenko74369502010-05-21 19:52:01 +02004376 o_addchr(dest, ch);
4377 debug_printf_parse(": '%c'\n", ch);
4378
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004379 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004380 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004381 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004382 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004383
Denys Vlasenko74369502010-05-21 19:52:01 +02004384 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004385 unsigned end_ch;
4386 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004387 /* handle parameter expansions
4388 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4389 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004390 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02004391 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004392
4393 /* Eat everything until closing '}' (or ':') */
4394 end_ch = '}';
4395 if (ENABLE_HUSH_BASH_COMPAT
4396 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004397 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004398 ) {
4399 /* It's ${var:N[:M]} thing */
4400 end_ch = '}' * 0x100 + ':';
4401 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004402 if (ENABLE_HUSH_BASH_COMPAT
4403 && ch == '/'
4404 ) {
4405 /* It's ${var/[/]pattern[/repl]} thing */
4406 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4407 i_getch(input);
4408 nommu_addchr(as_string, '/');
4409 ch = '\\';
4410 }
4411 end_ch = '}' * 0x100 + '/';
4412 }
4413 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004414 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004415 if (!BB_MMU)
4416 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004417#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004418 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004419 if (last_ch == 0) /* error? */
4420 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004421#else
4422#error Simple code to only allow ${var} is not implemented
4423#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004424 if (as_string) {
4425 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004426 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004427 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004428
4429 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4430 /* close the first block: */
4431 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004432 /* while parsing N from ${var:N[:M]}
4433 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004434 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004435 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004436 end_ch = '}';
4437 goto again;
4438 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004439 /* got '}' */
4440 if (end_ch == '}' * 0x100 + ':') {
4441 /* it's ${var:N} - emulate :999999999 */
4442 o_addstr(dest, "999999999");
4443 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004444 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004445 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004446 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004447 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004448 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4449 break;
4450 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004451#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004452 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004453 unsigned pos;
4454
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004455 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004456 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004457# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004458 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004459 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004460 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004461 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4462 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004463 if (!BB_MMU)
4464 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004465 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4466 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004467 if (as_string) {
4468 o_addstr(as_string, dest->data + pos);
4469 o_addchr(as_string, ')');
4470 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004471 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004472 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004473 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004474 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004475# endif
4476# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004477 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4478 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004479 if (!BB_MMU)
4480 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004481 if (!add_till_closing_bracket(dest, input, ')'))
4482 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004483 if (as_string) {
4484 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004485 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004486 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004487 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004488# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004489 break;
4490 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004491#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004492 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004493 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004494 nommu_addchr(as_string, ch);
Denys Vlasenko657086a2016-09-29 18:07:42 +02004495 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004496 if (isalnum(ch)) { /* it's $_name or $_123 */
4497 ch = '_';
4498 goto make_var;
4499 }
4500 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004501 /* TODO: $_ and $-: */
4502 /* $_ Shell or shell script name; or last argument of last command
4503 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4504 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004505 /* $- Option flags set by set builtin or shell options (-i etc) */
4506 default:
4507 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004508 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004509 debug_printf_parse("parse_dollar return 1 (ok)\n");
4510 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004511#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004512}
4513
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004514#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004515# if ENABLE_HUSH_BASH_COMPAT
4516#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4517 encode_string(dest, input, dquote_end, process_bkslash)
4518# else
4519/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4520#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4521 encode_string(dest, input, dquote_end)
4522# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004523#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004524
4525#else /* !MMU */
4526
4527# if ENABLE_HUSH_BASH_COMPAT
4528/* all parameters are needed, no macro tricks */
4529# else
4530#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4531 encode_string(as_string, dest, input, dquote_end)
4532# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004533#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004534static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004535 o_string *dest,
4536 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004537 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004538 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004539{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004540#if !ENABLE_HUSH_BASH_COMPAT
4541 const int process_bkslash = 1;
4542#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004543 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004544 int next;
4545
4546 again:
4547 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004548 if (ch != EOF)
4549 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004550 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004551 debug_printf_parse("encode_string return 1 (ok)\n");
4552 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004553 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004554 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004555 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004556 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004557 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004558 }
4559 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004560 if (ch != '\n') {
4561 next = i_peek(input);
4562 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004563 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004564 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004565 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004566 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004567 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004568 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004569 }
4570 /* bash:
4571 * "The backslash retains its special meaning [in "..."]
4572 * only when followed by one of the following characters:
4573 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004574 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004575 * NB: in (unquoted) heredoc, above does not apply to ",
4576 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004577 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004578 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004579 ch = i_getch(input); /* eat next */
4580 if (ch == '\n')
4581 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004582 } /* else: ch remains == '\\', and we double it below: */
4583 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004584 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004585 goto again;
4586 }
4587 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004588 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4589 debug_printf_parse("encode_string return 0: "
4590 "parse_dollar returned 0 (error)\n");
4591 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004592 }
4593 goto again;
4594 }
4595#if ENABLE_HUSH_TICK
4596 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004597 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004598 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4599 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004600 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4601 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004602 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4603 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004604 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004605 }
4606#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004607 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004608 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004609#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004610}
4611
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004612/*
4613 * Scan input until EOF or end_trigger char.
4614 * Return a list of pipes to execute, or NULL on EOF
4615 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004616 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004617 * reset parsing machinery and start parsing anew,
4618 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004619 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004620static struct pipe *parse_stream(char **pstring,
4621 struct in_str *input,
4622 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004623{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004624 struct parse_context ctx;
4625 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004626 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004627
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004628 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004629 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004630 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004631 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004632 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004633 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004634
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004635 /* If very first arg is "" or '', dest.data may end up NULL.
4636 * Preventing this: */
4637 o_addchr(&dest, '\0');
4638 dest.length = 0;
4639
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004640 /* We used to separate words on $IFS here. This was wrong.
4641 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004642 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004643 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004644
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004645 if (MAYBE_ASSIGNMENT != 0)
4646 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004647 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004648 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004649 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004650 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004651 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004652 int ch;
4653 int next;
4654 int redir_fd;
4655 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004656
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004657 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004658 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004659 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004660 if (ch == EOF) {
4661 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004662
4663 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004664 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004665 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004666 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004667 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004668 syntax_error_unterm_ch('(');
4669 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004670 }
Denys Vlasenko42246472016-11-07 16:22:35 +01004671 if (end_trigger == '}') {
4672 syntax_error_unterm_ch('{');
4673 goto parse_error;
4674 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004675
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004676 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004677 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004678 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004679 o_free(&dest);
4680 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004681 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004682 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004683 /* (this makes bare "&" cmd a no-op.
4684 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004685 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004686 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004687 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004688 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004689 pi = NULL;
4690 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004691#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004692 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004693 if (pstring)
4694 *pstring = ctx.as_string.data;
4695 else
4696 o_free_unsafe(&ctx.as_string);
4697#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004698 debug_leave();
4699 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004700 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004701 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004702 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004703
4704 next = '\0';
4705 if (ch != '\n')
4706 next = i_peek(input);
4707
4708 is_special = "{}<>;&|()#'" /* special outside of "str" */
4709 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4710 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004711 if (ctx.command->argv /* word [word]{... - non-special */
4712 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004713 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004714 || (next != ';' /* }; - special */
4715 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004716 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004717 && next != '&' /* }& and }&& ... - special */
4718 && next != '|' /* }|| ... - special */
4719 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004720 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004721 ) {
4722 /* They are not special, skip "{}" */
4723 is_special += 2;
4724 }
4725 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004726 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004727
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004728 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004729 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004730 o_addQchr(&dest, ch);
4731 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4732 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004733 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004734 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004735 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004736 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004737 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004738 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004739 continue;
4740 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004741
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004742 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004743 if (done_word(&dest, &ctx)) {
4744 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004745 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004746 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004747 /* Is this a case when newline is simply ignored?
4748 * Some examples:
4749 * "cmd | <newline> cmd ..."
4750 * "case ... in <newline> word) ..."
4751 */
4752 if (IS_NULL_CMD(ctx.command)
4753 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004754 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004755 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004756 * Without check #1, interactive shell
4757 * ignores even bare <newline>,
4758 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004759 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004760 * ps2> _ <=== wrong, should be ps1
4761 * Without check #2, "cmd & <newline>"
4762 * is similarly mistreated.
4763 * (BTW, this makes "cmd & cmd"
4764 * and "cmd && cmd" non-orthogonal.
4765 * Really, ask yourself, why
4766 * "cmd && <newline>" doesn't start
4767 * cmd but waits for more input?
4768 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004769 */
4770 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004771 if (pi->num_cmds != 0 /* check #1 */
4772 && pi->followup != PIPE_BG /* check #2 */
4773 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004774 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004775 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004776 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004777 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004778 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004779 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4780 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004781 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004782 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004783 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004784 heredoc_cnt = 0;
4785 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004786 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004787 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004788 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004789 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004790 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004791 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004792 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004793
4794 /* "cmd}" or "cmd }..." without semicolon or &:
4795 * } is an ordinary char in this case, even inside { cmd; }
4796 * Pathological example: { ""}; } should exec "}" cmd
4797 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004798 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004799 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004800 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004801 ) {
4802 goto ordinary_char;
4803 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004804 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4805 /* Generally, there should be semicolon: "cmd; }"
4806 * However, bash allows to omit it if "cmd" is
4807 * a group. Examples:
4808 * { { echo 1; } }
4809 * {(echo 1)}
4810 * { echo 0 >&2 | { echo 1; } }
4811 * { while false; do :; done }
4812 * { case a in b) ;; esac }
4813 */
4814 if (ctx.command->group)
4815 goto term_group;
4816 goto ordinary_char;
4817 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004818 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004819 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004820 goto skip_end_trigger;
4821 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004822 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004823 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004824 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004825 && (ch != ';' || heredoc_cnt == 0)
4826#if ENABLE_HUSH_CASE
4827 && (ch != ')'
4828 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004829 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004830 )
4831#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004832 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004833 if (heredoc_cnt) {
4834 /* This is technically valid:
4835 * { cat <<HERE; }; echo Ok
4836 * heredoc
4837 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004838 * HERE
4839 * but we don't support this.
4840 * We require heredoc to be in enclosing {}/(),
4841 * if any.
4842 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004843 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004844 goto parse_error;
4845 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004846 if (done_word(&dest, &ctx)) {
4847 goto parse_error;
4848 }
4849 done_pipe(&ctx, PIPE_SEQ);
4850 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004851 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004852 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004853 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004854 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004855 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004856 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004857#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004858 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004859 if (pstring)
4860 *pstring = ctx.as_string.data;
4861 else
4862 o_free_unsafe(&ctx.as_string);
4863#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004864 debug_leave();
4865 debug_printf_parse("parse_stream return %p: "
4866 "end_trigger char found\n",
4867 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004868 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004869 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004870 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004871 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004872 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004873 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004874
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004875 /* Catch <, > before deciding whether this word is
4876 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4877 switch (ch) {
4878 case '>':
4879 redir_fd = redirect_opt_num(&dest);
4880 if (done_word(&dest, &ctx)) {
4881 goto parse_error;
4882 }
4883 redir_style = REDIRECT_OVERWRITE;
4884 if (next == '>') {
4885 redir_style = REDIRECT_APPEND;
4886 ch = i_getch(input);
4887 nommu_addchr(&ctx.as_string, ch);
4888 }
4889#if 0
4890 else if (next == '(') {
4891 syntax_error(">(process) not supported");
4892 goto parse_error;
4893 }
4894#endif
4895 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4896 goto parse_error;
4897 continue; /* back to top of while (1) */
4898 case '<':
4899 redir_fd = redirect_opt_num(&dest);
4900 if (done_word(&dest, &ctx)) {
4901 goto parse_error;
4902 }
4903 redir_style = REDIRECT_INPUT;
4904 if (next == '<') {
4905 redir_style = REDIRECT_HEREDOC;
4906 heredoc_cnt++;
4907 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4908 ch = i_getch(input);
4909 nommu_addchr(&ctx.as_string, ch);
4910 } else if (next == '>') {
4911 redir_style = REDIRECT_IO;
4912 ch = i_getch(input);
4913 nommu_addchr(&ctx.as_string, ch);
4914 }
4915#if 0
4916 else if (next == '(') {
4917 syntax_error("<(process) not supported");
4918 goto parse_error;
4919 }
4920#endif
4921 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4922 goto parse_error;
4923 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004924 case '#':
4925 if (dest.length == 0 && !dest.has_quoted_part) {
4926 /* skip "#comment" */
4927 while (1) {
4928 ch = i_peek(input);
4929 if (ch == EOF || ch == '\n')
4930 break;
4931 i_getch(input);
4932 /* note: we do not add it to &ctx.as_string */
4933 }
4934 nommu_addchr(&ctx.as_string, '\n');
4935 continue; /* back to top of while (1) */
4936 }
4937 break;
4938 case '\\':
4939 if (next == '\n') {
4940 /* It's "\<newline>" */
4941#if !BB_MMU
4942 /* Remove trailing '\' from ctx.as_string */
4943 ctx.as_string.data[--ctx.as_string.length] = '\0';
4944#endif
4945 ch = i_getch(input); /* eat it */
4946 continue; /* back to top of while (1) */
4947 }
4948 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004949 }
4950
4951 if (dest.o_assignment == MAYBE_ASSIGNMENT
4952 /* check that we are not in word in "a=1 2>word b=1": */
4953 && !ctx.pending_redirect
4954 ) {
4955 /* ch is a special char and thus this word
4956 * cannot be an assignment */
4957 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004958 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004959 }
4960
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004961 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4962
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004963 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004964 case '#': /* non-comment #: "echo a#b" etc */
4965 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004966 break;
4967 case '\\':
4968 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004969 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004970 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004971 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004972 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004973 /* note: ch != '\n' (that case does not reach this place) */
4974 o_addchr(&dest, '\\');
4975 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4976 o_addchr(&dest, ch);
4977 nommu_addchr(&ctx.as_string, ch);
4978 /* Example: echo Hello \2>file
4979 * we need to know that word 2 is quoted */
4980 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004981 break;
4982 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004983 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004984 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004985 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004986 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004987 }
Eric Andersen25f27032001-04-26 23:22:31 +00004988 break;
4989 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004990 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004991 if (next == '\'' && !ctx.pending_redirect) {
4992 insert_empty_quoted_str_marker:
4993 nommu_addchr(&ctx.as_string, next);
4994 i_getch(input); /* eat second ' */
4995 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4996 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4997 } else {
4998 while (1) {
4999 ch = i_getch(input);
5000 if (ch == EOF) {
5001 syntax_error_unterm_ch('\'');
5002 goto parse_error;
5003 }
5004 nommu_addchr(&ctx.as_string, ch);
5005 if (ch == '\'')
5006 break;
5007 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005008 }
Eric Andersen25f27032001-04-26 23:22:31 +00005009 }
Eric Andersen25f27032001-04-26 23:22:31 +00005010 break;
5011 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005012 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005013 if (next == '"' && !ctx.pending_redirect)
5014 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005015 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005016 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005017 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005018 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005019 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00005020 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005021#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005022 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005023 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005024
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005025 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5026 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02005027 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005028 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5029 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005030# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005031 o_addstr(&ctx.as_string, dest.data + pos);
5032 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005033# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005034 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5035 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005036 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005037 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005038#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005039 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005040#if ENABLE_HUSH_CASE
5041 case_semi:
5042#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005043 if (done_word(&dest, &ctx)) {
5044 goto parse_error;
5045 }
5046 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005047#if ENABLE_HUSH_CASE
5048 /* Eat multiple semicolons, detect
5049 * whether it means something special */
5050 while (1) {
5051 ch = i_peek(input);
5052 if (ch != ';')
5053 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005054 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005055 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005056 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005057 ctx.ctx_dsemicolon = 1;
5058 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005059 break;
5060 }
5061 }
5062#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005063 new_cmd:
5064 /* We just finished a cmd. New one may start
5065 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005066 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005067 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00005068 break;
5069 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005070 if (done_word(&dest, &ctx)) {
5071 goto parse_error;
5072 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005073 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005074 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005075 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005076 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005077 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005078 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005079 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005080 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005081 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005082 if (done_word(&dest, &ctx)) {
5083 goto parse_error;
5084 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005085#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005086 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005087 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005088#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005089 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005090 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005091 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005092 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005093 } else {
5094 /* we could pick up a file descriptor choice here
5095 * with redirect_opt_num(), but bash doesn't do it.
5096 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005097 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005098 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005099 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005100 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005101#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005102 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005103 if (ctx.ctx_res_w == RES_MATCH
5104 && ctx.command->argv == NULL /* not (word|(... */
5105 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005106 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005107 ) {
5108 continue;
5109 }
5110#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005111 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005112 if (parse_group(&dest, &ctx, input, ch) != 0) {
5113 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005114 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005115 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005116 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005117#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005118 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005119 goto case_semi;
5120#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005121 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005122 /* proper use of this character is caught by end_trigger:
5123 * if we see {, we call parse_group(..., end_trigger='}')
5124 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005125 syntax_error_unexpected_ch(ch);
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005126 G.last_exitcode = 2;
5127 goto parse_error1;
Eric Andersen25f27032001-04-26 23:22:31 +00005128 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005129 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005130 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005131 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005132 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005133
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005134 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005135 G.last_exitcode = 1;
5136 parse_error1:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005137 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005138 struct parse_context *pctx;
5139 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005140
5141 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005142 * Sample for finding leaks on syntax error recovery path.
5143 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005144 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005145 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005146 * while if (true | { true;}); then echo ok; fi; do break; done
5147 * 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 +00005148 */
5149 pctx = &ctx;
5150 do {
5151 /* Update pipe/command counts,
5152 * otherwise freeing may miss some */
5153 done_pipe(pctx, PIPE_SEQ);
5154 debug_printf_clean("freeing list %p from ctx %p\n",
5155 pctx->list_head, pctx);
5156 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005157 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005158 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005159#if !BB_MMU
5160 o_free_unsafe(&pctx->as_string);
5161#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005162 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005163 if (pctx != &ctx) {
5164 free(pctx);
5165 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005166 IF_HAS_KEYWORDS(pctx = p2;)
5167 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005168
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005169 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005170#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005171 if (pstring)
5172 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005173#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005174 debug_leave();
5175 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005176 }
Eric Andersen25f27032001-04-26 23:22:31 +00005177}
5178
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005179
5180/*** Execution routines ***/
5181
5182/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005183#if !ENABLE_HUSH_BASH_COMPAT
5184/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5185#define expand_string_to_string(str, do_unbackslash) \
5186 expand_string_to_string(str)
5187#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005188static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005189#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005190static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005191#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005192
5193/* expand_strvec_to_strvec() takes a list of strings, expands
5194 * all variable references within and returns a pointer to
5195 * a list of expanded strings, possibly with larger number
5196 * of strings. (Think VAR="a b"; echo $VAR).
5197 * This new list is allocated as a single malloc block.
5198 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005199 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005200 * Caller can deallocate entire list by single free(list). */
5201
Denys Vlasenko238081f2010-10-03 14:26:26 +02005202/* A horde of its helpers come first: */
5203
5204static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5205{
5206 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005207 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005208
Denys Vlasenko9e800222010-10-03 14:28:04 +02005209#if ENABLE_HUSH_BRACE_EXPANSION
5210 if (c == '{' || c == '}') {
5211 /* { -> \{, } -> \} */
5212 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005213 /* And now we want to add { or } and continue:
5214 * o_addchr(o, c);
5215 * continue;
5216 * luckily, just falling throught achieves this.
5217 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005218 }
5219#endif
5220 o_addchr(o, c);
5221 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005222 /* \z -> \\\z; \<eol> -> \\<eol> */
5223 o_addchr(o, '\\');
5224 if (len) {
5225 len--;
5226 o_addchr(o, '\\');
5227 o_addchr(o, *str++);
5228 }
5229 }
5230 }
5231}
5232
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005233/* Store given string, finalizing the word and starting new one whenever
5234 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005235 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5236 * Return in *ended_with_ifs:
5237 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5238 */
5239static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005240{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005241 int last_is_ifs = 0;
5242
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005243 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005244 int word_len;
5245
5246 if (!*str) /* EOL - do not finalize word */
5247 break;
5248 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005249 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005250 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005251 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005252 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005253 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005254 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005255 * Example: "v='\*'; echo b$v" prints "b\*"
5256 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005257 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005258 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005259 /*/ Why can't we do it easier? */
5260 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5261 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5262 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005263 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005264 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005265 if (!*str) /* EOL - do not finalize word */
5266 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005267 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005268
5269 /* We know str here points to at least one IFS char */
5270 last_is_ifs = 1;
5271 str += strspn(str, G.ifs); /* skip IFS chars */
5272 if (!*str) /* EOL - do not finalize word */
5273 break;
5274
5275 /* Start new word... but not always! */
5276 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005277 if (output->has_quoted_part
5278 /* Case "v=' a'; echo $v":
5279 * here nothing precedes the space in $v expansion,
5280 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005281 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005282 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005283 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005284 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005285 o_addchr(output, '\0');
5286 debug_print_list("expand_on_ifs", output, n);
5287 n = o_save_ptr(output, n);
5288 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005289 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005290
5291 if (ended_with_ifs)
5292 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005293 debug_print_list("expand_on_ifs[1]", output, n);
5294 return n;
5295}
5296
5297/* Helper to expand $((...)) and heredoc body. These act as if
5298 * they are in double quotes, with the exception that they are not :).
5299 * Just the rules are similar: "expand only $var and `cmd`"
5300 *
5301 * Returns malloced string.
5302 * As an optimization, we return NULL if expansion is not needed.
5303 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005304#if !ENABLE_HUSH_BASH_COMPAT
5305/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5306#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5307 encode_then_expand_string(str)
5308#endif
5309static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005310{
5311 char *exp_str;
5312 struct in_str input;
5313 o_string dest = NULL_O_STRING;
5314
5315 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005316 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005317#if ENABLE_HUSH_TICK
5318 && !strchr(str, '`')
5319#endif
5320 ) {
5321 return NULL;
5322 }
5323
5324 /* We need to expand. Example:
5325 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5326 */
5327 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005328 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005329//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005330 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005331 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005332 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5333 o_free_unsafe(&dest);
5334 return exp_str;
5335}
5336
Denys Vlasenko0b883582016-12-23 16:49:07 +01005337#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005338static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005339{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005340 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005341 arith_t res;
5342 char *exp_str;
5343
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005344 math_state.lookupvar = get_local_var_value;
5345 math_state.setvar = set_local_var_from_halves;
5346 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005347 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005348 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005349 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005350 if (errmsg_p)
5351 *errmsg_p = math_state.errmsg;
5352 if (math_state.errmsg)
5353 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005354 return res;
5355}
5356#endif
5357
5358#if ENABLE_HUSH_BASH_COMPAT
5359/* ${var/[/]pattern[/repl]} helpers */
5360static char *strstr_pattern(char *val, const char *pattern, int *size)
5361{
5362 while (1) {
5363 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5364 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5365 if (end) {
5366 *size = end - val;
5367 return val;
5368 }
5369 if (*val == '\0')
5370 return NULL;
5371 /* Optimization: if "*pat" did not match the start of "string",
5372 * we know that "tring", "ring" etc will not match too:
5373 */
5374 if (pattern[0] == '*')
5375 return NULL;
5376 val++;
5377 }
5378}
5379static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5380{
5381 char *result = NULL;
5382 unsigned res_len = 0;
5383 unsigned repl_len = strlen(repl);
5384
5385 while (1) {
5386 int size;
5387 char *s = strstr_pattern(val, pattern, &size);
5388 if (!s)
5389 break;
5390
5391 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5392 memcpy(result + res_len, val, s - val);
5393 res_len += s - val;
5394 strcpy(result + res_len, repl);
5395 res_len += repl_len;
5396 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5397
5398 val = s + size;
5399 if (exp_op == '/')
5400 break;
5401 }
5402 if (val[0] && result) {
5403 result = xrealloc(result, res_len + strlen(val) + 1);
5404 strcpy(result + res_len, val);
5405 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5406 }
5407 debug_printf_varexp("result:'%s'\n", result);
5408 return result;
5409}
5410#endif
5411
5412/* Helper:
5413 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5414 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005415static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005416{
5417 const char *val = NULL;
5418 char *to_be_freed = NULL;
5419 char *p = *pp;
5420 char *var;
5421 char first_char;
5422 char exp_op;
5423 char exp_save = exp_save; /* for compiler */
5424 char *exp_saveptr; /* points to expansion operator */
5425 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005426 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005427
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005428 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005429 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005430 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005431 arg0 = arg[0];
5432 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005433 exp_op = 0;
5434
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005435 if (first_char == '#' /* ${#... */
5436 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5437 ) {
5438 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005439 var++;
5440 exp_op = 'L';
5441 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005442 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005443 if (exp_saveptr /* if 2nd char is one of expansion operators */
5444 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5445 ) {
5446 /* ${?:0}, ${#[:]%0} etc */
5447 exp_saveptr = var + 1;
5448 } else {
5449 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5450 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5451 }
5452 exp_op = exp_save = *exp_saveptr;
5453 if (exp_op) {
5454 exp_word = exp_saveptr + 1;
5455 if (exp_op == ':') {
5456 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005457//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005458 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005459 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005460 ) {
5461 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5462 exp_op = ':';
5463 exp_word--;
5464 }
5465 }
5466 *exp_saveptr = '\0';
5467 } /* else: it's not an expansion op, but bare ${var} */
5468 }
5469
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005470 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005471 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005472 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005473 int n = xatoi_positive(var);
5474 if (n < G.global_argc)
5475 val = G.global_argv[n];
5476 /* else val remains NULL: $N with too big N */
5477 } else {
5478 switch (var[0]) {
5479 case '$': /* pid */
5480 val = utoa(G.root_pid);
5481 break;
5482 case '!': /* bg pid */
5483 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5484 break;
5485 case '?': /* exitcode */
5486 val = utoa(G.last_exitcode);
5487 break;
5488 case '#': /* argc */
5489 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5490 break;
5491 default:
5492 val = get_local_var_value(var);
5493 }
5494 }
5495
5496 /* Handle any expansions */
5497 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005498 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005499 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005500 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005501 debug_printf_expand("%s\n", val);
5502 } else if (exp_op) {
5503 if (exp_op == '%' || exp_op == '#') {
5504 /* Standard-mandated substring removal ops:
5505 * ${parameter%word} - remove smallest suffix pattern
5506 * ${parameter%%word} - remove largest suffix pattern
5507 * ${parameter#word} - remove smallest prefix pattern
5508 * ${parameter##word} - remove largest prefix pattern
5509 *
5510 * Word is expanded to produce a glob pattern.
5511 * Then var's value is matched to it and matching part removed.
5512 */
5513 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005514 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005515 char *exp_exp_word;
5516 char *loc;
5517 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005518 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005519 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005520 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005521 if (exp_exp_word)
5522 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005523 /* HACK ALERT. We depend here on the fact that
5524 * G.global_argv and results of utoa and get_local_var_value
5525 * are actually in writable memory:
5526 * scan_and_match momentarily stores NULs there. */
5527 t = (char*)val;
5528 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005529 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005530 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005531 free(exp_exp_word);
5532 if (loc) { /* match was found */
5533 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005534 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005535 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005536 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005537 }
5538 }
5539 }
5540#if ENABLE_HUSH_BASH_COMPAT
5541 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005542 /* It's ${var/[/]pattern[/repl]} thing.
5543 * Note that in encoded form it has TWO parts:
5544 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005545 * and if // is used, it is encoded as \:
5546 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005547 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005548 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005549 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005550 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005551 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005552 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005553 * by the usual expansion rules:
5554 * >az; >bz;
5555 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5556 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5557 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5558 * v='a bz'; echo ${v/a*z/\z} prints "z"
5559 * (note that a*z _pattern_ is never globbed!)
5560 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005561 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005562 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005563 if (!pattern)
5564 pattern = xstrdup(exp_word);
5565 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5566 *p++ = SPECIAL_VAR_SYMBOL;
5567 exp_word = p;
5568 p = strchr(p, SPECIAL_VAR_SYMBOL);
5569 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005570 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005571 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5572 /* HACK ALERT. We depend here on the fact that
5573 * G.global_argv and results of utoa and get_local_var_value
5574 * are actually in writable memory:
5575 * replace_pattern momentarily stores NULs there. */
5576 t = (char*)val;
5577 to_be_freed = replace_pattern(t,
5578 pattern,
5579 (repl ? repl : exp_word),
5580 exp_op);
5581 if (to_be_freed) /* at least one replace happened */
5582 val = to_be_freed;
5583 free(pattern);
5584 free(repl);
5585 }
5586 }
5587#endif
5588 else if (exp_op == ':') {
Denys Vlasenko0b883582016-12-23 16:49:07 +01005589#if ENABLE_HUSH_BASH_COMPAT && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005590 /* It's ${var:N[:M]} bashism.
5591 * Note that in encoded form it has TWO parts:
5592 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5593 */
5594 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005595 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005596
Denys Vlasenko063847d2010-09-15 13:33:02 +02005597 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5598 if (errmsg)
5599 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005600 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5601 *p++ = SPECIAL_VAR_SYMBOL;
5602 exp_word = p;
5603 p = strchr(p, SPECIAL_VAR_SYMBOL);
5604 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005605 len = expand_and_evaluate_arith(exp_word, &errmsg);
5606 if (errmsg)
5607 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005608 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005609 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005610 if (beg < 0) /* bash compat */
5611 beg = 0;
5612 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005613 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005614 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005615 val = NULL;
5616 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005617 /* Paranoia. What if user entered 9999999999999
5618 * which fits in arith_t but not int? */
5619 if (len >= INT_MAX)
5620 len = INT_MAX;
5621 val = to_be_freed = xstrndup(val + beg, len);
5622 }
5623 debug_printf_varexp("val:'%s'\n", val);
5624 } else
5625#endif
5626 {
5627 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005628 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005629 }
5630 } else { /* one of "-=+?" */
5631 /* Standard-mandated substitution ops:
5632 * ${var?word} - indicate error if unset
5633 * If var is unset, word (or a message indicating it is unset
5634 * if word is null) is written to standard error
5635 * and the shell exits with a non-zero exit status.
5636 * Otherwise, the value of var is substituted.
5637 * ${var-word} - use default value
5638 * If var is unset, word is substituted.
5639 * ${var=word} - assign and use default value
5640 * If var is unset, word is assigned to var.
5641 * In all cases, final value of var is substituted.
5642 * ${var+word} - use alternative value
5643 * If var is unset, null is substituted.
5644 * Otherwise, word is substituted.
5645 *
5646 * Word is subjected to tilde expansion, parameter expansion,
5647 * command substitution, and arithmetic expansion.
5648 * If word is not needed, it is not expanded.
5649 *
5650 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5651 * but also treat null var as if it is unset.
5652 */
5653 int use_word = (!val || ((exp_save == ':') && !val[0]));
5654 if (exp_op == '+')
5655 use_word = !use_word;
5656 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5657 (exp_save == ':') ? "true" : "false", use_word);
5658 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005659 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005660 if (to_be_freed)
5661 exp_word = to_be_freed;
5662 if (exp_op == '?') {
5663 /* mimic bash message */
5664 die_if_script("%s: %s",
5665 var,
5666 exp_word[0] ? exp_word : "parameter null or not set"
5667 );
5668//TODO: how interactive bash aborts expansion mid-command?
5669 } else {
5670 val = exp_word;
5671 }
5672
5673 if (exp_op == '=') {
5674 /* ${var=[word]} or ${var:=[word]} */
5675 if (isdigit(var[0]) || var[0] == '#') {
5676 /* mimic bash message */
5677 die_if_script("$%s: cannot assign in this way", var);
5678 val = NULL;
5679 } else {
5680 char *new_var = xasprintf("%s=%s", var, val);
5681 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5682 }
5683 }
5684 }
5685 } /* one of "-=+?" */
5686
5687 *exp_saveptr = exp_save;
5688 } /* if (exp_op) */
5689
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005690 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005691
5692 *pp = p;
5693 *to_be_freed_pp = to_be_freed;
5694 return val;
5695}
5696
5697/* Expand all variable references in given string, adding words to list[]
5698 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5699 * to be filled). This routine is extremely tricky: has to deal with
5700 * variables/parameters with whitespace, $* and $@, and constructs like
5701 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005702static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005703{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005704 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005705 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005706 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005707 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005708 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005709 char *p;
5710
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005711 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5712 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005713 debug_print_list("expand_vars_to_list", output, n);
5714 n = o_save_ptr(output, n);
5715 debug_print_list("expand_vars_to_list[0]", output, n);
5716
5717 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5718 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005719 char *to_be_freed = NULL;
5720 const char *val = NULL;
5721#if ENABLE_HUSH_TICK
5722 o_string subst_result = NULL_O_STRING;
5723#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01005724#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005725 char arith_buf[sizeof(arith_t)*3 + 2];
5726#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005727
5728 if (ended_in_ifs) {
5729 o_addchr(output, '\0');
5730 n = o_save_ptr(output, n);
5731 ended_in_ifs = 0;
5732 }
5733
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005734 o_addblock(output, arg, p - arg);
5735 debug_print_list("expand_vars_to_list[1]", output, n);
5736 arg = ++p;
5737 p = strchr(p, SPECIAL_VAR_SYMBOL);
5738
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005739 /* Fetch special var name (if it is indeed one of them)
5740 * and quote bit, force the bit on if singleword expansion -
5741 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005742 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005743
5744 /* Is this variable quoted and thus expansion can't be null?
5745 * "$@" is special. Even if quoted, it can still
5746 * expand to nothing (not even an empty string),
5747 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005748 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005749 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005750
5751 switch (first_ch & 0x7f) {
5752 /* Highest bit in first_ch indicates that var is double-quoted */
5753 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005754 case '@': {
5755 int i;
5756 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005757 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005758 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005759 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005760 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005761 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005762 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005763 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5764 if (G.global_argv[i++][0] && G.global_argv[i]) {
5765 /* this argv[] is not empty and not last:
5766 * put terminating NUL, start new word */
5767 o_addchr(output, '\0');
5768 debug_print_list("expand_vars_to_list[2]", output, n);
5769 n = o_save_ptr(output, n);
5770 debug_print_list("expand_vars_to_list[3]", output, n);
5771 }
5772 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005773 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005774 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005775 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005776 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005777 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005778 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005779 while (1) {
5780 o_addQstr(output, G.global_argv[i]);
5781 if (++i >= G.global_argc)
5782 break;
5783 o_addchr(output, '\0');
5784 debug_print_list("expand_vars_to_list[4]", output, n);
5785 n = o_save_ptr(output, n);
5786 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005787 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005788 while (1) {
5789 o_addQstr(output, G.global_argv[i]);
5790 if (!G.global_argv[++i])
5791 break;
5792 if (G.ifs[0])
5793 o_addchr(output, G.ifs[0]);
5794 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005795 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005796 }
5797 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005798 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005799 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5800 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005801 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005802 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005803 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005804 break;
5805#if ENABLE_HUSH_TICK
5806 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005807 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005808 arg++;
5809 /* Can't just stuff it into output o_string,
5810 * expanded result may need to be globbed
5811 * and $IFS-splitted */
5812 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5813 G.last_exitcode = process_command_subs(&subst_result, arg);
5814 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5815 val = subst_result.data;
5816 goto store_val;
5817#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01005818#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005819 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5820 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005821
5822 arg++; /* skip '+' */
5823 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5824 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005825 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005826 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5827 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005828 val = arith_buf;
5829 break;
5830 }
5831#endif
5832 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005833 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005834 IF_HUSH_TICK(store_val:)
5835 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005836 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5837 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005838 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005839 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005840 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005841 }
5842 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005843 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005844 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5845 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005846 }
5847 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005848 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5849
5850 if (val && val[0]) {
5851 o_addQstr(output, val);
5852 }
5853 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005854
5855 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5856 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005857 if (*p != SPECIAL_VAR_SYMBOL)
5858 *p = SPECIAL_VAR_SYMBOL;
5859
5860#if ENABLE_HUSH_TICK
5861 o_free(&subst_result);
5862#endif
5863 arg = ++p;
5864 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5865
5866 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005867 if (ended_in_ifs) {
5868 o_addchr(output, '\0');
5869 n = o_save_ptr(output, n);
5870 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005871 debug_print_list("expand_vars_to_list[a]", output, n);
5872 /* this part is literal, and it was already pre-quoted
5873 * if needed (much earlier), do not use o_addQstr here! */
5874 o_addstr_with_NUL(output, arg);
5875 debug_print_list("expand_vars_to_list[b]", output, n);
5876 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005877 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005878 ) {
5879 n--;
5880 /* allow to reuse list[n] later without re-growth */
5881 output->has_empty_slot = 1;
5882 } else {
5883 o_addchr(output, '\0');
5884 }
5885
5886 return n;
5887}
5888
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005889static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005890{
5891 int n;
5892 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005893 o_string output = NULL_O_STRING;
5894
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005895 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005896
5897 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005898 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005899 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005900 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005901 }
5902 debug_print_list("expand_variables", &output, n);
5903
5904 /* output.data (malloced in one block) gets returned in "list" */
5905 list = o_finalize_list(&output, n);
5906 debug_print_strings("expand_variables[1]", list);
5907 return list;
5908}
5909
5910static char **expand_strvec_to_strvec(char **argv)
5911{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005912 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005913}
5914
5915#if ENABLE_HUSH_BASH_COMPAT
5916static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5917{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005918 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005919}
5920#endif
5921
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005922/* Used for expansion of right hand of assignments,
5923 * $((...)), heredocs, variable espansion parts.
5924 *
5925 * NB: should NOT do globbing!
5926 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5927 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005928static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005929{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005930#if !ENABLE_HUSH_BASH_COMPAT
5931 const int do_unbackslash = 1;
5932#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005933 char *argv[2], **list;
5934
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005935 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005936 /* This is generally an optimization, but it also
5937 * handles "", which otherwise trips over !list[0] check below.
5938 * (is this ever happens that we actually get str="" here?)
5939 */
5940 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5941 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005942 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005943 return xstrdup(str);
5944 }
5945
5946 argv[0] = (char*)str;
5947 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005948 list = expand_variables(argv, do_unbackslash
5949 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5950 : EXP_FLAG_SINGLEWORD
5951 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005952 if (HUSH_DEBUG)
5953 if (!list[0] || list[1])
5954 bb_error_msg_and_die("BUG in varexp2");
5955 /* actually, just move string 2*sizeof(char*) bytes back */
5956 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005957 if (do_unbackslash)
5958 unbackslash((char*)list);
5959 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005960 return (char*)list;
5961}
5962
5963/* Used for "eval" builtin */
5964static char* expand_strvec_to_string(char **argv)
5965{
5966 char **list;
5967
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005968 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005969 /* Convert all NULs to spaces */
5970 if (list[0]) {
5971 int n = 1;
5972 while (list[n]) {
5973 if (HUSH_DEBUG)
5974 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5975 bb_error_msg_and_die("BUG in varexp3");
5976 /* bash uses ' ' regardless of $IFS contents */
5977 list[n][-1] = ' ';
5978 n++;
5979 }
5980 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02005981 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005982 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5983 return (char*)list;
5984}
5985
5986static char **expand_assignments(char **argv, int count)
5987{
5988 int i;
5989 char **p;
5990
5991 G.expanded_assignments = p = NULL;
5992 /* Expand assignments into one string each */
5993 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005994 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005995 }
5996 G.expanded_assignments = NULL;
5997 return p;
5998}
5999
6000
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006001static void switch_off_special_sigs(unsigned mask)
6002{
6003 unsigned sig = 0;
6004 while ((mask >>= 1) != 0) {
6005 sig++;
6006 if (!(mask & 1))
6007 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006008#if ENABLE_HUSH_TRAP
6009 if (G_traps) {
6010 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006011 /* trap is '', has to remain SIG_IGN */
6012 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006013 free(G_traps[sig]);
6014 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006015 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006016#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006017 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006018 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006019 }
6020}
6021
Denys Vlasenkob347df92011-08-09 22:49:15 +02006022#if BB_MMU
6023/* never called */
6024void re_execute_shell(char ***to_free, const char *s,
6025 char *g_argv0, char **g_argv,
6026 char **builtin_argv) NORETURN;
6027
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006028static void reset_traps_to_defaults(void)
6029{
6030 /* This function is always called in a child shell
6031 * after fork (not vfork, NOMMU doesn't use this function).
6032 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006033 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006034 unsigned mask;
6035
6036 /* Child shells are not interactive.
6037 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6038 * Testcase: (while :; do :; done) + ^Z should background.
6039 * Same goes for SIGTERM, SIGHUP, SIGINT.
6040 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006041 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006042 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006043 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006044
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006045 /* Switch off special sigs */
6046 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006047# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006048 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006049# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006050 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006051 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6052 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006053
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006054# if ENABLE_HUSH_TRAP
6055 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006056 return;
6057
6058 /* Reset all sigs to default except ones with empty traps */
6059 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006060 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006061 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006062 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006063 continue; /* empty trap: has to remain SIG_IGN */
6064 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006065 free(G_traps[sig]);
6066 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006067 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006068 if (sig == 0)
6069 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006070 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006071 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006072# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006073}
6074
6075#else /* !BB_MMU */
6076
6077static void re_execute_shell(char ***to_free, const char *s,
6078 char *g_argv0, char **g_argv,
6079 char **builtin_argv) NORETURN;
6080static void re_execute_shell(char ***to_free, const char *s,
6081 char *g_argv0, char **g_argv,
6082 char **builtin_argv)
6083{
6084# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6085 /* delims + 2 * (number of bytes in printed hex numbers) */
6086 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6087 char *heredoc_argv[4];
6088 struct variable *cur;
6089# if ENABLE_HUSH_FUNCTIONS
6090 struct function *funcp;
6091# endif
6092 char **argv, **pp;
6093 unsigned cnt;
6094 unsigned long long empty_trap_mask;
6095
6096 if (!g_argv0) { /* heredoc */
6097 argv = heredoc_argv;
6098 argv[0] = (char *) G.argv0_for_re_execing;
6099 argv[1] = (char *) "-<";
6100 argv[2] = (char *) s;
6101 argv[3] = NULL;
6102 pp = &argv[3]; /* used as pointer to empty environment */
6103 goto do_exec;
6104 }
6105
6106 cnt = 0;
6107 pp = builtin_argv;
6108 if (pp) while (*pp++)
6109 cnt++;
6110
6111 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006112 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006113 int sig;
6114 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006115 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006116 empty_trap_mask |= 1LL << sig;
6117 }
6118 }
6119
6120 sprintf(param_buf, NOMMU_HACK_FMT
6121 , (unsigned) G.root_pid
6122 , (unsigned) G.root_ppid
6123 , (unsigned) G.last_bg_pid
6124 , (unsigned) G.last_exitcode
6125 , cnt
6126 , empty_trap_mask
6127 IF_HUSH_LOOPS(, G.depth_of_loop)
6128 );
6129# undef NOMMU_HACK_FMT
6130 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6131 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6132 */
6133 cnt += 6;
6134 for (cur = G.top_var; cur; cur = cur->next) {
6135 if (!cur->flg_export || cur->flg_read_only)
6136 cnt += 2;
6137 }
6138# if ENABLE_HUSH_FUNCTIONS
6139 for (funcp = G.top_func; funcp; funcp = funcp->next)
6140 cnt += 3;
6141# endif
6142 pp = g_argv;
6143 while (*pp++)
6144 cnt++;
6145 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6146 *pp++ = (char *) G.argv0_for_re_execing;
6147 *pp++ = param_buf;
6148 for (cur = G.top_var; cur; cur = cur->next) {
6149 if (strcmp(cur->varstr, hush_version_str) == 0)
6150 continue;
6151 if (cur->flg_read_only) {
6152 *pp++ = (char *) "-R";
6153 *pp++ = cur->varstr;
6154 } else if (!cur->flg_export) {
6155 *pp++ = (char *) "-V";
6156 *pp++ = cur->varstr;
6157 }
6158 }
6159# if ENABLE_HUSH_FUNCTIONS
6160 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6161 *pp++ = (char *) "-F";
6162 *pp++ = funcp->name;
6163 *pp++ = funcp->body_as_string;
6164 }
6165# endif
6166 /* We can pass activated traps here. Say, -Tnn:trap_string
6167 *
6168 * However, POSIX says that subshells reset signals with traps
6169 * to SIG_DFL.
6170 * I tested bash-3.2 and it not only does that with true subshells
6171 * of the form ( list ), but with any forked children shells.
6172 * I set trap "echo W" WINCH; and then tried:
6173 *
6174 * { echo 1; sleep 20; echo 2; } &
6175 * while true; do echo 1; sleep 20; echo 2; break; done &
6176 * true | { echo 1; sleep 20; echo 2; } | cat
6177 *
6178 * In all these cases sending SIGWINCH to the child shell
6179 * did not run the trap. If I add trap "echo V" WINCH;
6180 * _inside_ group (just before echo 1), it works.
6181 *
6182 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006183 */
6184 *pp++ = (char *) "-c";
6185 *pp++ = (char *) s;
6186 if (builtin_argv) {
6187 while (*++builtin_argv)
6188 *pp++ = *builtin_argv;
6189 *pp++ = (char *) "";
6190 }
6191 *pp++ = g_argv0;
6192 while (*g_argv)
6193 *pp++ = *g_argv++;
6194 /* *pp = NULL; - is already there */
6195 pp = environ;
6196
6197 do_exec:
6198 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006199 /* Don't propagate SIG_IGN to the child */
6200 if (SPECIAL_JOBSTOP_SIGS != 0)
6201 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006202 execve(bb_busybox_exec_path, argv, pp);
6203 /* Fallback. Useful for init=/bin/hush usage etc */
6204 if (argv[0][0] == '/')
6205 execve(argv[0], argv, pp);
6206 xfunc_error_retval = 127;
6207 bb_error_msg_and_die("can't re-execute the shell");
6208}
6209#endif /* !BB_MMU */
6210
6211
6212static int run_and_free_list(struct pipe *pi);
6213
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006214/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006215 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6216 * end_trigger controls how often we stop parsing
6217 * NUL: parse all, execute, return
6218 * ';': parse till ';' or newline, execute, repeat till EOF
6219 */
6220static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006221{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006222 /* Why we need empty flag?
6223 * An obscure corner case "false; ``; echo $?":
6224 * empty command in `` should still set $? to 0.
6225 * But we can't just set $? to 0 at the start,
6226 * this breaks "false; echo `echo $?`" case.
6227 */
6228 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006229 while (1) {
6230 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006231
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006232#if ENABLE_HUSH_INTERACTIVE
6233 if (end_trigger == ';')
6234 inp->promptmode = 0; /* PS1 */
6235#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006236 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006237 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6238 /* If we are in "big" script
6239 * (not in `cmd` or something similar)...
6240 */
6241 if (pipe_list == ERR_PTR && end_trigger == ';') {
6242 /* Discard cached input (rest of line) */
6243 int ch = inp->last_char;
6244 while (ch != EOF && ch != '\n') {
6245 //bb_error_msg("Discarded:'%c'", ch);
6246 ch = i_getch(inp);
6247 }
6248 /* Force prompt */
6249 inp->p = NULL;
6250 /* This stream isn't empty */
6251 empty = 0;
6252 continue;
6253 }
6254 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006255 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006256 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006257 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006258 debug_print_tree(pipe_list, 0);
6259 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6260 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006261 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006262 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006263 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006264 }
Eric Andersen25f27032001-04-26 23:22:31 +00006265}
6266
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006267static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006268{
6269 struct in_str input;
6270 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006271 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006272}
6273
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006274static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006275{
Eric Andersen25f27032001-04-26 23:22:31 +00006276 struct in_str input;
6277 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006278 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006279}
6280
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006281#if ENABLE_HUSH_TICK
6282static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6283{
6284 pid_t pid;
6285 int channel[2];
6286# if !BB_MMU
6287 char **to_free = NULL;
6288# endif
6289
6290 xpipe(channel);
6291 pid = BB_MMU ? xfork() : xvfork();
6292 if (pid == 0) { /* child */
6293 disable_restore_tty_pgrp_on_exit();
6294 /* Process substitution is not considered to be usual
6295 * 'command execution'.
6296 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6297 */
6298 bb_signals(0
6299 + (1 << SIGTSTP)
6300 + (1 << SIGTTIN)
6301 + (1 << SIGTTOU)
6302 , SIG_IGN);
6303 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6304 close(channel[0]); /* NB: close _first_, then move fd! */
6305 xmove_fd(channel[1], 1);
6306 /* Prevent it from trying to handle ctrl-z etc */
6307 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006308# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006309 /* Awful hack for `trap` or $(trap).
6310 *
6311 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6312 * contains an example where "trap" is executed in a subshell:
6313 *
6314 * save_traps=$(trap)
6315 * ...
6316 * eval "$save_traps"
6317 *
6318 * Standard does not say that "trap" in subshell shall print
6319 * parent shell's traps. It only says that its output
6320 * must have suitable form, but then, in the above example
6321 * (which is not supposed to be normative), it implies that.
6322 *
6323 * bash (and probably other shell) does implement it
6324 * (traps are reset to defaults, but "trap" still shows them),
6325 * but as a result, "trap" logic is hopelessly messed up:
6326 *
6327 * # trap
6328 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6329 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6330 * # true | trap <--- trap is in subshell - no output (ditto)
6331 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6332 * trap -- 'echo Ho' SIGWINCH
6333 * # echo `(trap)` <--- in subshell in subshell - output
6334 * trap -- 'echo Ho' SIGWINCH
6335 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6336 * trap -- 'echo Ho' SIGWINCH
6337 *
6338 * The rules when to forget and when to not forget traps
6339 * get really complex and nonsensical.
6340 *
6341 * Our solution: ONLY bare $(trap) or `trap` is special.
6342 */
6343 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006344 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006345 && skip_whitespace(s + 4)[0] == '\0'
6346 ) {
6347 static const char *const argv[] = { NULL, NULL };
6348 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006349 fflush_all(); /* important */
6350 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006351 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006352# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006353# if BB_MMU
6354 reset_traps_to_defaults();
6355 parse_and_run_string(s);
6356 _exit(G.last_exitcode);
6357# else
6358 /* We re-execute after vfork on NOMMU. This makes this script safe:
6359 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6360 * huge=`cat BIG` # was blocking here forever
6361 * echo OK
6362 */
6363 re_execute_shell(&to_free,
6364 s,
6365 G.global_argv[0],
6366 G.global_argv + 1,
6367 NULL);
6368# endif
6369 }
6370
6371 /* parent */
6372 *pid_p = pid;
6373# if ENABLE_HUSH_FAST
6374 G.count_SIGCHLD++;
6375//bb_error_msg("[%d] fork in generate_stream_from_string:"
6376// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6377// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6378# endif
6379 enable_restore_tty_pgrp_on_exit();
6380# if !BB_MMU
6381 free(to_free);
6382# endif
6383 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006384 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006385}
6386
6387/* Return code is exit status of the process that is run. */
6388static int process_command_subs(o_string *dest, const char *s)
6389{
6390 FILE *fp;
6391 struct in_str pipe_str;
6392 pid_t pid;
6393 int status, ch, eol_cnt;
6394
6395 fp = generate_stream_from_string(s, &pid);
6396
6397 /* Now send results of command back into original context */
6398 setup_file_in_str(&pipe_str, fp);
6399 eol_cnt = 0;
6400 while ((ch = i_getch(&pipe_str)) != EOF) {
6401 if (ch == '\n') {
6402 eol_cnt++;
6403 continue;
6404 }
6405 while (eol_cnt) {
6406 o_addchr(dest, '\n');
6407 eol_cnt--;
6408 }
6409 o_addQchr(dest, ch);
6410 }
6411
6412 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006413 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006414 /* We need to extract exitcode. Test case
6415 * "true; echo `sleep 1; false` $?"
6416 * should print 1 */
6417 safe_waitpid(pid, &status, 0);
6418 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6419 return WEXITSTATUS(status);
6420}
6421#endif /* ENABLE_HUSH_TICK */
6422
6423
6424static void setup_heredoc(struct redir_struct *redir)
6425{
6426 struct fd_pair pair;
6427 pid_t pid;
6428 int len, written;
6429 /* the _body_ of heredoc (misleading field name) */
6430 const char *heredoc = redir->rd_filename;
6431 char *expanded;
6432#if !BB_MMU
6433 char **to_free;
6434#endif
6435
6436 expanded = NULL;
6437 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006438 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006439 if (expanded)
6440 heredoc = expanded;
6441 }
6442 len = strlen(heredoc);
6443
6444 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6445 xpiped_pair(pair);
6446 xmove_fd(pair.rd, redir->rd_fd);
6447
6448 /* Try writing without forking. Newer kernels have
6449 * dynamically growing pipes. Must use non-blocking write! */
6450 ndelay_on(pair.wr);
6451 while (1) {
6452 written = write(pair.wr, heredoc, len);
6453 if (written <= 0)
6454 break;
6455 len -= written;
6456 if (len == 0) {
6457 close(pair.wr);
6458 free(expanded);
6459 return;
6460 }
6461 heredoc += written;
6462 }
6463 ndelay_off(pair.wr);
6464
6465 /* Okay, pipe buffer was not big enough */
6466 /* Note: we must not create a stray child (bastard? :)
6467 * for the unsuspecting parent process. Child creates a grandchild
6468 * and exits before parent execs the process which consumes heredoc
6469 * (that exec happens after we return from this function) */
6470#if !BB_MMU
6471 to_free = NULL;
6472#endif
6473 pid = xvfork();
6474 if (pid == 0) {
6475 /* child */
6476 disable_restore_tty_pgrp_on_exit();
6477 pid = BB_MMU ? xfork() : xvfork();
6478 if (pid != 0)
6479 _exit(0);
6480 /* grandchild */
6481 close(redir->rd_fd); /* read side of the pipe */
6482#if BB_MMU
6483 full_write(pair.wr, heredoc, len); /* may loop or block */
6484 _exit(0);
6485#else
6486 /* Delegate blocking writes to another process */
6487 xmove_fd(pair.wr, STDOUT_FILENO);
6488 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6489#endif
6490 }
6491 /* parent */
6492#if ENABLE_HUSH_FAST
6493 G.count_SIGCHLD++;
6494//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6495#endif
6496 enable_restore_tty_pgrp_on_exit();
6497#if !BB_MMU
6498 free(to_free);
6499#endif
6500 close(pair.wr);
6501 free(expanded);
6502 wait(NULL); /* wait till child has died */
6503}
6504
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006505/* fd: redirect wants this fd to be used (e.g. 3>file).
6506 * Move all conflicting internally used fds,
6507 * and remember them so that we can restore them later.
6508 */
6509static int save_fds_on_redirect(int fd, int squirrel[3])
6510{
6511 if (squirrel) {
6512 /* Handle redirects of fds 0,1,2 */
6513
6514 /* If we collide with an already moved stdio fd... */
6515 if (fd == squirrel[0]) {
6516 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6517 return 1;
6518 }
6519 if (fd == squirrel[1]) {
6520 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6521 return 1;
6522 }
6523 if (fd == squirrel[2]) {
6524 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6525 return 1;
6526 }
6527 /* If we are about to redirect stdio fd, and did not yet move it... */
6528 if (fd <= 2 && squirrel[fd] < 0) {
6529 /* We avoid taking stdio fds */
6530 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6531 if (squirrel[fd] < 0 && errno != EBADF)
6532 xfunc_die();
6533 return 0; /* "we did not close fd" */
6534 }
6535 }
6536
6537#if ENABLE_HUSH_INTERACTIVE
6538 if (fd != 0 && fd == G.interactive_fd) {
6539 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6540 return 1;
6541 }
6542#endif
6543
6544 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6545 * (1) Redirect in a forked child. No need to save FILEs' fds,
6546 * we aren't going to use them anymore, ok to trash.
6547 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6548 * but how are we doing to use them?
6549 * "fileno(fd) = new_fd" can't be done.
6550 */
6551 if (!squirrel)
6552 return 0;
6553
6554 return save_FILEs_on_redirect(fd);
6555}
6556
6557static void restore_redirects(int squirrel[3])
6558{
6559 int i, fd;
6560 for (i = 0; i <= 2; i++) {
6561 fd = squirrel[i];
6562 if (fd != -1) {
6563 /* We simply die on error */
6564 xmove_fd(fd, i);
6565 }
6566 }
6567
6568 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6569
6570 restore_redirected_FILEs();
6571}
6572
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006573/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6574 * and stderr if they are redirected. */
6575static int setup_redirects(struct command *prog, int squirrel[])
6576{
6577 int openfd, mode;
6578 struct redir_struct *redir;
6579
6580 for (redir = prog->redirects; redir; redir = redir->next) {
6581 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006582 /* "rd_fd<<HERE" case */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006583 save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006584 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6585 * of the heredoc */
6586 debug_printf_parse("set heredoc '%s'\n",
6587 redir->rd_filename);
6588 setup_heredoc(redir);
6589 continue;
6590 }
6591
6592 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006593 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006594 char *p;
6595 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02006596 /*
6597 * Examples:
6598 * "cmd >" (no filename)
6599 * "cmd > <file" (2nd redirect starts too early)
6600 */
6601 die_if_script("syntax error: %s", "invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006602 continue;
6603 }
6604 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006605 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006606 openfd = open_or_warn(p, mode);
6607 free(p);
6608 if (openfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006609 /* Error message from open_or_warn can be lost
6610 * if stderr has been redirected, but bash
6611 * and ash both lose it as well
6612 * (though zsh doesn't!)
6613 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006614 return 1;
6615 }
6616 } else {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006617 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006618 openfd = redir->rd_dup;
6619 }
6620
6621 if (openfd != redir->rd_fd) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006622 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006623 if (openfd == REDIRFD_CLOSE) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006624 /* "rd_fd >&-" means "close me" */
6625 if (!closed) {
6626 /* ^^^ optimization: saving may already
6627 * have closed it. If not... */
6628 close(redir->rd_fd);
6629 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006630 } else {
6631 xdup2(openfd, redir->rd_fd);
6632 if (redir->rd_dup == REDIRFD_TO_FILE)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006633 /* "rd_fd > FILE" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006634 close(openfd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006635 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006636 }
6637 }
6638 }
6639 return 0;
6640}
6641
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006642static char *find_in_path(const char *arg)
6643{
6644 char *ret = NULL;
6645 const char *PATH = get_local_var_value("PATH");
6646
6647 if (!PATH)
6648 return NULL;
6649
6650 while (1) {
6651 const char *end = strchrnul(PATH, ':');
6652 int sz = end - PATH; /* must be int! */
6653
6654 free(ret);
6655 if (sz != 0) {
6656 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6657 } else {
6658 /* We have xxx::yyyy in $PATH,
6659 * it means "use current dir" */
6660 ret = xstrdup(arg);
6661 }
6662 if (access(ret, F_OK) == 0)
6663 break;
6664
6665 if (*end == '\0') {
6666 free(ret);
6667 return NULL;
6668 }
6669 PATH = end + 1;
6670 }
6671
6672 return ret;
6673}
6674
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006675static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006676 const struct built_in_command *x,
6677 const struct built_in_command *end)
6678{
6679 while (x != end) {
6680 if (strcmp(name, x->b_cmd) != 0) {
6681 x++;
6682 continue;
6683 }
6684 debug_printf_exec("found builtin '%s'\n", name);
6685 return x;
6686 }
6687 return NULL;
6688}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006689static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006690{
6691 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6692}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006693static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006694{
6695 const struct built_in_command *x = find_builtin1(name);
6696 if (x)
6697 return x;
6698 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6699}
6700
6701#if ENABLE_HUSH_FUNCTIONS
6702static struct function **find_function_slot(const char *name)
6703{
6704 struct function **funcpp = &G.top_func;
6705 while (*funcpp) {
6706 if (strcmp(name, (*funcpp)->name) == 0) {
6707 break;
6708 }
6709 funcpp = &(*funcpp)->next;
6710 }
6711 return funcpp;
6712}
6713
6714static const struct function *find_function(const char *name)
6715{
6716 const struct function *funcp = *find_function_slot(name);
6717 if (funcp)
6718 debug_printf_exec("found function '%s'\n", name);
6719 return funcp;
6720}
6721
6722/* Note: takes ownership on name ptr */
6723static struct function *new_function(char *name)
6724{
6725 struct function **funcpp = find_function_slot(name);
6726 struct function *funcp = *funcpp;
6727
6728 if (funcp != NULL) {
6729 struct command *cmd = funcp->parent_cmd;
6730 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6731 if (!cmd) {
6732 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6733 free(funcp->name);
6734 /* Note: if !funcp->body, do not free body_as_string!
6735 * This is a special case of "-F name body" function:
6736 * body_as_string was not malloced! */
6737 if (funcp->body) {
6738 free_pipe_list(funcp->body);
6739# if !BB_MMU
6740 free(funcp->body_as_string);
6741# endif
6742 }
6743 } else {
6744 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6745 cmd->argv[0] = funcp->name;
6746 cmd->group = funcp->body;
6747# if !BB_MMU
6748 cmd->group_as_string = funcp->body_as_string;
6749# endif
6750 }
6751 } else {
6752 debug_printf_exec("remembering new function '%s'\n", name);
6753 funcp = *funcpp = xzalloc(sizeof(*funcp));
6754 /*funcp->next = NULL;*/
6755 }
6756
6757 funcp->name = name;
6758 return funcp;
6759}
6760
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01006761# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006762static void unset_func(const char *name)
6763{
6764 struct function **funcpp = find_function_slot(name);
6765 struct function *funcp = *funcpp;
6766
6767 if (funcp != NULL) {
6768 debug_printf_exec("freeing function '%s'\n", funcp->name);
6769 *funcpp = funcp->next;
6770 /* funcp is unlinked now, deleting it.
6771 * Note: if !funcp->body, the function was created by
6772 * "-F name body", do not free ->body_as_string
6773 * and ->name as they were not malloced. */
6774 if (funcp->body) {
6775 free_pipe_list(funcp->body);
6776 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01006777# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006778 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01006779# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006780 }
6781 free(funcp);
6782 }
6783}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01006784# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006785
6786# if BB_MMU
6787#define exec_function(to_free, funcp, argv) \
6788 exec_function(funcp, argv)
6789# endif
6790static void exec_function(char ***to_free,
6791 const struct function *funcp,
6792 char **argv) NORETURN;
6793static void exec_function(char ***to_free,
6794 const struct function *funcp,
6795 char **argv)
6796{
6797# if BB_MMU
6798 int n = 1;
6799
6800 argv[0] = G.global_argv[0];
6801 G.global_argv = argv;
6802 while (*++argv)
6803 n++;
6804 G.global_argc = n;
6805 /* On MMU, funcp->body is always non-NULL */
6806 n = run_list(funcp->body);
6807 fflush_all();
6808 _exit(n);
6809# else
6810 re_execute_shell(to_free,
6811 funcp->body_as_string,
6812 G.global_argv[0],
6813 argv + 1,
6814 NULL);
6815# endif
6816}
6817
6818static int run_function(const struct function *funcp, char **argv)
6819{
6820 int rc;
6821 save_arg_t sv;
6822 smallint sv_flg;
6823
6824 save_and_replace_G_args(&sv, argv);
6825
6826 /* "we are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006827 sv_flg = G_flag_return_in_progress;
6828 G_flag_return_in_progress = -1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006829# if ENABLE_HUSH_LOCAL
6830 G.func_nest_level++;
6831# endif
6832
6833 /* On MMU, funcp->body is always non-NULL */
6834# if !BB_MMU
6835 if (!funcp->body) {
6836 /* Function defined by -F */
6837 parse_and_run_string(funcp->body_as_string);
6838 rc = G.last_exitcode;
6839 } else
6840# endif
6841 {
6842 rc = run_list(funcp->body);
6843 }
6844
6845# if ENABLE_HUSH_LOCAL
6846 {
6847 struct variable *var;
6848 struct variable **var_pp;
6849
6850 var_pp = &G.top_var;
6851 while ((var = *var_pp) != NULL) {
6852 if (var->func_nest_level < G.func_nest_level) {
6853 var_pp = &var->next;
6854 continue;
6855 }
6856 /* Unexport */
6857 if (var->flg_export)
6858 bb_unsetenv(var->varstr);
6859 /* Remove from global list */
6860 *var_pp = var->next;
6861 /* Free */
6862 if (!var->max_len)
6863 free(var->varstr);
6864 free(var);
6865 }
6866 G.func_nest_level--;
6867 }
6868# endif
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006869 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006870
6871 restore_G_args(&sv, argv);
6872
6873 return rc;
6874}
6875#endif /* ENABLE_HUSH_FUNCTIONS */
6876
6877
6878#if BB_MMU
6879#define exec_builtin(to_free, x, argv) \
6880 exec_builtin(x, argv)
6881#else
6882#define exec_builtin(to_free, x, argv) \
6883 exec_builtin(to_free, argv)
6884#endif
6885static void exec_builtin(char ***to_free,
6886 const struct built_in_command *x,
6887 char **argv) NORETURN;
6888static void exec_builtin(char ***to_free,
6889 const struct built_in_command *x,
6890 char **argv)
6891{
6892#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006893 int rcode;
6894 fflush_all();
6895 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006896 fflush_all();
6897 _exit(rcode);
6898#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006899 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006900 /* On NOMMU, we must never block!
6901 * Example: { sleep 99 | read line; } & echo Ok
6902 */
6903 re_execute_shell(to_free,
6904 argv[0],
6905 G.global_argv[0],
6906 G.global_argv + 1,
6907 argv);
6908#endif
6909}
6910
6911
6912static void execvp_or_die(char **argv) NORETURN;
6913static void execvp_or_die(char **argv)
6914{
Denys Vlasenko04465da2016-10-03 01:01:15 +02006915 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006916 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006917 /* Don't propagate SIG_IGN to the child */
6918 if (SPECIAL_JOBSTOP_SIGS != 0)
6919 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006920 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02006921 e = 2;
6922 if (errno == EACCES) e = 126;
6923 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006924 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02006925 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006926}
6927
6928#if ENABLE_HUSH_MODE_X
6929static void dump_cmd_in_x_mode(char **argv)
6930{
6931 if (G_x_mode && argv) {
6932 /* We want to output the line in one write op */
6933 char *buf, *p;
6934 int len;
6935 int n;
6936
6937 len = 3;
6938 n = 0;
6939 while (argv[n])
6940 len += strlen(argv[n++]) + 1;
6941 buf = xmalloc(len);
6942 buf[0] = '+';
6943 p = buf + 1;
6944 n = 0;
6945 while (argv[n])
6946 p += sprintf(p, " %s", argv[n++]);
6947 *p++ = '\n';
6948 *p = '\0';
6949 fputs(buf, stderr);
6950 free(buf);
6951 }
6952}
6953#else
6954# define dump_cmd_in_x_mode(argv) ((void)0)
6955#endif
6956
6957#if BB_MMU
6958#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6959 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6960#define pseudo_exec(nommu_save, command, argv_expanded) \
6961 pseudo_exec(command, argv_expanded)
6962#endif
6963
6964/* Called after [v]fork() in run_pipe, or from builtin_exec.
6965 * Never returns.
6966 * Don't exit() here. If you don't exec, use _exit instead.
6967 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006968 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006969 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006970static void pseudo_exec_argv(nommu_save_t *nommu_save,
6971 char **argv, int assignment_cnt,
6972 char **argv_expanded) NORETURN;
6973static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6974 char **argv, int assignment_cnt,
6975 char **argv_expanded)
6976{
6977 char **new_env;
6978
6979 new_env = expand_assignments(argv, assignment_cnt);
6980 dump_cmd_in_x_mode(new_env);
6981
6982 if (!argv[assignment_cnt]) {
6983 /* Case when we are here: ... | var=val | ...
6984 * (note that we do not exit early, i.e., do not optimize out
6985 * expand_assignments(): think about ... | var=`sleep 1` | ...
6986 */
6987 free_strings(new_env);
6988 _exit(EXIT_SUCCESS);
6989 }
6990
6991#if BB_MMU
6992 set_vars_and_save_old(new_env);
6993 free(new_env); /* optional */
6994 /* we can also destroy set_vars_and_save_old's return value,
6995 * to save memory */
6996#else
6997 nommu_save->new_env = new_env;
6998 nommu_save->old_vars = set_vars_and_save_old(new_env);
6999#endif
7000
7001 if (argv_expanded) {
7002 argv = argv_expanded;
7003 } else {
7004 argv = expand_strvec_to_strvec(argv + assignment_cnt);
7005#if !BB_MMU
7006 nommu_save->argv = argv;
7007#endif
7008 }
7009 dump_cmd_in_x_mode(argv);
7010
7011#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7012 if (strchr(argv[0], '/') != NULL)
7013 goto skip;
7014#endif
7015
7016 /* Check if the command matches any of the builtins.
7017 * Depending on context, this might be redundant. But it's
7018 * easier to waste a few CPU cycles than it is to figure out
7019 * if this is one of those cases.
7020 */
7021 {
7022 /* On NOMMU, it is more expensive to re-execute shell
7023 * just in order to run echo or test builtin.
7024 * It's better to skip it here and run corresponding
7025 * non-builtin later. */
7026 const struct built_in_command *x;
7027 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7028 if (x) {
7029 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7030 }
7031 }
7032#if ENABLE_HUSH_FUNCTIONS
7033 /* Check if the command matches any functions */
7034 {
7035 const struct function *funcp = find_function(argv[0]);
7036 if (funcp) {
7037 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7038 }
7039 }
7040#endif
7041
7042#if ENABLE_FEATURE_SH_STANDALONE
7043 /* Check if the command matches any busybox applets */
7044 {
7045 int a = find_applet_by_name(argv[0]);
7046 if (a >= 0) {
7047# if BB_MMU /* see above why on NOMMU it is not allowed */
7048 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007049 /* Do not leak open fds from opened script files etc */
7050 close_all_FILE_list();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007051 debug_printf_exec("running applet '%s'\n", argv[0]);
7052 run_applet_no_and_exit(a, argv);
7053 }
7054# endif
7055 /* Re-exec ourselves */
7056 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007057 /* Don't propagate SIG_IGN to the child */
7058 if (SPECIAL_JOBSTOP_SIGS != 0)
7059 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007060 execv(bb_busybox_exec_path, argv);
7061 /* If they called chroot or otherwise made the binary no longer
7062 * executable, fall through */
7063 }
7064 }
7065#endif
7066
7067#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7068 skip:
7069#endif
7070 execvp_or_die(argv);
7071}
7072
7073/* Called after [v]fork() in run_pipe
7074 */
7075static void pseudo_exec(nommu_save_t *nommu_save,
7076 struct command *command,
7077 char **argv_expanded) NORETURN;
7078static void pseudo_exec(nommu_save_t *nommu_save,
7079 struct command *command,
7080 char **argv_expanded)
7081{
7082 if (command->argv) {
7083 pseudo_exec_argv(nommu_save, command->argv,
7084 command->assignment_cnt, argv_expanded);
7085 }
7086
7087 if (command->group) {
7088 /* Cases when we are here:
7089 * ( list )
7090 * { list } &
7091 * ... | ( list ) | ...
7092 * ... | { list } | ...
7093 */
7094#if BB_MMU
7095 int rcode;
7096 debug_printf_exec("pseudo_exec: run_list\n");
7097 reset_traps_to_defaults();
7098 rcode = run_list(command->group);
7099 /* OK to leak memory by not calling free_pipe_list,
7100 * since this process is about to exit */
7101 _exit(rcode);
7102#else
7103 re_execute_shell(&nommu_save->argv_from_re_execing,
7104 command->group_as_string,
7105 G.global_argv[0],
7106 G.global_argv + 1,
7107 NULL);
7108#endif
7109 }
7110
7111 /* Case when we are here: ... | >file */
7112 debug_printf_exec("pseudo_exec'ed null command\n");
7113 _exit(EXIT_SUCCESS);
7114}
7115
7116#if ENABLE_HUSH_JOB
7117static const char *get_cmdtext(struct pipe *pi)
7118{
7119 char **argv;
7120 char *p;
7121 int len;
7122
7123 /* This is subtle. ->cmdtext is created only on first backgrounding.
7124 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7125 * On subsequent bg argv is trashed, but we won't use it */
7126 if (pi->cmdtext)
7127 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007128
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007129 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007130 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007131 pi->cmdtext = xzalloc(1);
7132 return pi->cmdtext;
7133 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007134 len = 0;
7135 do {
7136 len += strlen(*argv) + 1;
7137 } while (*++argv);
7138 p = xmalloc(len);
7139 pi->cmdtext = p;
7140 argv = pi->cmds[0].argv;
7141 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007142 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007143 *p++ = ' ';
7144 } while (*++argv);
7145 p[-1] = '\0';
7146 return pi->cmdtext;
7147}
7148
7149static void insert_bg_job(struct pipe *pi)
7150{
7151 struct pipe *job, **jobp;
7152 int i;
7153
7154 /* Linear search for the ID of the job to use */
7155 pi->jobid = 1;
7156 for (job = G.job_list; job; job = job->next)
7157 if (job->jobid >= pi->jobid)
7158 pi->jobid = job->jobid + 1;
7159
7160 /* Add job to the list of running jobs */
7161 jobp = &G.job_list;
7162 while ((job = *jobp) != NULL)
7163 jobp = &job->next;
7164 job = *jobp = xmalloc(sizeof(*job));
7165
7166 *job = *pi; /* physical copy */
7167 job->next = NULL;
7168 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7169 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7170 for (i = 0; i < pi->num_cmds; i++) {
7171 job->cmds[i].pid = pi->cmds[i].pid;
7172 /* all other fields are not used and stay zero */
7173 }
7174 job->cmdtext = xstrdup(get_cmdtext(pi));
7175
7176 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007177 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007178 G.last_jobid = job->jobid;
7179}
7180
7181static void remove_bg_job(struct pipe *pi)
7182{
7183 struct pipe *prev_pipe;
7184
7185 if (pi == G.job_list) {
7186 G.job_list = pi->next;
7187 } else {
7188 prev_pipe = G.job_list;
7189 while (prev_pipe->next != pi)
7190 prev_pipe = prev_pipe->next;
7191 prev_pipe->next = pi->next;
7192 }
7193 if (G.job_list)
7194 G.last_jobid = G.job_list->jobid;
7195 else
7196 G.last_jobid = 0;
7197}
7198
7199/* Remove a backgrounded job */
7200static void delete_finished_bg_job(struct pipe *pi)
7201{
7202 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007203 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007204}
7205#endif /* JOB */
7206
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007207static int job_exited_or_stopped(struct pipe *pi)
7208{
7209 int rcode, i;
7210
7211 if (pi->alive_cmds != pi->stopped_cmds)
7212 return -1;
7213
7214 /* All processes in fg pipe have exited or stopped */
7215 rcode = 0;
7216 i = pi->num_cmds;
7217 while (--i >= 0) {
7218 rcode = pi->cmds[i].cmd_exitcode;
7219 /* usually last process gives overall exitstatus,
7220 * but with "set -o pipefail", last *failed* process does */
7221 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7222 break;
7223 }
7224 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7225 return rcode;
7226}
7227
Denys Vlasenko7e675362016-10-28 21:57:31 +02007228static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007229{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007230#if ENABLE_HUSH_JOB
7231 struct pipe *pi;
7232#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007233 int i, dead;
7234
7235 dead = WIFEXITED(status) || WIFSIGNALED(status);
7236
7237#if DEBUG_JOBS
7238 if (WIFSTOPPED(status))
7239 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7240 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7241 if (WIFSIGNALED(status))
7242 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7243 childpid, WTERMSIG(status), WEXITSTATUS(status));
7244 if (WIFEXITED(status))
7245 debug_printf_jobs("pid %d exited, exitcode %d\n",
7246 childpid, WEXITSTATUS(status));
7247#endif
7248 /* Were we asked to wait for a fg pipe? */
7249 if (fg_pipe) {
7250 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007251
Denys Vlasenko7e675362016-10-28 21:57:31 +02007252 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007253 int rcode;
7254
Denys Vlasenko7e675362016-10-28 21:57:31 +02007255 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7256 if (fg_pipe->cmds[i].pid != childpid)
7257 continue;
7258 if (dead) {
7259 int ex;
7260 fg_pipe->cmds[i].pid = 0;
7261 fg_pipe->alive_cmds--;
7262 ex = WEXITSTATUS(status);
7263 /* bash prints killer signal's name for *last*
7264 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7265 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7266 */
7267 if (WIFSIGNALED(status)) {
7268 int sig = WTERMSIG(status);
7269 if (i == fg_pipe->num_cmds-1)
7270 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7271 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7272 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7273 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7274 * Maybe we need to use sig | 128? */
7275 ex = sig + 128;
7276 }
7277 fg_pipe->cmds[i].cmd_exitcode = ex;
7278 } else {
7279 fg_pipe->stopped_cmds++;
7280 }
7281 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7282 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007283 rcode = job_exited_or_stopped(fg_pipe);
7284 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007285/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7286 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7287 * and "killall -STOP cat" */
7288 if (G_interactive_fd) {
7289#if ENABLE_HUSH_JOB
7290 if (fg_pipe->alive_cmds != 0)
7291 insert_bg_job(fg_pipe);
7292#endif
7293 return rcode;
7294 }
7295 if (fg_pipe->alive_cmds == 0)
7296 return rcode;
7297 }
7298 /* There are still running processes in the fg_pipe */
7299 return -1;
7300 }
7301 /* It wasnt in fg_pipe, look for process in bg pipes */
7302 }
7303
7304#if ENABLE_HUSH_JOB
7305 /* We were asked to wait for bg or orphaned children */
7306 /* No need to remember exitcode in this case */
7307 for (pi = G.job_list; pi; pi = pi->next) {
7308 for (i = 0; i < pi->num_cmds; i++) {
7309 if (pi->cmds[i].pid == childpid)
7310 goto found_pi_and_prognum;
7311 }
7312 }
7313 /* Happens when shell is used as init process (init=/bin/sh) */
7314 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7315 return -1; /* this wasn't a process from fg_pipe */
7316
7317 found_pi_and_prognum:
7318 if (dead) {
7319 /* child exited */
7320 pi->cmds[i].pid = 0;
7321 pi->cmds[i].cmd_exitcode = WEXITSTATUS(status);
7322 if (WIFSIGNALED(status))
7323 pi->cmds[i].cmd_exitcode = 128 + WTERMSIG(status);
7324 pi->alive_cmds--;
7325 if (!pi->alive_cmds) {
7326 if (G_interactive_fd)
7327 printf(JOB_STATUS_FORMAT, pi->jobid,
7328 "Done", pi->cmdtext);
7329 delete_finished_bg_job(pi);
7330 }
7331 } else {
7332 /* child stopped */
7333 pi->stopped_cmds++;
7334 }
7335#endif
7336 return -1; /* this wasn't a process from fg_pipe */
7337}
7338
7339/* Check to see if any processes have exited -- if they have,
7340 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007341 *
7342 * If non-NULL fg_pipe: wait for its completion or stop.
7343 * Return its exitcode or zero if stopped.
7344 *
7345 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7346 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7347 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7348 * or 0 if no children changed status.
7349 *
7350 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7351 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7352 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02007353 */
7354static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7355{
7356 int attributes;
7357 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007358 int rcode = 0;
7359
7360 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7361
7362 attributes = WUNTRACED;
7363 if (fg_pipe == NULL)
7364 attributes |= WNOHANG;
7365
7366 errno = 0;
7367#if ENABLE_HUSH_FAST
7368 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7369//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7370//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7371 /* There was neither fork nor SIGCHLD since last waitpid */
7372 /* Avoid doing waitpid syscall if possible */
7373 if (!G.we_have_children) {
7374 errno = ECHILD;
7375 return -1;
7376 }
7377 if (fg_pipe == NULL) { /* is WNOHANG set? */
7378 /* We have children, but they did not exit
7379 * or stop yet (we saw no SIGCHLD) */
7380 return 0;
7381 }
7382 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7383 }
7384#endif
7385
7386/* Do we do this right?
7387 * bash-3.00# sleep 20 | false
7388 * <ctrl-Z pressed>
7389 * [3]+ Stopped sleep 20 | false
7390 * bash-3.00# echo $?
7391 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7392 * [hush 1.14.0: yes we do it right]
7393 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007394 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007395 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007396#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02007397 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007398 i = G.count_SIGCHLD;
7399#endif
7400 childpid = waitpid(-1, &status, attributes);
7401 if (childpid <= 0) {
7402 if (childpid && errno != ECHILD)
7403 bb_perror_msg("waitpid");
7404#if ENABLE_HUSH_FAST
7405 else { /* Until next SIGCHLD, waitpid's are useless */
7406 G.we_have_children = (childpid == 0);
7407 G.handled_SIGCHLD = i;
7408//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7409 }
7410#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007411 /* ECHILD (no children), or 0 (no change in children status) */
7412 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007413 break;
7414 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007415 rcode = process_wait_result(fg_pipe, childpid, status);
7416 if (rcode >= 0) {
7417 /* fg_pipe exited or stopped */
7418 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007419 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007420 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007421 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007422 rcode = WEXITSTATUS(status);
7423 if (WIFSIGNALED(status))
7424 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007425 if (WIFSTOPPED(status))
7426 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7427 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007428 rcode++;
7429 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007430 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007431 /* This wasn't one of our processes, or */
7432 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007433 } /* while (waitpid succeeds)... */
7434
7435 return rcode;
7436}
7437
7438#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007439static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007440{
7441 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007442 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007443 if (G_saved_tty_pgrp) {
7444 /* Job finished, move the shell to the foreground */
7445 p = getpgrp(); /* our process group id */
7446 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7447 tcsetpgrp(G_interactive_fd, p);
7448 }
7449 return rcode;
7450}
7451#endif
7452
7453/* Start all the jobs, but don't wait for anything to finish.
7454 * See checkjobs().
7455 *
7456 * Return code is normally -1, when the caller has to wait for children
7457 * to finish to determine the exit status of the pipe. If the pipe
7458 * is a simple builtin command, however, the action is done by the
7459 * time run_pipe returns, and the exit code is provided as the
7460 * return value.
7461 *
7462 * Returns -1 only if started some children. IOW: we have to
7463 * mask out retvals of builtins etc with 0xff!
7464 *
7465 * The only case when we do not need to [v]fork is when the pipe
7466 * is single, non-backgrounded, non-subshell command. Examples:
7467 * cmd ; ... { list } ; ...
7468 * cmd && ... { list } && ...
7469 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007470 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007471 * or (if SH_STANDALONE) an applet, and we can run the { list }
7472 * with run_list. If it isn't one of these, we fork and exec cmd.
7473 *
7474 * Cases when we must fork:
7475 * non-single: cmd | cmd
7476 * backgrounded: cmd & { list } &
7477 * subshell: ( list ) [&]
7478 */
7479#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01007480#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007481 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7482#endif
7483static int redirect_and_varexp_helper(char ***new_env_p,
7484 struct variable **old_vars_p,
7485 struct command *command,
7486 int squirrel[3],
7487 char **argv_expanded)
7488{
7489 /* setup_redirects acts on file descriptors, not FILEs.
7490 * This is perfect for work that comes after exec().
7491 * Is it really safe for inline use? Experimentally,
7492 * things seem to work. */
7493 int rcode = setup_redirects(command, squirrel);
7494 if (rcode == 0) {
7495 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7496 *new_env_p = new_env;
7497 dump_cmd_in_x_mode(new_env);
7498 dump_cmd_in_x_mode(argv_expanded);
7499 if (old_vars_p)
7500 *old_vars_p = set_vars_and_save_old(new_env);
7501 }
7502 return rcode;
7503}
7504static NOINLINE int run_pipe(struct pipe *pi)
7505{
7506 static const char *const null_ptr = NULL;
7507
7508 int cmd_no;
7509 int next_infd;
7510 struct command *command;
7511 char **argv_expanded;
7512 char **argv;
7513 /* it is not always needed, but we aim to smaller code */
7514 int squirrel[] = { -1, -1, -1 };
7515 int rcode;
7516
7517 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7518 debug_enter();
7519
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007520 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7521 * Result should be 3 lines: q w e, qwe, q w e
7522 */
7523 G.ifs = get_local_var_value("IFS");
7524 if (!G.ifs)
7525 G.ifs = defifs;
7526
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007527 IF_HUSH_JOB(pi->pgrp = -1;)
7528 pi->stopped_cmds = 0;
7529 command = &pi->cmds[0];
7530 argv_expanded = NULL;
7531
7532 if (pi->num_cmds != 1
7533 || pi->followup == PIPE_BG
7534 || command->cmd_type == CMD_SUBSHELL
7535 ) {
7536 goto must_fork;
7537 }
7538
7539 pi->alive_cmds = 1;
7540
7541 debug_printf_exec(": group:%p argv:'%s'\n",
7542 command->group, command->argv ? command->argv[0] : "NONE");
7543
7544 if (command->group) {
7545#if ENABLE_HUSH_FUNCTIONS
7546 if (command->cmd_type == CMD_FUNCDEF) {
7547 /* "executing" func () { list } */
7548 struct function *funcp;
7549
7550 funcp = new_function(command->argv[0]);
7551 /* funcp->name is already set to argv[0] */
7552 funcp->body = command->group;
7553# if !BB_MMU
7554 funcp->body_as_string = command->group_as_string;
7555 command->group_as_string = NULL;
7556# endif
7557 command->group = NULL;
7558 command->argv[0] = NULL;
7559 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7560 funcp->parent_cmd = command;
7561 command->child_func = funcp;
7562
7563 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7564 debug_leave();
7565 return EXIT_SUCCESS;
7566 }
7567#endif
7568 /* { list } */
7569 debug_printf("non-subshell group\n");
7570 rcode = 1; /* exitcode if redir failed */
7571 if (setup_redirects(command, squirrel) == 0) {
7572 debug_printf_exec(": run_list\n");
7573 rcode = run_list(command->group) & 0xff;
7574 }
7575 restore_redirects(squirrel);
7576 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7577 debug_leave();
7578 debug_printf_exec("run_pipe: return %d\n", rcode);
7579 return rcode;
7580 }
7581
7582 argv = command->argv ? command->argv : (char **) &null_ptr;
7583 {
7584 const struct built_in_command *x;
7585#if ENABLE_HUSH_FUNCTIONS
7586 const struct function *funcp;
7587#else
7588 enum { funcp = 0 };
7589#endif
7590 char **new_env = NULL;
7591 struct variable *old_vars = NULL;
7592
7593 if (argv[command->assignment_cnt] == NULL) {
7594 /* Assignments, but no command */
7595 /* Ensure redirects take effect (that is, create files).
7596 * Try "a=t >file" */
7597#if 0 /* A few cases in testsuite fail with this code. FIXME */
7598 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7599 /* Set shell variables */
7600 if (new_env) {
7601 argv = new_env;
7602 while (*argv) {
7603 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7604 /* Do we need to flag set_local_var() errors?
7605 * "assignment to readonly var" and "putenv error"
7606 */
7607 argv++;
7608 }
7609 }
7610 /* Redirect error sets $? to 1. Otherwise,
7611 * if evaluating assignment value set $?, retain it.
7612 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7613 if (rcode == 0)
7614 rcode = G.last_exitcode;
7615 /* Exit, _skipping_ variable restoring code: */
7616 goto clean_up_and_ret0;
7617
7618#else /* Older, bigger, but more correct code */
7619
7620 rcode = setup_redirects(command, squirrel);
7621 restore_redirects(squirrel);
7622 /* Set shell variables */
7623 if (G_x_mode)
7624 bb_putchar_stderr('+');
7625 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007626 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007627 if (G_x_mode)
7628 fprintf(stderr, " %s", p);
7629 debug_printf_exec("set shell var:'%s'->'%s'\n",
7630 *argv, p);
7631 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7632 /* Do we need to flag set_local_var() errors?
7633 * "assignment to readonly var" and "putenv error"
7634 */
7635 argv++;
7636 }
7637 if (G_x_mode)
7638 bb_putchar_stderr('\n');
7639 /* Redirect error sets $? to 1. Otherwise,
7640 * if evaluating assignment value set $?, retain it.
7641 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7642 if (rcode == 0)
7643 rcode = G.last_exitcode;
7644 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7645 debug_leave();
7646 debug_printf_exec("run_pipe: return %d\n", rcode);
7647 return rcode;
7648#endif
7649 }
7650
7651 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007652#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007653 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007654 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007655 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007656#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007657 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007658 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7659 }
7660
7661 /* if someone gives us an empty string: `cmd with empty output` */
7662 if (!argv_expanded[0]) {
7663 free(argv_expanded);
7664 debug_leave();
7665 return G.last_exitcode;
7666 }
7667
7668 x = find_builtin(argv_expanded[0]);
7669#if ENABLE_HUSH_FUNCTIONS
7670 funcp = NULL;
7671 if (!x)
7672 funcp = find_function(argv_expanded[0]);
7673#endif
7674 if (x || funcp) {
7675 if (!funcp) {
7676 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7677 debug_printf("exec with redirects only\n");
7678 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007679 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007680 goto clean_up_and_ret1;
7681 }
7682 }
7683 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7684 if (rcode == 0) {
7685 if (!funcp) {
7686 debug_printf_exec(": builtin '%s' '%s'...\n",
7687 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007688 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007689 rcode = x->b_function(argv_expanded) & 0xff;
7690 fflush_all();
7691 }
7692#if ENABLE_HUSH_FUNCTIONS
7693 else {
7694# if ENABLE_HUSH_LOCAL
7695 struct variable **sv;
7696 sv = G.shadowed_vars_pp;
7697 G.shadowed_vars_pp = &old_vars;
7698# endif
7699 debug_printf_exec(": function '%s' '%s'...\n",
7700 funcp->name, argv_expanded[1]);
7701 rcode = run_function(funcp, argv_expanded) & 0xff;
7702# if ENABLE_HUSH_LOCAL
7703 G.shadowed_vars_pp = sv;
7704# endif
7705 }
7706#endif
7707 }
7708 clean_up_and_ret:
7709 unset_vars(new_env);
7710 add_vars(old_vars);
7711/* clean_up_and_ret0: */
7712 restore_redirects(squirrel);
7713 clean_up_and_ret1:
7714 free(argv_expanded);
7715 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7716 debug_leave();
7717 debug_printf_exec("run_pipe return %d\n", rcode);
7718 return rcode;
7719 }
7720
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007721 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007722 int n = find_applet_by_name(argv_expanded[0]);
7723 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7724 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7725 if (rcode == 0) {
7726 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7727 argv_expanded[0], argv_expanded[1]);
7728 rcode = run_nofork_applet(n, argv_expanded);
7729 }
7730 goto clean_up_and_ret;
7731 }
7732 }
7733 /* It is neither builtin nor applet. We must fork. */
7734 }
7735
7736 must_fork:
7737 /* NB: argv_expanded may already be created, and that
7738 * might include `cmd` runs! Do not rerun it! We *must*
7739 * use argv_expanded if it's non-NULL */
7740
7741 /* Going to fork a child per each pipe member */
7742 pi->alive_cmds = 0;
7743 next_infd = 0;
7744
7745 cmd_no = 0;
7746 while (cmd_no < pi->num_cmds) {
7747 struct fd_pair pipefds;
7748#if !BB_MMU
7749 volatile nommu_save_t nommu_save;
7750 nommu_save.new_env = NULL;
7751 nommu_save.old_vars = NULL;
7752 nommu_save.argv = NULL;
7753 nommu_save.argv_from_re_execing = NULL;
7754#endif
7755 command = &pi->cmds[cmd_no];
7756 cmd_no++;
7757 if (command->argv) {
7758 debug_printf_exec(": pipe member '%s' '%s'...\n",
7759 command->argv[0], command->argv[1]);
7760 } else {
7761 debug_printf_exec(": pipe member with no argv\n");
7762 }
7763
7764 /* pipes are inserted between pairs of commands */
7765 pipefds.rd = 0;
7766 pipefds.wr = 1;
7767 if (cmd_no < pi->num_cmds)
7768 xpiped_pair(pipefds);
7769
7770 command->pid = BB_MMU ? fork() : vfork();
7771 if (!command->pid) { /* child */
7772#if ENABLE_HUSH_JOB
7773 disable_restore_tty_pgrp_on_exit();
7774 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7775
7776 /* Every child adds itself to new process group
7777 * with pgid == pid_of_first_child_in_pipe */
7778 if (G.run_list_level == 1 && G_interactive_fd) {
7779 pid_t pgrp;
7780 pgrp = pi->pgrp;
7781 if (pgrp < 0) /* true for 1st process only */
7782 pgrp = getpid();
7783 if (setpgid(0, pgrp) == 0
7784 && pi->followup != PIPE_BG
7785 && G_saved_tty_pgrp /* we have ctty */
7786 ) {
7787 /* We do it in *every* child, not just first,
7788 * to avoid races */
7789 tcsetpgrp(G_interactive_fd, pgrp);
7790 }
7791 }
7792#endif
7793 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7794 /* 1st cmd in backgrounded pipe
7795 * should have its stdin /dev/null'ed */
7796 close(0);
7797 if (open(bb_dev_null, O_RDONLY))
7798 xopen("/", O_RDONLY);
7799 } else {
7800 xmove_fd(next_infd, 0);
7801 }
7802 xmove_fd(pipefds.wr, 1);
7803 if (pipefds.rd > 1)
7804 close(pipefds.rd);
7805 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02007806 * and the pipe fd (fd#1) is available for dup'ing:
7807 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7808 * of cmd1 goes into pipe.
7809 */
7810 if (setup_redirects(command, NULL)) {
7811 /* Happens when redir file can't be opened:
7812 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7813 * FOO
7814 * hush: can't open '/qwe/rty': No such file or directory
7815 * BAZ
7816 * (echo BAR is not executed, it hits _exit(1) below)
7817 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007818 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007819 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007820
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007821 /* Stores to nommu_save list of env vars putenv'ed
7822 * (NOMMU, on MMU we don't need that) */
7823 /* cast away volatility... */
7824 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7825 /* pseudo_exec() does not return */
7826 }
7827
7828 /* parent or error */
7829#if ENABLE_HUSH_FAST
7830 G.count_SIGCHLD++;
7831//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7832#endif
7833 enable_restore_tty_pgrp_on_exit();
7834#if !BB_MMU
7835 /* Clean up after vforked child */
7836 free(nommu_save.argv);
7837 free(nommu_save.argv_from_re_execing);
7838 unset_vars(nommu_save.new_env);
7839 add_vars(nommu_save.old_vars);
7840#endif
7841 free(argv_expanded);
7842 argv_expanded = NULL;
7843 if (command->pid < 0) { /* [v]fork failed */
7844 /* Clearly indicate, was it fork or vfork */
7845 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7846 } else {
7847 pi->alive_cmds++;
7848#if ENABLE_HUSH_JOB
7849 /* Second and next children need to know pid of first one */
7850 if (pi->pgrp < 0)
7851 pi->pgrp = command->pid;
7852#endif
7853 }
7854
7855 if (cmd_no > 1)
7856 close(next_infd);
7857 if (cmd_no < pi->num_cmds)
7858 close(pipefds.wr);
7859 /* Pass read (output) pipe end to next iteration */
7860 next_infd = pipefds.rd;
7861 }
7862
7863 if (!pi->alive_cmds) {
7864 debug_leave();
7865 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7866 return 1;
7867 }
7868
7869 debug_leave();
7870 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7871 return -1;
7872}
7873
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007874/* NB: called by pseudo_exec, and therefore must not modify any
7875 * global data until exec/_exit (we can be a child after vfork!) */
7876static int run_list(struct pipe *pi)
7877{
7878#if ENABLE_HUSH_CASE
7879 char *case_word = NULL;
7880#endif
7881#if ENABLE_HUSH_LOOPS
7882 struct pipe *loop_top = NULL;
7883 char **for_lcur = NULL;
7884 char **for_list = NULL;
7885#endif
7886 smallint last_followup;
7887 smalluint rcode;
7888#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7889 smalluint cond_code = 0;
7890#else
7891 enum { cond_code = 0 };
7892#endif
7893#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007894 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007895 smallint last_rword; /* ditto */
7896#endif
7897
7898 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7899 debug_enter();
7900
7901#if ENABLE_HUSH_LOOPS
7902 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007903 {
7904 struct pipe *cpipe;
7905 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7906 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7907 continue;
7908 /* current word is FOR or IN (BOLD in comments below) */
7909 if (cpipe->next == NULL) {
7910 syntax_error("malformed for");
7911 debug_leave();
7912 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7913 return 1;
7914 }
7915 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7916 if (cpipe->next->res_word == RES_DO)
7917 continue;
7918 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7919 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7920 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7921 ) {
7922 syntax_error("malformed for");
7923 debug_leave();
7924 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7925 return 1;
7926 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007927 }
7928 }
7929#endif
7930
7931 /* Past this point, all code paths should jump to ret: label
7932 * in order to return, no direct "return" statements please.
7933 * This helps to ensure that no memory is leaked. */
7934
7935#if ENABLE_HUSH_JOB
7936 G.run_list_level++;
7937#endif
7938
7939#if HAS_KEYWORDS
7940 rword = RES_NONE;
7941 last_rword = RES_XXXX;
7942#endif
7943 last_followup = PIPE_SEQ;
7944 rcode = G.last_exitcode;
7945
7946 /* Go through list of pipes, (maybe) executing them. */
7947 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007948 int r;
7949
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007950 if (G.flag_SIGINT)
7951 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007952 if (G_flag_return_in_progress == 1)
7953 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007954
7955 IF_HAS_KEYWORDS(rword = pi->res_word;)
7956 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7957 rword, cond_code, last_rword);
7958#if ENABLE_HUSH_LOOPS
7959 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7960 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7961 ) {
7962 /* start of a loop: remember where loop starts */
7963 loop_top = pi;
7964 G.depth_of_loop++;
7965 }
7966#endif
7967 /* Still in the same "if...", "then..." or "do..." branch? */
7968 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7969 if ((rcode == 0 && last_followup == PIPE_OR)
7970 || (rcode != 0 && last_followup == PIPE_AND)
7971 ) {
7972 /* It is "<true> || CMD" or "<false> && CMD"
7973 * and we should not execute CMD */
7974 debug_printf_exec("skipped cmd because of || or &&\n");
7975 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02007976 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007977 }
7978 }
7979 last_followup = pi->followup;
7980 IF_HAS_KEYWORDS(last_rword = rword;)
7981#if ENABLE_HUSH_IF
7982 if (cond_code) {
7983 if (rword == RES_THEN) {
7984 /* if false; then ... fi has exitcode 0! */
7985 G.last_exitcode = rcode = EXIT_SUCCESS;
7986 /* "if <false> THEN cmd": skip cmd */
7987 continue;
7988 }
7989 } else {
7990 if (rword == RES_ELSE || rword == RES_ELIF) {
7991 /* "if <true> then ... ELSE/ELIF cmd":
7992 * skip cmd and all following ones */
7993 break;
7994 }
7995 }
7996#endif
7997#if ENABLE_HUSH_LOOPS
7998 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7999 if (!for_lcur) {
8000 /* first loop through for */
8001
8002 static const char encoded_dollar_at[] ALIGN1 = {
8003 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
8004 }; /* encoded representation of "$@" */
8005 static const char *const encoded_dollar_at_argv[] = {
8006 encoded_dollar_at, NULL
8007 }; /* argv list with one element: "$@" */
8008 char **vals;
8009
8010 vals = (char**)encoded_dollar_at_argv;
8011 if (pi->next->res_word == RES_IN) {
8012 /* if no variable values after "in" we skip "for" */
8013 if (!pi->next->cmds[0].argv) {
8014 G.last_exitcode = rcode = EXIT_SUCCESS;
8015 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8016 break;
8017 }
8018 vals = pi->next->cmds[0].argv;
8019 } /* else: "for var; do..." -> assume "$@" list */
8020 /* create list of variable values */
8021 debug_print_strings("for_list made from", vals);
8022 for_list = expand_strvec_to_strvec(vals);
8023 for_lcur = for_list;
8024 debug_print_strings("for_list", for_list);
8025 }
8026 if (!*for_lcur) {
8027 /* "for" loop is over, clean up */
8028 free(for_list);
8029 for_list = NULL;
8030 for_lcur = NULL;
8031 break;
8032 }
8033 /* Insert next value from for_lcur */
8034 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8035 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
8036 continue;
8037 }
8038 if (rword == RES_IN) {
8039 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8040 }
8041 if (rword == RES_DONE) {
8042 continue; /* "done" has no cmds too */
8043 }
8044#endif
8045#if ENABLE_HUSH_CASE
8046 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008047 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008048 case_word = expand_strvec_to_string(pi->cmds->argv);
8049 continue;
8050 }
8051 if (rword == RES_MATCH) {
8052 char **argv;
8053
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008054 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008055 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8056 break;
8057 /* all prev words didn't match, does this one match? */
8058 argv = pi->cmds->argv;
8059 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02008060 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008061 /* TODO: which FNM_xxx flags to use? */
8062 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8063 free(pattern);
8064 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008065 free(case_word);
8066 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008067 break;
8068 }
8069 argv++;
8070 }
8071 continue;
8072 }
8073 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008074 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008075 if (cond_code != 0)
8076 continue; /* not matched yet, skip this pipe */
8077 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008078 if (rword == RES_ESAC) {
8079 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8080 if (case_word) {
8081 /* "case" did not match anything: still set $? (to 0) */
8082 G.last_exitcode = rcode = EXIT_SUCCESS;
8083 }
8084 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008085#endif
8086 /* Just pressing <enter> in shell should check for jobs.
8087 * OTOH, in non-interactive shell this is useless
8088 * and only leads to extra job checks */
8089 if (pi->num_cmds == 0) {
8090 if (G_interactive_fd)
8091 goto check_jobs_and_continue;
8092 continue;
8093 }
8094
8095 /* After analyzing all keywords and conditions, we decided
8096 * to execute this pipe. NB: have to do checkjobs(NULL)
8097 * after run_pipe to collect any background children,
8098 * even if list execution is to be stopped. */
8099 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008100#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008101 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008102#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008103 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8104 if (r != -1) {
8105 /* We ran a builtin, function, or group.
8106 * rcode is already known
8107 * and we don't need to wait for anything. */
8108 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8109 G.last_exitcode = rcode;
8110 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008111#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008112 /* Was it "break" or "continue"? */
8113 if (G.flag_break_continue) {
8114 smallint fbc = G.flag_break_continue;
8115 /* We might fall into outer *loop*,
8116 * don't want to break it too */
8117 if (loop_top) {
8118 G.depth_break_continue--;
8119 if (G.depth_break_continue == 0)
8120 G.flag_break_continue = 0;
8121 /* else: e.g. "continue 2" should *break* once, *then* continue */
8122 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8123 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008124 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008125 break;
8126 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008127 /* "continue": simulate end of loop */
8128 rword = RES_DONE;
8129 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008130 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008131#endif
8132 if (G_flag_return_in_progress == 1) {
8133 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8134 break;
8135 }
8136 } else if (pi->followup == PIPE_BG) {
8137 /* What does bash do with attempts to background builtins? */
8138 /* even bash 3.2 doesn't do that well with nested bg:
8139 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8140 * I'm NOT treating inner &'s as jobs */
8141#if ENABLE_HUSH_JOB
8142 if (G.run_list_level == 1)
8143 insert_bg_job(pi);
8144#endif
8145 /* Last command's pid goes to $! */
8146 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8147 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8148/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash says 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008149 rcode = EXIT_SUCCESS;
8150 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008151 } else {
8152#if ENABLE_HUSH_JOB
8153 if (G.run_list_level == 1 && G_interactive_fd) {
8154 /* Waits for completion, then fg's main shell */
8155 rcode = checkjobs_and_fg_shell(pi);
8156 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008157 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008158 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008159#endif
8160 /* This one just waits for completion */
8161 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8162 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8163 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008164 G.last_exitcode = rcode;
8165 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008166 }
8167
8168 /* Analyze how result affects subsequent commands */
8169#if ENABLE_HUSH_IF
8170 if (rword == RES_IF || rword == RES_ELIF)
8171 cond_code = rcode;
8172#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008173 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008174 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008175 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008176#if ENABLE_HUSH_LOOPS
8177 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008178 if (pi->next
8179 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008180 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008181 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008182 if (rword == RES_WHILE) {
8183 if (rcode) {
8184 /* "while false; do...done" - exitcode 0 */
8185 G.last_exitcode = rcode = EXIT_SUCCESS;
8186 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008187 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008188 }
8189 }
8190 if (rword == RES_UNTIL) {
8191 if (!rcode) {
8192 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008193 break;
8194 }
8195 }
8196 }
8197#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008198 } /* for (pi) */
8199
8200#if ENABLE_HUSH_JOB
8201 G.run_list_level--;
8202#endif
8203#if ENABLE_HUSH_LOOPS
8204 if (loop_top)
8205 G.depth_of_loop--;
8206 free(for_list);
8207#endif
8208#if ENABLE_HUSH_CASE
8209 free(case_word);
8210#endif
8211 debug_leave();
8212 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8213 return rcode;
8214}
8215
8216/* Select which version we will use */
8217static int run_and_free_list(struct pipe *pi)
8218{
8219 int rcode = 0;
8220 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08008221 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008222 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8223 rcode = run_list(pi);
8224 }
8225 /* free_pipe_list has the side effect of clearing memory.
8226 * In the long run that function can be merged with run_list,
8227 * but doing that now would hobble the debugging effort. */
8228 free_pipe_list(pi);
8229 debug_printf_exec("run_and_free_list return %d\n", rcode);
8230 return rcode;
8231}
8232
8233
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008234static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00008235{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008236 sighandler_t old_handler;
8237 unsigned sig = 0;
8238 while ((mask >>= 1) != 0) {
8239 sig++;
8240 if (!(mask & 1))
8241 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02008242 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008243 /* POSIX allows shell to re-enable SIGCHLD
8244 * even if it was SIG_IGN on entry.
8245 * Therefore we skip IGN check for it:
8246 */
8247 if (sig == SIGCHLD)
8248 continue;
8249 if (old_handler == SIG_IGN) {
8250 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008251 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008252#if ENABLE_HUSH_TRAP
8253 if (!G_traps)
8254 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8255 free(G_traps[sig]);
8256 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8257#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008258 }
8259 }
8260}
8261
8262/* Called a few times only (or even once if "sh -c") */
8263static void install_special_sighandlers(void)
8264{
Denis Vlasenkof9375282009-04-05 19:13:39 +00008265 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008266
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008267 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008268 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008269 if (G_interactive_fd) {
8270 mask |= SPECIAL_INTERACTIVE_SIGS;
8271 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008272 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008273 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008274 /* Careful, do not re-install handlers we already installed */
8275 if (G.special_sig_mask != mask) {
8276 unsigned diff = mask & ~G.special_sig_mask;
8277 G.special_sig_mask = mask;
8278 install_sighandlers(diff);
8279 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008280}
8281
8282#if ENABLE_HUSH_JOB
8283/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008284/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008285static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00008286{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008287 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008288
8289 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008290 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01008291 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8292 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008293 + (1 << SIGBUS ) * HUSH_DEBUG
8294 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01008295 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008296 + (1 << SIGABRT)
8297 /* bash 3.2 seems to handle these just like 'fatal' ones */
8298 + (1 << SIGPIPE)
8299 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008300 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008301 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008302 * we never want to restore pgrp on exit, and this fn is not called
8303 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008304 /*+ (1 << SIGHUP )*/
8305 /*+ (1 << SIGTERM)*/
8306 /*+ (1 << SIGINT )*/
8307 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008308 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008309
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008310 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008311}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00008312#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00008313
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008314static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00008315{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008316 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008317 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008318 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08008319 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008320 break;
8321 case 'x':
8322 IF_HUSH_MODE_X(G_x_mode = state;)
8323 break;
8324 case 'o':
8325 if (!o_opt) {
8326 /* "set -+o" without parameter.
8327 * in bash, set -o produces this output:
8328 * pipefail off
8329 * and set +o:
8330 * set +o pipefail
8331 * We always use the second form.
8332 */
8333 const char *p = o_opt_strings;
8334 idx = 0;
8335 while (*p) {
8336 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8337 idx++;
8338 p += strlen(p) + 1;
8339 }
8340 break;
8341 }
8342 idx = index_in_strings(o_opt_strings, o_opt);
8343 if (idx >= 0) {
8344 G.o_opt[idx] = state;
8345 break;
8346 }
8347 default:
8348 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008349 }
8350 return EXIT_SUCCESS;
8351}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008352
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00008353int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00008354int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00008355{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008356 enum {
8357 OPT_login = (1 << 0),
8358 };
8359 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00008360 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008361 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008362 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008363 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008364 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00008365
Denis Vlasenko574f2f42008-02-27 18:41:59 +00008366 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02008367 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008368 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008369
Denys Vlasenko10c01312011-05-11 11:49:21 +02008370#if ENABLE_HUSH_FAST
8371 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8372#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008373#if !BB_MMU
8374 G.argv0_for_re_execing = argv[0];
8375#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008376 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008377 shell_ver = xzalloc(sizeof(*shell_ver));
8378 shell_ver->flg_export = 1;
8379 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02008380 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02008381 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008382 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02008383 /* Create shell local variables from the values
8384 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00008385 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008386 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008387 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008388 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008389 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008390 if (e) while (*e) {
8391 char *value = strchr(*e, '=');
8392 if (value) { /* paranoia */
8393 cur_var->next = xzalloc(sizeof(*cur_var));
8394 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00008395 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008396 cur_var->max_len = strlen(*e);
8397 cur_var->flg_export = 1;
8398 }
8399 e++;
8400 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02008401 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008402 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8403 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02008404
8405 /* Export PWD */
8406 set_pwd_var(/*exp:*/ 1);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008407
8408#if ENABLE_HUSH_BASH_COMPAT
8409 /* Set (but not export) HOSTNAME unless already set */
8410 if (!get_local_var_value("HOSTNAME")) {
8411 struct utsname uts;
8412 uname(&uts);
8413 set_local_var_from_halves("HOSTNAME", uts.nodename);
8414 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008415 /* bash also exports SHLVL and _,
8416 * and sets (but doesn't export) the following variables:
8417 * BASH=/bin/bash
8418 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8419 * BASH_VERSION='3.2.0(1)-release'
8420 * HOSTTYPE=i386
8421 * MACHTYPE=i386-pc-linux-gnu
8422 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02008423 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02008424 * EUID=<NNNNN>
8425 * UID=<NNNNN>
8426 * GROUPS=()
8427 * LINES=<NNN>
8428 * COLUMNS=<NNN>
8429 * BASH_ARGC=()
8430 * BASH_ARGV=()
8431 * BASH_LINENO=()
8432 * BASH_SOURCE=()
8433 * DIRSTACK=()
8434 * PIPESTATUS=([0]="0")
8435 * HISTFILE=/<xxx>/.bash_history
8436 * HISTFILESIZE=500
8437 * HISTSIZE=500
8438 * MAILCHECK=60
8439 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8440 * SHELL=/bin/bash
8441 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8442 * TERM=dumb
8443 * OPTERR=1
8444 * OPTIND=1
8445 * IFS=$' \t\n'
8446 * PS1='\s-\v\$ '
8447 * PS2='> '
8448 * PS4='+ '
8449 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008450#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02008451
Denis Vlasenko38f63192007-01-22 09:03:07 +00008452#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02008453 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008454#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02008455
Eric Andersen94ac2442001-05-22 19:05:18 +00008456 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00008457 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00008458
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008459 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00008460
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008461 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008462 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008463 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008464 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008465 * in order to intercept (more) signals.
8466 */
8467
8468 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008469 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008470 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008471 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008472 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008473 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008474#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00008475 "<:$:R:V:"
8476# if ENABLE_HUSH_FUNCTIONS
8477 "F:"
8478# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008479#endif
8480 );
8481 if (opt <= 0)
8482 break;
Eric Andersen25f27032001-04-26 23:22:31 +00008483 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008484 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008485 /* Possibilities:
8486 * sh ... -c 'script'
8487 * sh ... -c 'script' ARG0 [ARG1...]
8488 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01008489 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008490 * "" needs to be replaced with NULL
8491 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01008492 * Note: the form without ARG0 never happens:
8493 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008494 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02008495 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008496 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008497 G.root_ppid = getppid();
8498 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008499 G.global_argv = argv + optind;
8500 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008501 if (builtin_argc) {
8502 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8503 const struct built_in_command *x;
8504
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008505 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008506 x = find_builtin(optarg);
8507 if (x) { /* paranoia */
8508 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8509 G.global_argv += builtin_argc;
8510 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008511 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01008512 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008513 }
8514 goto final_return;
8515 }
8516 if (!G.global_argv[0]) {
8517 /* -c 'script' (no params): prevent empty $0 */
8518 G.global_argv--; /* points to argv[i] of 'script' */
8519 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02008520 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008521 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008522 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008523 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008524 goto final_return;
8525 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00008526 /* Well, we cannot just declare interactiveness,
8527 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008528 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008529 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008530 case 's':
8531 /* "-s" means "read from stdin", but this is how we always
8532 * operate, so simply do nothing here. */
8533 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008534 case 'l':
8535 flags |= OPT_login;
8536 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008537#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008538 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02008539 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008540 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008541 case '$': {
8542 unsigned long long empty_trap_mask;
8543
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008544 G.root_pid = bb_strtou(optarg, &optarg, 16);
8545 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02008546 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8547 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008548 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8549 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008550 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008551 optarg++;
8552 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008553 optarg++;
8554 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8555 if (empty_trap_mask != 0) {
8556 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008557 install_special_sighandlers();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008558 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008559 for (sig = 1; sig < NSIG; sig++) {
8560 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008561 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008562 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008563 }
8564 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008565 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008566# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008567 optarg++;
8568 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008569# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008570 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008571 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008572 case 'R':
8573 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02008574 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008575 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00008576# if ENABLE_HUSH_FUNCTIONS
8577 case 'F': {
8578 struct function *funcp = new_function(optarg);
8579 /* funcp->name is already set to optarg */
8580 /* funcp->body is set to NULL. It's a special case. */
8581 funcp->body_as_string = argv[optind];
8582 optind++;
8583 break;
8584 }
8585# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008586#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008587 case 'n':
8588 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008589 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008590 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008591 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008592#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008593 fprintf(stderr, "Usage: sh [FILE]...\n"
8594 " or: sh -c command [args]...\n\n");
8595 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008596#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008597 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008598#endif
Eric Andersen25f27032001-04-26 23:22:31 +00008599 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008600 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008601
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008602 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8603 G.global_argc = argc - (optind - 1);
8604 G.global_argv = argv + (optind - 1);
8605 G.global_argv[0] = argv[0];
8606
Denys Vlasenkodea47882009-10-09 15:40:49 +02008607 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008608 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008609 G.root_ppid = getppid();
8610 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008611
8612 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008613 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008614 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008615 debug_printf("sourcing /etc/profile\n");
8616 input = fopen_for_read("/etc/profile");
8617 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008618 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008619 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008620 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008621 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008622 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008623 /* bash: after sourcing /etc/profile,
8624 * tries to source (in the given order):
8625 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008626 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008627 * bash also sources ~/.bash_logout on exit.
8628 * If called as sh, skips .bash_XXX files.
8629 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008630 }
8631
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008632 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008633 FILE *input;
8634 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008635 * "bash <script>" (which is never interactive (unless -i?))
8636 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008637 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02008638 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008639 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008640 G.global_argc--;
8641 G.global_argv++;
8642 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02008643 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008644 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02008645 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008646 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008647 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008648 parse_and_run_file(input);
8649#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008650 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008651#endif
8652 goto final_return;
8653 }
8654
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008655 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008656 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008657 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008658
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008659 /* A shell is interactive if the '-i' flag was given,
8660 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008661 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008662 * no arguments remaining or the -s flag given
8663 * standard input is a terminal
8664 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008665 * Refer to Posix.2, the description of the 'sh' utility.
8666 */
8667#if ENABLE_HUSH_JOB
8668 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008669 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8670 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8671 if (G_saved_tty_pgrp < 0)
8672 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008673
8674 /* try to dup stdin to high fd#, >= 255 */
8675 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8676 if (G_interactive_fd < 0) {
8677 /* try to dup to any fd */
8678 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008679 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008680 /* give up */
8681 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008682 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008683 }
8684 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008685// TODO: track & disallow any attempts of user
8686// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008687 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008688 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008689 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008690 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008691
Mike Frysinger38478a62009-05-20 04:48:06 -04008692 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008693 /* If we were run as 'hush &', sleep until we are
8694 * in the foreground (tty pgrp == our pgrp).
8695 * If we get started under a job aware app (like bash),
8696 * make sure we are now in charge so we don't fight over
8697 * who gets the foreground */
8698 while (1) {
8699 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008700 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8701 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008702 break;
8703 /* send TTIN to ourself (should stop us) */
8704 kill(- shell_pgrp, SIGTTIN);
8705 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008706 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008707
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008708 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008709 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008710
Mike Frysinger38478a62009-05-20 04:48:06 -04008711 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008712 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008713 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008714 /* Put ourselves in our own process group
8715 * (bash, too, does this only if ctty is available) */
8716 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8717 /* Grab control of the terminal */
8718 tcsetpgrp(G_interactive_fd, getpid());
8719 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02008720 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008721
8722# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8723 {
8724 const char *hp = get_local_var_value("HISTFILE");
8725 if (!hp) {
8726 hp = get_local_var_value("HOME");
8727 if (hp)
8728 hp = concat_path_file(hp, ".hush_history");
8729 } else {
8730 hp = xstrdup(hp);
8731 }
8732 if (hp) {
8733 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008734 //set_local_var(xasprintf("HISTFILE=%s", ...));
8735 }
8736# if ENABLE_FEATURE_SH_HISTFILESIZE
8737 hp = get_local_var_value("HISTFILESIZE");
8738 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8739# endif
8740 }
8741# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008742 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008743 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008744 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008745#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008746 /* No job control compiled in, only prompt/line editing */
8747 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008748 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8749 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008750 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008751 G_interactive_fd = dup(STDIN_FILENO);
8752 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008753 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008754 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008755 }
8756 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008757 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008758 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008759 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008760 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008761#else
8762 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008763 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008764#endif
8765 /* bash:
8766 * if interactive but not a login shell, sources ~/.bashrc
8767 * (--norc turns this off, --rcfile <file> overrides)
8768 */
8769
8770 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008771 /* note: ash and hush share this string */
8772 printf("\n\n%s %s\n"
8773 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8774 "\n",
8775 bb_banner,
8776 "hush - the humble shell"
8777 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008778 }
8779
Denis Vlasenkof9375282009-04-05 19:13:39 +00008780 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008781
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008782 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008783 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008784}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008785
8786
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008787#if ENABLE_MSH
8788int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8789int msh_main(int argc, char **argv)
8790{
Denys Vlasenkoed6ff5e2016-09-30 12:28:37 +02008791 bb_error_msg("msh is deprecated, please use hush instead");
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008792 return hush_main(argc, argv);
8793}
8794#endif
8795
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008796
8797/*
8798 * Built-ins
8799 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008800static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008801{
8802 return 0;
8803}
8804
Denys Vlasenko265062d2017-01-10 15:13:30 +01008805#if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008806static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008807{
8808 int argc = 0;
8809 while (*argv) {
8810 argc++;
8811 argv++;
8812 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008813 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008814}
Denys Vlasenko265062d2017-01-10 15:13:30 +01008815#endif
8816#if ENABLE_HUSH_TEST
Mike Frysingerccb19592009-10-15 03:31:15 -04008817static int FAST_FUNC builtin_test(char **argv)
8818{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008819 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008820}
Denys Vlasenko265062d2017-01-10 15:13:30 +01008821#endif
Denys Vlasenko1cc68042017-01-09 17:10:04 +01008822#if ENABLE_HUSH_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008823static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008824{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008825 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008826}
Denys Vlasenko1cc68042017-01-09 17:10:04 +01008827#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01008828#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008829static int FAST_FUNC builtin_printf(char **argv)
8830{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008831 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008832}
8833#endif
8834
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008835static char **skip_dash_dash(char **argv)
8836{
8837 argv++;
8838 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8839 argv++;
8840 return argv;
8841}
8842
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008843static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008844{
8845 int rcode = EXIT_SUCCESS;
8846
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008847 argv = skip_dash_dash(argv);
8848 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008849 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008850 /* bash:
8851 * eval "echo Hi; done" ("done" is syntax error):
8852 * "echo Hi" will not execute too.
8853 */
8854 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008855 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008856 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008857 }
8858 return rcode;
8859}
8860
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008861static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008862{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008863 const char *newdir;
8864
8865 argv = skip_dash_dash(argv);
8866 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008867 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008868 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008869 * bash says "bash: cd: HOME not set" and does nothing
8870 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008871 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008872 const char *home = get_local_var_value("HOME");
8873 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008874 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008875 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008876 /* Mimic bash message exactly */
8877 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008878 return EXIT_FAILURE;
8879 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008880 /* Read current dir (get_cwd(1) is inside) and set PWD.
8881 * Note: do not enforce exporting. If PWD was unset or unexported,
8882 * set it again, but do not export. bash does the same.
8883 */
8884 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008885 return EXIT_SUCCESS;
8886}
8887
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008888static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008889{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008890 argv = skip_dash_dash(argv);
8891 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008892 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008893
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008894 /* Careful: we can end up here after [v]fork. Do not restore
8895 * tty pgrp then, only top-level shell process does that */
8896 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8897 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8898
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008899 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008900 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008901 * and tcsetpgrp, and this is inherently racy.
8902 */
8903 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008904}
8905
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008906static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008907{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008908 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008909
8910 /* interactive bash:
8911 * # trap "echo EEE" EXIT
8912 * # exit
8913 * exit
8914 * There are stopped jobs.
8915 * (if there are _stopped_ jobs, running ones don't count)
8916 * # exit
8917 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01008918 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00008919 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008920 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008921 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008922
8923 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008924 argv = skip_dash_dash(argv);
8925 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008926 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008927 /* mimic bash: exit 123abc == exit 255 + error msg */
8928 xfunc_error_retval = 255;
8929 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008930 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008931}
8932
Denys Vlasenko41ade052017-01-08 18:56:24 +01008933#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008934static void print_escaped(const char *s)
8935{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008936 if (*s == '\'')
8937 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008938 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008939 const char *p = strchrnul(s, '\'');
8940 /* print 'xxxx', possibly just '' */
8941 printf("'%.*s'", (int)(p - s), s);
8942 if (*p == '\0')
8943 break;
8944 s = p;
8945 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008946 /* s points to '; print "'''...'''" */
8947 putchar('"');
8948 do putchar('\''); while (*++s == '\'');
8949 putchar('"');
8950 } while (*s);
8951}
Denys Vlasenko41ade052017-01-08 18:56:24 +01008952#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008953
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01008954#if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL
8955# if !ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02008956#define helper_export_local(argv, exp, lvl) \
8957 helper_export_local(argv, exp)
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01008958# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02008959static void helper_export_local(char **argv, int exp, int lvl)
8960{
8961 do {
8962 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008963 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008964
8965 /* So far we do not check that name is valid (TODO?) */
8966
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008967 if (*name_end == '\0') {
8968 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008969
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008970 vpp = get_ptr_to_local_var(name, name_end - name);
8971 var = vpp ? *vpp : NULL;
8972
Denys Vlasenko295fef82009-06-03 12:47:26 +02008973 if (exp == -1) { /* unexporting? */
8974 /* export -n NAME (without =VALUE) */
8975 if (var) {
8976 var->flg_export = 0;
8977 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8978 unsetenv(name);
8979 } /* else: export -n NOT_EXISTING_VAR: no-op */
8980 continue;
8981 }
8982 if (exp == 1) { /* exporting? */
8983 /* export NAME (without =VALUE) */
8984 if (var) {
8985 var->flg_export = 1;
8986 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8987 putenv(var->varstr);
8988 continue;
8989 }
8990 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01008991# if ENABLE_HUSH_LOCAL
Denys Vlasenko61508d92016-10-02 21:12:02 +02008992 if (exp == 0 /* local? */
8993 && var && var->func_nest_level == lvl
8994 ) {
8995 /* "local x=abc; ...; local x" - ignore second local decl */
Denys Vlasenko80729a42016-10-02 22:33:15 +02008996 continue;
Denys Vlasenko61508d92016-10-02 21:12:02 +02008997 }
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01008998# endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02008999 /* Exporting non-existing variable.
9000 * bash does not put it in environment,
9001 * but remembers that it is exported,
9002 * and does put it in env when it is set later.
9003 * We just set it to "" and export. */
9004 /* Or, it's "local NAME" (without =VALUE).
9005 * bash sets the value to "". */
9006 name = xasprintf("%s=", name);
9007 } else {
9008 /* (Un)exporting/making local NAME=VALUE */
9009 name = xstrdup(name);
9010 }
9011 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
9012 } while (*++argv);
9013}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009014#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02009015
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009016#if ENABLE_HUSH_EXPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009017static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009018{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00009019 unsigned opt_unexport;
9020
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02009021#if ENABLE_HUSH_EXPORT_N
9022 /* "!": do not abort on errors */
9023 opt_unexport = getopt32(argv, "!n");
9024 if (opt_unexport == (uint32_t)-1)
9025 return EXIT_FAILURE;
9026 argv += optind;
9027#else
9028 opt_unexport = 0;
9029 argv++;
9030#endif
9031
9032 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009033 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009034 if (e) {
9035 while (*e) {
9036#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009037 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009038#else
9039 /* ash emits: export VAR='VAL'
9040 * bash: declare -x VAR="VAL"
9041 * we follow ash example */
9042 const char *s = *e++;
9043 const char *p = strchr(s, '=');
9044
9045 if (!p) /* wtf? take next variable */
9046 continue;
9047 /* export var= */
9048 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009049 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009050 putchar('\n');
9051#endif
9052 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009053 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009054 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009055 return EXIT_SUCCESS;
9056 }
9057
Denys Vlasenko295fef82009-06-03 12:47:26 +02009058 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009059
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009060 return EXIT_SUCCESS;
9061}
Denys Vlasenko6ec76d82017-01-08 18:40:41 +01009062#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009063
Denys Vlasenko295fef82009-06-03 12:47:26 +02009064#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009065static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009066{
9067 if (G.func_nest_level == 0) {
9068 bb_error_msg("%s: not in a function", argv[0]);
9069 return EXIT_FAILURE; /* bash compat */
9070 }
9071 helper_export_local(argv, 0, G.func_nest_level);
9072 return EXIT_SUCCESS;
9073}
9074#endif
9075
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009076#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009077/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9078static int FAST_FUNC builtin_unset(char **argv)
9079{
9080 int ret;
9081 unsigned opts;
9082
9083 /* "!": do not abort on errors */
9084 /* "+": stop at 1st non-option */
9085 opts = getopt32(argv, "!+vf");
9086 if (opts == (unsigned)-1)
9087 return EXIT_FAILURE;
9088 if (opts == 3) {
9089 bb_error_msg("unset: -v and -f are exclusive");
9090 return EXIT_FAILURE;
9091 }
9092 argv += optind;
9093
9094 ret = EXIT_SUCCESS;
9095 while (*argv) {
9096 if (!(opts & 2)) { /* not -f */
9097 if (unset_local_var(*argv)) {
9098 /* unset <nonexistent_var> doesn't fail.
9099 * Error is when one tries to unset RO var.
9100 * Message was printed by unset_local_var. */
9101 ret = EXIT_FAILURE;
9102 }
9103 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009104# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +02009105 else {
9106 unset_func(*argv);
9107 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009108# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009109 argv++;
9110 }
9111 return ret;
9112}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009113#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009114
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009115#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009116/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9117 * built-in 'set' handler
9118 * SUSv3 says:
9119 * set [-abCefhmnuvx] [-o option] [argument...]
9120 * set [+abCefhmnuvx] [+o option] [argument...]
9121 * set -- [argument...]
9122 * set -o
9123 * set +o
9124 * Implementations shall support the options in both their hyphen and
9125 * plus-sign forms. These options can also be specified as options to sh.
9126 * Examples:
9127 * Write out all variables and their values: set
9128 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9129 * Turn on the -x and -v options: set -xv
9130 * Unset all positional parameters: set --
9131 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9132 * Set the positional parameters to the expansion of x, even if x expands
9133 * with a leading '-' or '+': set -- $x
9134 *
9135 * So far, we only support "set -- [argument...]" and some of the short names.
9136 */
9137static int FAST_FUNC builtin_set(char **argv)
9138{
9139 int n;
9140 char **pp, **g_argv;
9141 char *arg = *++argv;
9142
9143 if (arg == NULL) {
9144 struct variable *e;
9145 for (e = G.top_var; e; e = e->next)
9146 puts(e->varstr);
9147 return EXIT_SUCCESS;
9148 }
9149
9150 do {
9151 if (strcmp(arg, "--") == 0) {
9152 ++argv;
9153 goto set_argv;
9154 }
9155 if (arg[0] != '+' && arg[0] != '-')
9156 break;
9157 for (n = 1; arg[n]; ++n) {
9158 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9159 goto error;
9160 if (arg[n] == 'o' && argv[1])
9161 argv++;
9162 }
9163 } while ((arg = *++argv) != NULL);
9164 /* Now argv[0] is 1st argument */
9165
9166 if (arg == NULL)
9167 return EXIT_SUCCESS;
9168 set_argv:
9169
9170 /* NB: G.global_argv[0] ($0) is never freed/changed */
9171 g_argv = G.global_argv;
9172 if (G.global_args_malloced) {
9173 pp = g_argv;
9174 while (*++pp)
9175 free(*pp);
9176 g_argv[1] = NULL;
9177 } else {
9178 G.global_args_malloced = 1;
9179 pp = xzalloc(sizeof(pp[0]) * 2);
9180 pp[0] = g_argv[0]; /* retain $0 */
9181 g_argv = pp;
9182 }
9183 /* This realloc's G.global_argv */
9184 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9185
9186 n = 1;
9187 while (*++pp)
9188 n++;
9189 G.global_argc = n;
9190
9191 return EXIT_SUCCESS;
9192
9193 /* Nothing known, so abort */
9194 error:
9195 bb_error_msg("set: %s: invalid option", arg);
9196 return EXIT_FAILURE;
9197}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009198#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009199
9200static int FAST_FUNC builtin_shift(char **argv)
9201{
9202 int n = 1;
9203 argv = skip_dash_dash(argv);
9204 if (argv[0]) {
9205 n = atoi(argv[0]);
9206 }
9207 if (n >= 0 && n < G.global_argc) {
Denys Vlasenko4e4f88e2017-01-09 07:57:38 +01009208 if (G_global_args_malloced) {
Denys Vlasenko61508d92016-10-02 21:12:02 +02009209 int m = 1;
9210 while (m <= n)
9211 free(G.global_argv[m++]);
9212 }
9213 G.global_argc -= n;
9214 memmove(&G.global_argv[1], &G.global_argv[n+1],
9215 G.global_argc * sizeof(G.global_argv[0]));
9216 return EXIT_SUCCESS;
9217 }
9218 return EXIT_FAILURE;
9219}
9220
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009221#if ENABLE_HUSH_READ
Denys Vlasenko61508d92016-10-02 21:12:02 +02009222/* Interruptibility of read builtin in bash
9223 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9224 *
9225 * Empty trap makes read ignore corresponding signal, for any signal.
9226 *
9227 * SIGINT:
9228 * - terminates non-interactive shell;
9229 * - interrupts read in interactive shell;
9230 * if it has non-empty trap:
9231 * - executes trap and returns to command prompt in interactive shell;
9232 * - executes trap and returns to read in non-interactive shell;
9233 * SIGTERM:
9234 * - is ignored (does not interrupt) read in interactive shell;
9235 * - terminates non-interactive shell;
9236 * if it has non-empty trap:
9237 * - executes trap and returns to read;
9238 * SIGHUP:
9239 * - terminates shell (regardless of interactivity);
9240 * if it has non-empty trap:
9241 * - executes trap and returns to read;
9242 */
9243static int FAST_FUNC builtin_read(char **argv)
9244{
9245 const char *r;
9246 char *opt_n = NULL;
9247 char *opt_p = NULL;
9248 char *opt_t = NULL;
9249 char *opt_u = NULL;
9250 const char *ifs;
9251 int read_flags;
9252
9253 /* "!": do not abort on errors.
9254 * Option string must start with "sr" to match BUILTIN_READ_xxx
9255 */
9256 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9257 if (read_flags == (uint32_t)-1)
9258 return EXIT_FAILURE;
9259 argv += optind;
9260 ifs = get_local_var_value("IFS"); /* can be NULL */
9261
9262 again:
9263 r = shell_builtin_read(set_local_var_from_halves,
9264 argv,
9265 ifs,
9266 read_flags,
9267 opt_n,
9268 opt_p,
9269 opt_t,
9270 opt_u
9271 );
9272
9273 if ((uintptr_t)r == 1 && errno == EINTR) {
9274 unsigned sig = check_and_run_traps();
9275 if (sig && sig != SIGINT)
9276 goto again;
9277 }
9278
9279 if ((uintptr_t)r > 1) {
9280 bb_error_msg("%s", r);
9281 r = (char*)(uintptr_t)1;
9282 }
9283
9284 return (uintptr_t)r;
9285}
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009286#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009287
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009288#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009289static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009290{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009291 int sig;
9292 char *new_cmd;
9293
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009294 if (!G_traps)
9295 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009296
9297 argv++;
9298 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00009299 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009300 /* No args: print all trapped */
9301 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009302 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009303 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009304 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02009305 /* note: bash adds "SIG", but only if invoked
9306 * as "bash". If called as "sh", or if set -o posix,
9307 * then it prints short signal names.
9308 * We are printing short names: */
9309 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009310 }
9311 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009312 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009313 return EXIT_SUCCESS;
9314 }
9315
9316 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009317 /* If first arg is a number: reset all specified signals */
9318 sig = bb_strtou(*argv, NULL, 10);
9319 if (errno == 0) {
9320 int ret;
9321 process_sig_list:
9322 ret = EXIT_SUCCESS;
9323 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009324 sighandler_t handler;
9325
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009326 sig = get_signum(*argv++);
9327 if (sig < 0 || sig >= NSIG) {
9328 ret = EXIT_FAILURE;
9329 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00009330 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009331 continue;
9332 }
9333
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009334 free(G_traps[sig]);
9335 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009336
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009337 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009338 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009339
9340 /* There is no signal for 0 (EXIT) */
9341 if (sig == 0)
9342 continue;
9343
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009344 if (new_cmd)
9345 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9346 else
9347 /* We are removing trap handler */
9348 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02009349 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009350 }
9351 return ret;
9352 }
9353
9354 if (!argv[1]) { /* no second arg */
9355 bb_error_msg("trap: invalid arguments");
9356 return EXIT_FAILURE;
9357 }
9358
9359 /* First arg is "-": reset all specified to default */
9360 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9361 /* Everything else: set arg as signal handler
9362 * (includes "" case, which ignores signal) */
9363 if (argv[0][0] == '-') {
9364 if (argv[0][1] == '\0') { /* "-" */
9365 /* new_cmd remains NULL: "reset these sigs" */
9366 goto reset_traps;
9367 }
9368 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9369 argv++;
9370 }
9371 /* else: "-something", no special meaning */
9372 }
9373 new_cmd = *argv;
9374 reset_traps:
9375 argv++;
9376 goto process_sig_list;
9377}
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009378#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009379
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009380#if ENABLE_HUSH_TYPE
Mike Frysinger93cadc22009-05-27 17:06:25 -04009381/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009382static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04009383{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009384 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04009385
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009386 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04009387 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02009388 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04009389
9390 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009391 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009392 type = "an alias";*/
9393#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009394 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009395 type = "a function";
9396#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009397 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009398 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009399 else if ((path = find_in_path(*argv)) != NULL)
9400 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009401 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009402 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04009403 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009404 continue;
9405 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04009406
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009407 printf("%s is %s\n", *argv, type);
9408 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04009409 }
9410
9411 return ret;
9412}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009413#endif
Mike Frysinger93cadc22009-05-27 17:06:25 -04009414
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009415#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009416static struct pipe *parse_jobspec(const char *str)
9417{
9418 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01009419 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009420
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01009421 if (sscanf(str, "%%%u", &jobnum) != 1) {
9422 if (str[0] != '%'
9423 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
9424 ) {
9425 bb_error_msg("bad argument '%s'", str);
9426 return NULL;
9427 }
9428 /* It is "%%", "%+" or "%" - current job */
9429 jobnum = G.last_jobid;
9430 if (jobnum == 0) {
9431 bb_error_msg("no current job");
9432 return NULL;
9433 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009434 }
9435 for (pi = G.job_list; pi; pi = pi->next) {
9436 if (pi->jobid == jobnum) {
9437 return pi;
9438 }
9439 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +01009440 bb_error_msg("%u: no such job", jobnum);
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009441 return NULL;
9442}
9443
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009444/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009445static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009446{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009447 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009448 struct pipe *pi;
9449
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009450 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009451 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009452
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009453 /* If they gave us no args, assume they want the last backgrounded task */
9454 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00009455 for (pi = G.job_list; pi; pi = pi->next) {
9456 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009457 goto found;
9458 }
9459 }
9460 bb_error_msg("%s: no current job", argv[0]);
9461 return EXIT_FAILURE;
9462 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009463
9464 pi = parse_jobspec(argv[1]);
9465 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009466 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009467 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00009468 /* TODO: bash prints a string representation
9469 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04009470 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009471 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009472 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009473 }
9474
9475 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009476 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9477 for (i = 0; i < pi->num_cmds; i++) {
9478 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009479 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009480 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009481
9482 i = kill(- pi->pgrp, SIGCONT);
9483 if (i < 0) {
9484 if (errno == ESRCH) {
9485 delete_finished_bg_job(pi);
9486 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009487 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009488 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009489 }
9490
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009491 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009492 remove_bg_job(pi);
9493 return checkjobs_and_fg_shell(pi);
9494 }
9495 return EXIT_SUCCESS;
9496}
9497#endif
9498
9499#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009500static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009501{
9502 const struct built_in_command *x;
9503
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009504 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009505 "Built-in commands:\n"
9506 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009507 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01009508 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009509 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009510 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009511 return EXIT_SUCCESS;
9512}
9513#endif
9514
Denys Vlasenkoff463a82013-05-12 02:45:23 +02009515#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02009516static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9517{
9518 show_history(G.line_input_state);
9519 return EXIT_SUCCESS;
9520}
9521#endif
9522
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009523#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009524static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009525{
9526 struct pipe *job;
9527 const char *status_string;
9528
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009529 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denis Vlasenko87a86552008-07-29 19:43:10 +00009530 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009531 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009532 status_string = "Stopped";
9533 else
9534 status_string = "Running";
9535
9536 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9537 }
9538 return EXIT_SUCCESS;
9539}
9540#endif
9541
Denys Vlasenko44719692017-01-08 18:44:41 +01009542#if ENABLE_HUSH_MEMLEAK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009543static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009544{
9545 void *p;
9546 unsigned long l;
9547
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009548# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02009549 /* Optional. Reduces probability of false positives */
9550 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009551# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009552 /* Crude attempt to find where "free memory" starts,
9553 * sans fragmentation. */
9554 p = malloc(240);
9555 l = (unsigned long)p;
9556 free(p);
9557 p = malloc(3400);
9558 if (l < (unsigned long)p) l = (unsigned long)p;
9559 free(p);
9560
Denys Vlasenko7f0ebbc2016-10-03 17:42:53 +02009561
9562# if 0 /* debug */
9563 {
9564 struct mallinfo mi = mallinfo();
9565 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
9566 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
9567 }
9568# endif
9569
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009570 if (!G.memleak_value)
9571 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02009572
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009573 l -= G.memleak_value;
9574 if ((long)l < 0)
9575 l = 0;
9576 l /= 1024;
9577 if (l > 127)
9578 l = 127;
9579
9580 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9581 return l;
9582}
9583#endif
9584
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009585static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009586{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009587 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009588 return EXIT_SUCCESS;
9589}
9590
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009591static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009592{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009593 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009594 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009595 save_arg_t sv;
Denys Vlasenko2b155902017-01-09 08:13:21 +01009596 char *args_need_save;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009597#if ENABLE_HUSH_FUNCTIONS
9598 smallint sv_flg;
9599#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009600
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009601 argv = skip_dash_dash(argv);
9602 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009603 if (!filename) {
9604 /* bash says: "bash: .: filename argument required" */
9605 return 2; /* bash compat */
9606 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009607 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009608 if (!strchr(filename, '/')) {
9609 arg_path = find_in_path(filename);
9610 if (arg_path)
9611 filename = arg_path;
9612 }
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009613 input = remember_FILE(fopen_or_warn(filename, "r"));
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009614 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009615 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009616 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009617 /* POSIX: non-interactive shell should abort here,
9618 * not merely fail. So far no one complained :)
9619 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009620 return EXIT_FAILURE;
9621 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009622
Mike Frysinger885b6f22009-04-18 21:04:25 +00009623#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009624 sv_flg = G_flag_return_in_progress;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009625 /* "we are inside sourced file, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009626 G_flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009627#endif
Denys Vlasenko2b155902017-01-09 08:13:21 +01009628 args_need_save = argv[1]; /* used as a boolean variable */
9629 if (args_need_save)
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009630 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009631
Denys Vlasenko992e0ff2016-09-29 01:27:09 +02009632 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9633 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009634 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009635 fclose_and_forget(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009636
Denys Vlasenko2b155902017-01-09 08:13:21 +01009637 if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009638 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00009639#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009640 G_flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009641#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009642
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009643 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009644}
9645
Denys Vlasenkod5933b12017-01-08 18:31:39 +01009646#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009647static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009648{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009649 int rc;
9650 mode_t mask;
9651
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009652 rc = 1;
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009653 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009654 argv = skip_dash_dash(argv);
9655 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009656 mode_t old_mask = mask;
9657
Denys Vlasenko6283f982015-10-07 16:56:20 +02009658 /* numeric umasks are taken as-is */
9659 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9660 if (!isdigit(argv[0][0]))
9661 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009662 mask = bb_parse_mode(argv[0], mask);
Denys Vlasenko6283f982015-10-07 16:56:20 +02009663 if (!isdigit(argv[0][0]))
9664 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009665 if ((unsigned)mask > 0777) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009666 mask = old_mask;
9667 /* bash messages:
9668 * bash: umask: 'q': invalid symbolic mode operator
9669 * bash: umask: 999: octal number out of range
9670 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02009671 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009672 rc = 0;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009673 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009674 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009675 /* Mimic bash */
9676 printf("%04o\n", (unsigned) mask);
9677 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009678 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009679 umask(mask);
9680
9681 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009682}
Denys Vlasenkod5933b12017-01-08 18:31:39 +01009683#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009684
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009685#if ENABLE_HUSH_KILL
9686static int FAST_FUNC builtin_kill(char **argv)
9687{
9688 int ret = 0;
9689
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +01009690# if ENABLE_HUSH_JOB
9691 if (argv[1] && strcmp(argv[1], "-l") != 0) {
9692 int i = 1;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009693
9694 do {
9695 struct pipe *pi;
9696 char *dst;
9697 int j, n;
9698
9699 if (argv[i][0] != '%')
9700 continue;
9701 /*
9702 * "kill %N" - job kill
9703 * Converting to pgrp / pid kill
9704 */
9705 pi = parse_jobspec(argv[i]);
9706 if (!pi) {
9707 /* Eat bad jobspec */
9708 j = i;
9709 do {
9710 j++;
9711 argv[j - 1] = argv[j];
9712 } while (argv[j]);
9713 ret = 1;
9714 i--;
9715 continue;
9716 }
9717 /*
9718 * In jobs started under job control, we signal
9719 * entire process group by kill -PGRP_ID.
9720 * This happens, f.e., in interactive shell.
9721 *
9722 * Otherwise, we signal each child via
9723 * kill PID1 PID2 PID3.
9724 * Testcases:
9725 * sh -c 'sleep 1|sleep 1 & kill %1'
9726 * sh -c 'true|sleep 2 & sleep 1; kill %1'
9727 * sh -c 'true|sleep 1 & sleep 2; kill %1'
9728 */
Denys Vlasenko5362cc42017-01-09 05:57:13 +01009729 n = G_interactive_fd ? 1 : pi->num_cmds;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009730 dst = alloca(n * sizeof(int)*4);
9731 argv[i] = dst;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009732 if (G_interactive_fd)
9733 dst += sprintf(dst, " -%u", (int)pi->pgrp);
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +01009734 else for (j = 0; j < n; j++) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009735 struct command *cmd = &pi->cmds[j];
9736 /* Skip exited members of the job */
9737 if (cmd->pid == 0)
9738 continue;
9739 /*
9740 * kill_main has matching code to expect
9741 * leading space. Needed to not confuse
9742 * negative pids with "kill -SIGNAL_NO" syntax
9743 */
9744 dst += sprintf(dst, " %u", (int)cmd->pid);
9745 }
9746 *dst = '\0';
9747 } while (argv[++i]);
9748 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +01009749# endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009750
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +01009751 if (argv[1] || ret == 0) {
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009752 ret = run_applet_main(argv, kill_main);
9753 }
Denys Vlasenkofd68f1e2017-01-09 05:47:57 +01009754 /* else: ret = 1, "kill %bad_jobspec" case */
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009755 return ret;
9756}
9757#endif
9758
9759#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +00009760/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009761#if !ENABLE_HUSH_JOB
9762# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
9763#endif
9764static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +02009765{
9766 int ret = 0;
9767 for (;;) {
9768 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009769 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +02009770
Denys Vlasenko830ea352016-11-08 04:59:11 +01009771 if (!sigisemptyset(&G.pending_set))
9772 goto check_sig;
9773
Denys Vlasenko7e675362016-10-28 21:57:31 +02009774 /* waitpid is not interruptible by SA_RESTARTed
9775 * signals which we use. Thus, this ugly dance:
9776 */
9777
9778 /* Make sure possible SIGCHLD is stored in kernel's
9779 * pending signal mask before we call waitpid.
9780 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009781 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +02009782 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009783 sigfillset(&oldset); /* block all signals, remember old set */
9784 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009785
9786 if (!sigisemptyset(&G.pending_set)) {
9787 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009788 goto restore;
9789 }
9790
9791 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009792/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009793 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009794 debug_printf_exec("checkjobs:%d\n", ret);
9795#if ENABLE_HUSH_JOB
9796 if (waitfor_pipe) {
9797 int rcode = job_exited_or_stopped(waitfor_pipe);
9798 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
9799 if (rcode >= 0) {
9800 ret = rcode;
9801 sigprocmask(SIG_SETMASK, &oldset, NULL);
9802 break;
9803 }
9804 }
9805#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009806 /* if ECHILD, there are no children (ret is -1 or 0) */
9807 /* if ret == 0, no children changed state */
9808 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009809 if (errno == ECHILD || ret) {
9810 ret--;
9811 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009812 ret = 0;
9813 sigprocmask(SIG_SETMASK, &oldset, NULL);
9814 break;
9815 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009816 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009817 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9818 /* Note: sigsuspend invokes signal handler */
9819 sigsuspend(&oldset);
9820 restore:
9821 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +01009822 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009823 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009824 sig = check_and_run_traps();
9825 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009826 ret = 128 + sig;
9827 break;
9828 }
9829 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9830 }
9831 return ret;
9832}
9833
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009834static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00009835{
Denys Vlasenko7e675362016-10-28 21:57:31 +02009836 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009837 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009838
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009839 argv = skip_dash_dash(argv);
9840 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009841 /* Don't care about wait results */
9842 /* Note 1: must wait until there are no more children */
9843 /* Note 2: must be interruptible */
9844 /* Examples:
9845 * $ sleep 3 & sleep 6 & wait
9846 * [1] 30934 sleep 3
9847 * [2] 30935 sleep 6
9848 * [1] Done sleep 3
9849 * [2] Done sleep 6
9850 * $ sleep 3 & sleep 6 & wait
9851 * [1] 30936 sleep 3
9852 * [2] 30937 sleep 6
9853 * [1] Done sleep 3
9854 * ^C <-- after ~4 sec from keyboard
9855 * $
9856 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009857 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009858 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009859
Denys Vlasenko7e675362016-10-28 21:57:31 +02009860 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009861 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009862 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009863#if ENABLE_HUSH_JOB
9864 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +01009865 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01009866 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009867 wait_pipe = parse_jobspec(*argv);
9868 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +01009869 ret = job_exited_or_stopped(wait_pipe);
9870 if (ret < 0)
9871 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009872 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01009873 /* else: parse_jobspec() already emitted error msg */
9874 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009875 }
9876#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00009877 /* mimic bash message */
9878 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009879 ret = EXIT_FAILURE;
9880 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009881 }
Denys Vlasenko02affb42016-11-08 00:59:29 +01009882
Denys Vlasenko7e675362016-10-28 21:57:31 +02009883 /* Do we have such child? */
9884 ret = waitpid(pid, &status, WNOHANG);
9885 if (ret < 0) {
9886 /* No */
9887 if (errno == ECHILD) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009888 if (G.last_bg_pid > 0 && pid == G.last_bg_pid) {
9889 /* "wait $!" but last bg task has already exited. Try:
9890 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
9891 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +01009892 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009893 */
Denys Vlasenko26ad94b2016-11-07 23:07:21 +01009894 /* ret = G.last_bg_pid_exitstatus - FIXME */
9895 } else {
9896 /* Example: "wait 1". mimic bash message */
9897 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009898 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009899 } else {
9900 /* ??? */
9901 bb_perror_msg("wait %s", *argv);
9902 }
9903 ret = 127;
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009904 continue; /* bash checks all argv[] */
9905 }
9906 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009907 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +01009908 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009909 } else {
9910 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +01009911 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +02009912 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009913 if (WIFSIGNALED(status))
9914 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009915 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009916 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009917
9918 return ret;
9919}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009920#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +00009921
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009922#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9923static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9924{
9925 if (argv[1]) {
9926 def = bb_strtou(argv[1], NULL, 10);
9927 if (errno || def < def_min || argv[2]) {
9928 bb_error_msg("%s: bad arguments", argv[0]);
9929 def = UINT_MAX;
9930 }
9931 }
9932 return def;
9933}
9934#endif
9935
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009936#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009937static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009938{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009939 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009940 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009941 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +02009942 /* if we came from builtin_continue(), need to undo "= 1" */
9943 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009944 return EXIT_SUCCESS; /* bash compat */
9945 }
Denys Vlasenko49117b42016-07-21 14:40:08 +02009946 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009947
9948 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9949 if (depth == UINT_MAX)
9950 G.flag_break_continue = BC_BREAK;
9951 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009952 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009953
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009954 return EXIT_SUCCESS;
9955}
9956
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009957static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009958{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009959 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9960 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009961}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009962#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009963
9964#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009965static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009966{
9967 int rc;
9968
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009969 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009970 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9971 return EXIT_FAILURE; /* bash compat */
9972 }
9973
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009974 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009975
9976 /* bash:
9977 * out of range: wraps around at 256, does not error out
9978 * non-numeric param:
9979 * f() { false; return qwe; }; f; echo $?
9980 * bash: return: qwe: numeric argument required <== we do this
9981 * 255 <== we also do this
9982 */
9983 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9984 return rc;
9985}
9986#endif