blob: e3dcf2c382f3a058bfec8bf6b97dcd0e26bb035d [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 Vlasenko8da415e2010-12-05 01:30:14 +010084#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85 || defined(__APPLE__) \
86 )
87# include <malloc.h> /* for malloc_trim */
88#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +000089#include <glob.h>
90/* #include <dmalloc.h> */
91#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000092# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000093#endif
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020094#include <sys/utsname.h> /* for setting $HOSTNAME */
Denys Vlasenko03dad222010-01-12 23:29:57 +010095
Denys Vlasenko20704f02011-03-23 17:59:27 +010096#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
97#include "unicode.h"
Denys Vlasenko03dad222010-01-12 23:29:57 +010098#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000099#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +0000100#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +0200101#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200102# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +0200103#else
104# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200105#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200106#ifndef F_DUPFD_CLOEXEC
107# define F_DUPFD_CLOEXEC F_DUPFD
108#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000109#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200110# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000111#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000112
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:config HUSH
114//config: bool "hush"
115//config: default y
116//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200117//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200118//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119//config: case/esac. Redirections, here documents, $((arithmetic))
120//config: and functions are supported.
121//config:
122//config: It will compile and work on no-mmu systems.
123//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +0200124//config: It does not handle select, aliases, tilde expansion,
125//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200126//config:
127//config:config HUSH_BASH_COMPAT
128//config: bool "bash-compatible extensions"
129//config: default y
130//config: depends on HUSH
131//config: help
132//config: Enable bash-compatible extensions.
133//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200134//config:config HUSH_BRACE_EXPANSION
135//config: bool "Brace expansion"
136//config: default y
137//config: depends on HUSH_BASH_COMPAT
138//config: help
139//config: Enable {abc,def} extension.
140//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200141//config:config HUSH_HELP
142//config: bool "help builtin"
143//config: default y
144//config: depends on HUSH
145//config: help
146//config: Enable help builtin in hush. Code size + ~1 kbyte.
147//config:
148//config:config HUSH_INTERACTIVE
149//config: bool "Interactive mode"
150//config: default y
151//config: depends on HUSH
152//config: help
153//config: Enable interactive mode (prompt and command editing).
154//config: Without this, hush simply reads and executes commands
155//config: from stdin just like a shell script from a file.
156//config: No prompt, no PS1/PS2 magic shell variables.
157//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200158//config:config HUSH_SAVEHISTORY
159//config: bool "Save command history to .hush_history"
160//config: default y
161//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
162//config: help
163//config: Enable history saving in hush.
164//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:config HUSH_JOB
166//config: bool "Job control"
167//config: default y
168//config: depends on HUSH_INTERACTIVE
169//config: help
170//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
171//config: command (not entire shell), fg/bg builtins work. Without this option,
172//config: "cmd &" still works by simply spawning a process and immediately
173//config: prompting for next command (or executing next command in a script),
174//config: but no separate process group is formed.
175//config:
176//config:config HUSH_TICK
177//config: bool "Process substitution"
178//config: default y
179//config: depends on HUSH
180//config: help
181//config: Enable process substitution `command` and $(command) in hush.
182//config:
183//config:config HUSH_IF
184//config: bool "Support if/then/elif/else/fi"
185//config: default y
186//config: depends on HUSH
187//config: help
188//config: Enable if/then/elif/else/fi in hush.
189//config:
190//config:config HUSH_LOOPS
191//config: bool "Support for, while and until loops"
192//config: default y
193//config: depends on HUSH
194//config: help
195//config: Enable for, while and until loops in hush.
196//config:
197//config:config HUSH_CASE
198//config: bool "Support case ... esac statement"
199//config: default y
200//config: depends on HUSH
201//config: help
202//config: Enable case ... esac statement in hush. +400 bytes.
203//config:
204//config:config HUSH_FUNCTIONS
205//config: bool "Support funcname() { commands; } syntax"
206//config: default y
207//config: depends on HUSH
208//config: help
209//config: Enable support for shell functions in hush. +800 bytes.
210//config:
211//config:config HUSH_LOCAL
212//config: bool "Support local builtin"
213//config: default y
214//config: depends on HUSH_FUNCTIONS
215//config: help
216//config: Enable support for local variables in functions.
217//config:
218//config:config HUSH_RANDOM_SUPPORT
219//config: bool "Pseudorandom generator and $RANDOM variable"
220//config: default y
221//config: depends on HUSH
222//config: help
223//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
224//config: Each read of "$RANDOM" will generate a new pseudorandom value.
225//config:
226//config:config HUSH_EXPORT_N
227//config: bool "Support 'export -n' option"
228//config: default y
229//config: depends on HUSH
230//config: help
231//config: export -n unexports variables. It is a bash extension.
232//config:
233//config:config HUSH_MODE_X
234//config: bool "Support 'hush -x' option and 'set -x' command"
235//config: default y
236//config: depends on HUSH
237//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200238//config: This instructs hush to print commands before execution.
239//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200240//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200241//config:config MSH
242//config: bool "msh (deprecated: aliased to hush)"
243//config: default n
244//config: select HUSH
245//config: help
246//config: msh is deprecated and will be removed, please migrate to hush.
247//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200248
Denys Vlasenko20704f02011-03-23 17:59:27 +0100249//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
250//applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
251//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
252//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
253
254//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
255//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
256
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100257/* -i (interactive) and -s (read stdin) are also accepted,
258 * but currently do nothing, therefore aren't shown in help.
259 * NOMMU-specific options are not meant to be used by users,
260 * therefore we don't show them either.
261 */
262//usage:#define hush_trivial_usage
Denys Vlasenkof58f7052011-05-12 02:10:33 +0200263//usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100264//usage:#define hush_full_usage "\n\n"
265//usage: "Unix shell interpreter"
266
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100267//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100268//usage:#define msh_full_usage hush_full_usage
269
270//usage:#if ENABLE_FEATURE_SH_IS_HUSH
271//usage:# define sh_trivial_usage hush_trivial_usage
272//usage:# define sh_full_usage hush_full_usage
273//usage:#endif
274//usage:#if ENABLE_FEATURE_BASH_IS_HUSH
275//usage:# define bash_trivial_usage hush_trivial_usage
276//usage:# define bash_full_usage hush_full_usage
277//usage:#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200278
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000279
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200280/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000281#define LEAK_HUNTING 0
282#define BUILD_AS_NOMMU 0
283/* Enable/disable sanity checks. Ok to enable in production,
284 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
285 * Keeping 1 for now even in released versions.
286 */
287#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200288/* Slightly bigger (+200 bytes), but faster hush.
289 * So far it only enables a trick with counting SIGCHLDs and forks,
290 * which allows us to do fewer waitpid's.
291 * (we can detect a case where neither forks were done nor SIGCHLDs happened
292 * and therefore waitpid will return the same result as last time)
293 */
294#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200295/* TODO: implement simplified code for users which do not need ${var%...} ops
296 * So far ${var%...} ops are always enabled:
297 */
298#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000299
300
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000301#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000302# undef BB_MMU
303# undef USE_FOR_NOMMU
304# undef USE_FOR_MMU
305# define BB_MMU 0
306# define USE_FOR_NOMMU(...) __VA_ARGS__
307# define USE_FOR_MMU(...)
308#endif
309
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200310#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100311#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000312/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000313# undef CONFIG_FEATURE_SH_STANDALONE
314# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000315# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100316# undef IF_NOT_FEATURE_SH_STANDALONE
317# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000318# define IF_FEATURE_SH_STANDALONE(...)
319# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000320#endif
321
Denis Vlasenko05743d72008-02-10 12:10:08 +0000322#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000323# undef ENABLE_FEATURE_EDITING
324# define ENABLE_FEATURE_EDITING 0
325# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
326# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200327# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
328# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000329#endif
330
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000331/* Do we support ANY keywords? */
332#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000333# define HAS_KEYWORDS 1
334# define IF_HAS_KEYWORDS(...) __VA_ARGS__
335# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000336#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000337# define HAS_KEYWORDS 0
338# define IF_HAS_KEYWORDS(...)
339# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000340#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000341
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000342/* If you comment out one of these below, it will be #defined later
343 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000344#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000345/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000346#define debug_printf_parse(...) do {} while (0)
347#define debug_print_tree(a, b) do {} while (0)
348#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000349#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000350#define debug_printf_jobs(...) do {} while (0)
351#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200352#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000353#define debug_printf_glob(...) do {} while (0)
354#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000355#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000356#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000357
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000358#define ERR_PTR ((void*)(long)1)
359
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200360#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000361
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200362#define _SPECIAL_VARS_STR "_*@$!?#"
363#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
364#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200365#if ENABLE_HUSH_BASH_COMPAT
366/* Support / and // replace ops */
367/* Note that // is stored as \ in "encoded" string representation */
368# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
369# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
370# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
371#else
372# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
373# define VAR_SUBST_OPS "%#:-=+?"
374# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
375#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200376
377#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000378
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200379struct variable;
380
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000381static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
382
383/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000384 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000385 */
386#if !BB_MMU
387typedef struct nommu_save_t {
388 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200389 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000390 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000391 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000392} nommu_save_t;
393#endif
394
Denys Vlasenko9b782552010-09-08 13:33:26 +0200395enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000396 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000397#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000398 RES_IF ,
399 RES_THEN ,
400 RES_ELIF ,
401 RES_ELSE ,
402 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000403#endif
404#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000405 RES_FOR ,
406 RES_WHILE ,
407 RES_UNTIL ,
408 RES_DO ,
409 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000410#endif
411#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000412 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000413#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000414#if ENABLE_HUSH_CASE
415 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200416 /* three pseudo-keywords support contrived "case" syntax: */
417 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
418 RES_MATCH , /* "word)" */
419 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000420 RES_ESAC ,
421#endif
422 RES_XXXX ,
423 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200424};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000425
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000426typedef struct o_string {
427 char *data;
428 int length; /* position where data is appended */
429 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200430 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000431 /* At least some part of the string was inside '' or "",
432 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200433 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000434 smallint has_empty_slot;
435 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
436} o_string;
437enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200438 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
439 EXP_FLAG_GLOB = 0x2,
440 /* Protect newly added chars against globbing
441 * by prepending \ to *, ?, [, \ */
442 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
443};
444enum {
445 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000446 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200447 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200448 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200449 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000450};
451/* Used for initialization: o_string foo = NULL_O_STRING; */
452#define NULL_O_STRING { NULL }
453
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200454#ifndef debug_printf_parse
455static const char *const assignment_flag[] = {
456 "MAYBE_ASSIGNMENT",
457 "DEFINITELY_ASSIGNMENT",
458 "NOT_ASSIGNMENT",
459 "WORD_IS_KEYWORD",
460};
461#endif
462
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000463typedef struct in_str {
464 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000465#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000466 smallint promptmode; /* 0: PS1, 1: PS2 */
467#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200468 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200469 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000470 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200471 int (*get) (struct in_str *) FAST_FUNC;
472 int (*peek) (struct in_str *) FAST_FUNC;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200473 int (*peek2) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000474} in_str;
475#define i_getch(input) ((input)->get(input))
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200476#define i_peek(input) ((input)->peek(input))
477#define i_peek2(input) ((input)->peek2(input))
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000478
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200479/* The descrip member of this structure is only used to make
480 * debugging output pretty */
481static const struct {
482 int mode;
483 signed char default_fd;
484 char descrip[3];
485} redir_table[] = {
486 { O_RDONLY, 0, "<" },
487 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
488 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
489 { O_CREAT|O_RDWR, 1, "<>" },
490 { O_RDONLY, 0, "<<" },
491/* Should not be needed. Bogus default_fd helps in debugging */
492/* { O_RDONLY, 77, "<<" }, */
493};
494
Eric Andersen25f27032001-04-26 23:22:31 +0000495struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000496 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000497 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000498 int rd_fd; /* fd to redirect */
499 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
500 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000501 smallint rd_type; /* (enum redir_type) */
502 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000503 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200504 * bit 0: do we need to trim leading tabs?
505 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000506 */
Eric Andersen25f27032001-04-26 23:22:31 +0000507};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000508typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200509 REDIRECT_INPUT = 0,
510 REDIRECT_OVERWRITE = 1,
511 REDIRECT_APPEND = 2,
512 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000513 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200514 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000515
516 REDIRFD_CLOSE = -3,
517 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000518 REDIRFD_TO_FILE = -1,
519 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000520
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000521 HEREDOC_SKIPTABS = 1,
522 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000523} redir_type;
524
Eric Andersen25f27032001-04-26 23:22:31 +0000525
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000526struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000527 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000528 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200529 smallint cmd_type; /* CMD_xxx */
530#define CMD_NORMAL 0
531#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200532#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200533/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200534# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000535#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200536#if ENABLE_HUSH_FUNCTIONS
537# define CMD_FUNCDEF 3
538#endif
539
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100540 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200541 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
542 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000543#if !BB_MMU
544 char *group_as_string;
545#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000546#if ENABLE_HUSH_FUNCTIONS
547 struct function *child_func;
548/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200549 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000550 * When we execute "f1() {a;}" cmd, we create new function and clear
551 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200552 * When we execute "f1() {b;}", we notice that f1 exists,
553 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000554 * we put those fields back into cmd->xxx
555 * (struct function has ->parent_cmd ptr to facilitate that).
556 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
557 * Without this trick, loop would execute a;b;b;b;...
558 * instead of correct sequence a;b;a;b;...
559 * When command is freed, it severs the link
560 * (sets ->child_func->parent_cmd to NULL).
561 */
562#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000563 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000564/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
565 * and on execution these are substituted with their values.
566 * Substitution can make _several_ words out of one argv[n]!
567 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000568 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000569 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000570 struct redir_struct *redirects; /* I/O redirections */
571};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000572/* Is there anything in this command at all? */
573#define IS_NULL_CMD(cmd) \
574 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
575
Eric Andersen25f27032001-04-26 23:22:31 +0000576struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000577 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000578 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000579 int alive_cmds; /* number of commands running (not exited) */
580 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000581#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000582 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000583 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000584 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000585#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000586 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000587 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000588 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
589 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000590};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000591typedef enum pipe_style {
592 PIPE_SEQ = 1,
593 PIPE_AND = 2,
594 PIPE_OR = 3,
595 PIPE_BG = 4,
596} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000597/* Is there anything in this pipe at all? */
598#define IS_NULL_PIPE(pi) \
599 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000600
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000601/* This holds pointers to the various results of parsing */
602struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000603 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000604 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000605 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000606 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000607 /* last command in pipe (being constructed right now) */
608 struct command *command;
609 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000610 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000611#if !BB_MMU
612 o_string as_string;
613#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000614#if HAS_KEYWORDS
615 smallint ctx_res_w;
616 smallint ctx_inverted; /* "! cmd | cmd" */
617#if ENABLE_HUSH_CASE
618 smallint ctx_dsemicolon; /* ";;" seen */
619#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000620 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
621 int old_flag;
622 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000623 * example: "if pipe1; pipe2; then pipe3; fi"
624 * when we see "if" or "then", we malloc and copy current context,
625 * and make ->stack point to it. then we parse pipeN.
626 * when closing "then" / fi" / whatever is found,
627 * we move list_head into ->stack->command->group,
628 * copy ->stack into current context, and delete ->stack.
629 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000630 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000631 struct parse_context *stack;
632#endif
633};
634
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000635/* On program start, environ points to initial environment.
636 * putenv adds new pointers into it, unsetenv removes them.
637 * Neither of these (de)allocates the strings.
638 * setenv allocates new strings in malloc space and does putenv,
639 * and thus setenv is unusable (leaky) for shell's purposes */
640#define setenv(...) setenv_is_leaky_dont_use()
641struct variable {
642 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000643 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200644#if ENABLE_HUSH_LOCAL
645 unsigned func_nest_level;
646#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000647 int max_len; /* if > 0, name is part of initial env; else name is malloced */
648 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000649 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000650};
651
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000652enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000653 BC_BREAK = 1,
654 BC_CONTINUE = 2,
655};
656
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000657#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000658struct function {
659 struct function *next;
660 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000661 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000662 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200663# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000664 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200665# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000666};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000667#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000668
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000669
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100670/* set -/+o OPT support. (TODO: make it optional)
671 * bash supports the following opts:
672 * allexport off
673 * braceexpand on
674 * emacs on
675 * errexit off
676 * errtrace off
677 * functrace off
678 * hashall on
679 * histexpand off
680 * history on
681 * ignoreeof off
682 * interactive-comments on
683 * keyword off
684 * monitor on
685 * noclobber off
686 * noexec off
687 * noglob off
688 * nolog off
689 * notify off
690 * nounset off
691 * onecmd off
692 * physical off
693 * pipefail off
694 * posix off
695 * privileged off
696 * verbose off
697 * vi off
698 * xtrace off
699 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800700static const char o_opt_strings[] ALIGN1 =
701 "pipefail\0"
702 "noexec\0"
703#if ENABLE_HUSH_MODE_X
704 "xtrace\0"
705#endif
706 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100707enum {
708 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800709 OPT_O_NOEXEC,
710#if ENABLE_HUSH_MODE_X
711 OPT_O_XTRACE,
712#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100713 NUM_OPT_O
714};
715
716
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200717struct FILE_list {
718 struct FILE_list *next;
719 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200720 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200721};
722
723
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000724/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000725/* Sorted roughly by size (smaller offsets == smaller code) */
726struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000727 /* interactive_fd != 0 means we are an interactive shell.
728 * If we are, then saved_tty_pgrp can also be != 0, meaning
729 * that controlling tty is available. With saved_tty_pgrp == 0,
730 * job control still works, but terminal signals
731 * (^C, ^Z, ^Y, ^\) won't work at all, and background
732 * process groups can only be created with "cmd &".
733 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
734 * to give tty to the foreground process group,
735 * and will take it back when the group is stopped (^Z)
736 * or killed (^C).
737 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000738#if ENABLE_HUSH_INTERACTIVE
739 /* 'interactive_fd' is a fd# open to ctty, if we have one
740 * _AND_ if we decided to act interactively */
741 int interactive_fd;
742 const char *PS1;
743 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000744# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000745#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000746# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000747#endif
748#if ENABLE_FEATURE_EDITING
749 line_input_t *line_input_state;
750#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000751 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200752 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000753 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200754#if ENABLE_HUSH_RANDOM_SUPPORT
755 random_t random_gen;
756#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000757#if ENABLE_HUSH_JOB
758 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000759 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000760 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000761 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400762# define G_saved_tty_pgrp (G.saved_tty_pgrp)
763#else
764# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000765#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100766 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100767#if ENABLE_HUSH_MODE_X
768# define G_x_mode (G.o_opt[OPT_O_XTRACE])
769#else
770# define G_x_mode 0
771#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000772 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000773#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000774 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000775#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000776#if ENABLE_HUSH_FUNCTIONS
777 /* 0: outside of a function (or sourced file)
778 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000779 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000780 */
781 smallint flag_return_in_progress;
782#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000783 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000784 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000785 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000786 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000787 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000788 /* how many non-NULL argv's we have. NB: $# + 1 */
789 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000790 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000791#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000792 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000793#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000794#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000795 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000796 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000797#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000798 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000799 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200800 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200801 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000802#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000803 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200804# if ENABLE_HUSH_LOCAL
805 struct variable **shadowed_vars_pp;
806 unsigned func_nest_level;
807# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000808#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000809 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200810#if ENABLE_HUSH_FAST
811 unsigned count_SIGCHLD;
812 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200813 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200814#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200815 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200816 /* Which signals have non-DFL handler (even with no traps set)?
817 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200818 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200819 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200820 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200821 * Other than these two times, never modified.
822 */
823 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200824#if ENABLE_HUSH_JOB
825 unsigned fatal_sig_mask;
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200826# define G_fatal_sig_mask G.fatal_sig_mask
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200827#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200828# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200829#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000830 char **traps; /* char *traps[NSIG] */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200831 sigset_t pending_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000832#if HUSH_DEBUG
833 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000834 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000835#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200836 struct sigaction sa;
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200837 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000838};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000839#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000840/* Not #defining name to G.name - this quickly gets unwieldy
841 * (too many defines). Also, I actually prefer to see when a variable
842 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000843#define INIT_G() do { \
844 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200845 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
846 sigfillset(&G.sa.sa_mask); \
847 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000848} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000849
850
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000851/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200852static int builtin_cd(char **argv) FAST_FUNC;
853static int builtin_echo(char **argv) FAST_FUNC;
854static int builtin_eval(char **argv) FAST_FUNC;
855static int builtin_exec(char **argv) FAST_FUNC;
856static int builtin_exit(char **argv) FAST_FUNC;
857static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000858#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200859static int builtin_fg_bg(char **argv) FAST_FUNC;
860static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000861#endif
862#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200863static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000864#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200865#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200866static int builtin_history(char **argv) FAST_FUNC;
867#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200868#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200869static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200870#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000871#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200872static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000873#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400874#if ENABLE_PRINTF
875static int builtin_printf(char **argv) FAST_FUNC;
876#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200877static int builtin_pwd(char **argv) FAST_FUNC;
878static int builtin_read(char **argv) FAST_FUNC;
879static int builtin_set(char **argv) FAST_FUNC;
880static int builtin_shift(char **argv) FAST_FUNC;
881static int builtin_source(char **argv) FAST_FUNC;
882static int builtin_test(char **argv) FAST_FUNC;
883static int builtin_trap(char **argv) FAST_FUNC;
884static int builtin_type(char **argv) FAST_FUNC;
885static int builtin_true(char **argv) FAST_FUNC;
886static int builtin_umask(char **argv) FAST_FUNC;
887static int builtin_unset(char **argv) FAST_FUNC;
888static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000889#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200890static int builtin_break(char **argv) FAST_FUNC;
891static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000892#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000893#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200894static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000895#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000896
897/* Table of built-in functions. They can be forked or not, depending on
898 * context: within pipes, they fork. As simple commands, they do not.
899 * When used in non-forking context, they can change global variables
900 * in the parent shell process. If forked, of course they cannot.
901 * For example, 'unset foo | whatever' will parse and run, but foo will
902 * still be set at the end. */
903struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100904 const char *b_cmd;
905 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000906#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100907 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200908# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000909#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200910# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000911#endif
912};
913
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200914static const struct built_in_command bltins1[] = {
915 BLTIN("." , builtin_source , "Run commands in a file"),
916 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000917#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200918 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000919#endif
920#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200921 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000922#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200923 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000924#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200925 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000926#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200927 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
928 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
929 BLTIN("exit" , builtin_exit , "Exit"),
930 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000931#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200932 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000933#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000934#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200935 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000936#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200937#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200938 BLTIN("history" , builtin_history , "Show command history"),
939#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000940#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200941 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000942#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200943#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200944 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200945#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000946#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200947 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000948#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200949 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000950#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200951 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000952#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200953 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
954 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200955#if ENABLE_HUSH_BASH_COMPAT
956 BLTIN("source" , builtin_source , "Run commands in a file"),
957#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200958 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko2bba5912014-03-14 12:43:57 +0100959 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100960 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100961 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200962 BLTIN("umask" , builtin_umask , "Set file creation mask"),
963 BLTIN("unset" , builtin_unset , "Unset variables"),
964 BLTIN("wait" , builtin_wait , "Wait for process"),
965};
966/* For now, echo and test are unconditionally enabled.
967 * Maybe make it configurable? */
968static const struct built_in_command bltins2[] = {
969 BLTIN("[" , builtin_test , NULL),
970 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400971#if ENABLE_PRINTF
972 BLTIN("printf" , builtin_printf , NULL),
973#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200974 BLTIN("pwd" , builtin_pwd , NULL),
975 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000976};
977
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000978
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000979/* Debug printouts.
980 */
981#if HUSH_DEBUG
982/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100983# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000984# define debug_enter() (G.debug_indent++)
985# define debug_leave() (G.debug_indent--)
986#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200987# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000988# define debug_enter() ((void)0)
989# define debug_leave() ((void)0)
990#endif
991
992#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100993# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000994#endif
995
996#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100997# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000998#endif
999
1000#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001001#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001002#endif
1003
1004#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001005# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001006#endif
1007
1008#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001009# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001010# define DEBUG_JOBS 1
1011#else
1012# define DEBUG_JOBS 0
1013#endif
1014
1015#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001016# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001017# define DEBUG_EXPAND 1
1018#else
1019# define DEBUG_EXPAND 0
1020#endif
1021
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001022#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001023# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001024#endif
1025
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001026#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001027# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001028# define DEBUG_GLOB 1
1029#else
1030# define DEBUG_GLOB 0
1031#endif
1032
1033#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001034# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001035#endif
1036
1037#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001038# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001039#endif
1040
1041#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001042# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001043# define DEBUG_CLEAN 1
1044#else
1045# define DEBUG_CLEAN 0
1046#endif
1047
1048#if DEBUG_EXPAND
1049static void debug_print_strings(const char *prefix, char **vv)
1050{
1051 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001052 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001053 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001054 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001055}
1056#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001057# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001058#endif
1059
1060
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001061/* Leak hunting. Use hush_leaktool.sh for post-processing.
1062 */
1063#if LEAK_HUNTING
1064static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001065{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001066 void *ptr = xmalloc((size + 0xff) & ~0xff);
1067 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1068 return ptr;
1069}
1070static void *xxrealloc(int lineno, void *ptr, size_t size)
1071{
1072 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1073 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1074 return ptr;
1075}
1076static char *xxstrdup(int lineno, const char *str)
1077{
1078 char *ptr = xstrdup(str);
1079 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1080 return ptr;
1081}
1082static void xxfree(void *ptr)
1083{
1084 fdprintf(2, "free %p\n", ptr);
1085 free(ptr);
1086}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001087# define xmalloc(s) xxmalloc(__LINE__, s)
1088# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1089# define xstrdup(s) xxstrdup(__LINE__, s)
1090# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001091#endif
1092
1093
1094/* Syntax and runtime errors. They always abort scripts.
1095 * In interactive use they usually discard unparsed and/or unexecuted commands
1096 * and return to the prompt.
1097 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1098 */
1099#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001100# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001101# define syntax_error(lineno, msg) syntax_error(msg)
1102# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1103# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1104# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1105# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001106#endif
1107
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001108static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001109{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001110 va_list p;
1111
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001112#if HUSH_DEBUG >= 2
1113 bb_error_msg("hush.c:%u", lineno);
1114#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001115 va_start(p, fmt);
1116 bb_verror_msg(fmt, p, NULL);
1117 va_end(p);
1118 if (!G_interactive_fd)
1119 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001120}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001121
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001122static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001123{
1124 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001125 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001126 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001127 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001128}
1129
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001130static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001131{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001132 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001133}
1134
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001135static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001136{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001137 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001138}
1139
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001140static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001141{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001142 char msg[2] = { ch, '\0' };
1143 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001144}
1145
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001146static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001147{
1148 char msg[2];
1149 msg[0] = ch;
1150 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001151 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001152}
1153
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001154#if HUSH_DEBUG < 2
1155# undef die_if_script
1156# undef syntax_error
1157# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001158# undef syntax_error_unterm_ch
1159# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001160# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001161#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001162# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001163# define syntax_error(msg) syntax_error(__LINE__, msg)
1164# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1165# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1166# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1167# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001168#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001169
Denis Vlasenko552433b2009-04-04 19:29:21 +00001170
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001171#if ENABLE_HUSH_INTERACTIVE
1172static void cmdedit_update_prompt(void);
1173#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001174# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001175#endif
1176
1177
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001178/* Utility functions
1179 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001180/* Replace each \x with x in place, return ptr past NUL. */
1181static char *unbackslash(char *src)
1182{
Denys Vlasenko71885402009-09-24 01:44:13 +02001183 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001184 while (1) {
1185 if (*src == '\\')
1186 src++;
1187 if ((*dst++ = *src++) == '\0')
1188 break;
1189 }
1190 return dst;
1191}
1192
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001193static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001194{
1195 int i;
1196 unsigned count1;
1197 unsigned count2;
1198 char **v;
1199
1200 v = strings;
1201 count1 = 0;
1202 if (v) {
1203 while (*v) {
1204 count1++;
1205 v++;
1206 }
1207 }
1208 count2 = 0;
1209 v = add;
1210 while (*v) {
1211 count2++;
1212 v++;
1213 }
1214 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1215 v[count1 + count2] = NULL;
1216 i = count2;
1217 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001218 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001219 return v;
1220}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001221#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001222static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1223{
1224 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1225 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1226 return ptr;
1227}
1228#define add_strings_to_strings(strings, add, need_to_dup) \
1229 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1230#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001231
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001232/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001233static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001234{
1235 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001236 v[0] = add;
1237 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001238 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001239}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001240#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001241static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1242{
1243 char **ptr = add_string_to_strings(strings, add);
1244 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1245 return ptr;
1246}
1247#define add_string_to_strings(strings, add) \
1248 xx_add_string_to_strings(__LINE__, strings, add)
1249#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001250
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001251static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001252{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001253 char **v;
1254
1255 if (!strings)
1256 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001257 v = strings;
1258 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001259 free(*v);
1260 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001261 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001262 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001263}
1264
Denis Vlasenko76d50412008-06-10 16:19:39 +00001265
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001266static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1267{
1268 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1269 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1270 if (newfd < 0) {
1271 /* fd was not open? */
1272 if (errno == EBADF)
1273 return fd;
1274 xfunc_die();
1275 }
1276 close(fd);
1277 return newfd;
1278}
1279
1280
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001281/* Manipulating the list of open FILEs */
1282static FILE *remember_FILE(FILE *fp)
1283{
1284 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001285 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001286 n->next = G.FILE_list;
1287 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001288 n->fp = fp;
1289 n->fd = fileno(fp);
1290 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001291 }
1292 return fp;
1293}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001294static void fclose_and_forget(FILE *fp)
1295{
1296 struct FILE_list **pp = &G.FILE_list;
1297 while (*pp) {
1298 struct FILE_list *cur = *pp;
1299 if (cur->fp == fp) {
1300 *pp = cur->next;
1301 free(cur);
1302 break;
1303 }
1304 pp = &cur->next;
1305 }
1306 fclose(fp);
1307}
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001308static int save_FILEs_on_redirect(int fd)
1309{
1310 struct FILE_list *fl = G.FILE_list;
1311 while (fl) {
1312 if (fd == fl->fd) {
1313 /* We use it only on script files, they are all CLOEXEC */
1314 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1315 return 1;
1316 }
1317 fl = fl->next;
1318 }
1319 return 0;
1320}
1321static void restore_redirected_FILEs(void)
1322{
1323 struct FILE_list *fl = G.FILE_list;
1324 while (fl) {
1325 int should_be = fileno(fl->fp);
1326 if (fl->fd != should_be) {
1327 xmove_fd(fl->fd, should_be);
1328 fl->fd = should_be;
1329 }
1330 fl = fl->next;
1331 }
1332}
1333#if ENABLE_FEATURE_SH_STANDALONE
1334static void close_all_FILE_list(void)
1335{
1336 struct FILE_list *fl = G.FILE_list;
1337 while (fl) {
1338 /* fclose would also free FILE object.
1339 * It is disastrous if we share memory with a vforked parent.
1340 * I'm not sure we never come here after vfork.
1341 * Therefore just close fd, nothing more.
1342 */
1343 /*fclose(fl->fp); - unsafe */
1344 close(fl->fd);
1345 fl = fl->next;
1346 }
1347}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001348#endif
1349
1350
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001351/* Helpers for setting new $n and restoring them back
1352 */
1353typedef struct save_arg_t {
1354 char *sv_argv0;
1355 char **sv_g_argv;
1356 int sv_g_argc;
1357 smallint sv_g_malloced;
1358} save_arg_t;
1359
1360static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1361{
1362 int n;
1363
1364 sv->sv_argv0 = argv[0];
1365 sv->sv_g_argv = G.global_argv;
1366 sv->sv_g_argc = G.global_argc;
1367 sv->sv_g_malloced = G.global_args_malloced;
1368
1369 argv[0] = G.global_argv[0]; /* retain $0 */
1370 G.global_argv = argv;
1371 G.global_args_malloced = 0;
1372
1373 n = 1;
1374 while (*++argv)
1375 n++;
1376 G.global_argc = n;
1377}
1378
1379static void restore_G_args(save_arg_t *sv, char **argv)
1380{
1381 char **pp;
1382
1383 if (G.global_args_malloced) {
1384 /* someone ran "set -- arg1 arg2 ...", undo */
1385 pp = G.global_argv;
1386 while (*++pp) /* note: does not free $0 */
1387 free(*pp);
1388 free(G.global_argv);
1389 }
1390 argv[0] = sv->sv_argv0;
1391 G.global_argv = sv->sv_g_argv;
1392 G.global_argc = sv->sv_g_argc;
1393 G.global_args_malloced = sv->sv_g_malloced;
1394}
1395
1396
Denis Vlasenkod5762932009-03-31 11:22:57 +00001397/* Basic theory of signal handling in shell
1398 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001399 * This does not describe what hush does, rather, it is current understanding
1400 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001401 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1402 *
1403 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1404 * is finished or backgrounded. It is the same in interactive and
1405 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001406 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001407 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001408 * backgrounds (i.e. stops) or kills all members of currently running
1409 * pipe.
1410 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001411 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001412 * or by SIGINT in interactive shell.
1413 *
1414 * Trap handlers will execute even within trap handlers. (right?)
1415 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001416 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1417 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001418 *
1419 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001420 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001421 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001422 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001423 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001424 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001425 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001426 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001427 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001428 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001429 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001430 *
1431 * SIGQUIT: ignore
1432 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001433 * SIGHUP (interactive):
1434 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001435 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001436 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1437 * that all pipe members are stopped. Try this in bash:
1438 * while :; do :; done - ^Z does not background it
1439 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001440 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001441 * of the command line, show prompt. NB: ^C does not send SIGINT
1442 * to interactive shell while shell is waiting for a pipe,
1443 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001444 * Example 1: this waits 5 sec, but does not execute ls:
1445 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1446 * Example 2: this does not wait and does not execute ls:
1447 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1448 * Example 3: this does not wait 5 sec, but executes ls:
1449 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001450 * Example 4: this does not wait and does not execute ls:
1451 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001452 *
1453 * (What happens to signals which are IGN on shell start?)
1454 * (What happens with signal mask on shell start?)
1455 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001456 * Old implementation
1457 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001458 * We use in-kernel pending signal mask to determine which signals were sent.
1459 * We block all signals which we don't want to take action immediately,
1460 * i.e. we block all signals which need to have special handling as described
1461 * above, and all signals which have traps set.
1462 * After each pipe execution, we extract any pending signals via sigtimedwait()
1463 * and act on them.
1464 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001465 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001466 * sigset_t blocked_set: current blocked signal set
1467 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001468 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001469 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001470 * "trap 'cmd' SIGxxx":
1471 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001472 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001473 * unblock signals with special interactive handling
1474 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001475 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001476 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001477 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001478 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001479 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001480 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001481 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001482 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001483 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001484 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001485 * Standard says "When a subshell is entered, traps that are not being ignored
1486 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001487 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001488 *
1489 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001490 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001491 * masked signals are not visible!
1492 *
1493 * New implementation
1494 * ==================
1495 * We record each signal we are interested in by installing signal handler
1496 * for them - a bit like emulating kernel pending signal mask in userspace.
1497 * We are interested in: signals which need to have special handling
1498 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001499 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001500 * After each pipe execution, we extract any pending signals
1501 * and act on them.
1502 *
1503 * unsigned special_sig_mask: a mask of shell-special signals.
1504 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1505 * char *traps[sig] if trap for sig is set (even if it's '').
1506 * sigset_t pending_set: set of sigs we received.
1507 *
1508 * "trap - SIGxxx":
1509 * if sig is in special_sig_mask, set handler back to:
1510 * record_pending_signo, or to IGN if it's a tty stop signal
1511 * if sig is in fatal_sig_mask, set handler back to sigexit.
1512 * else: set handler back to SIG_DFL
1513 * "trap 'cmd' SIGxxx":
1514 * set handler to record_pending_signo.
1515 * "trap '' SIGxxx":
1516 * set handler to SIG_IGN.
1517 * after [v]fork, if we plan to be a shell:
1518 * set signals with special interactive handling to SIG_DFL
1519 * (because child shell is not interactive),
1520 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1521 * after [v]fork, if we plan to exec:
1522 * POSIX says fork clears pending signal mask in child - no need to clear it.
1523 *
1524 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1525 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1526 *
1527 * Note (compat):
1528 * Standard says "When a subshell is entered, traps that are not being ignored
1529 * are set to the default actions". bash interprets it so that traps which
1530 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001531 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001532enum {
1533 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001534 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001535 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001536 | (1 << SIGHUP)
1537 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001538 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001539#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001540 | (1 << SIGTTIN)
1541 | (1 << SIGTTOU)
1542 | (1 << SIGTSTP)
1543#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001544 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001545};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001546
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001547static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001548{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001549 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001550#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001551 if (sig == SIGCHLD) {
1552 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001553//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 +02001554 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001555#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001556}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001557
Denys Vlasenko0806e402011-05-12 23:06:20 +02001558static sighandler_t install_sighandler(int sig, sighandler_t handler)
1559{
1560 struct sigaction old_sa;
1561
1562 /* We could use signal() to install handlers... almost:
1563 * except that we need to mask ALL signals while handlers run.
1564 * I saw signal nesting in strace, race window isn't small.
1565 * SA_RESTART is also needed, but in Linux, signal()
1566 * sets SA_RESTART too.
1567 */
1568 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1569 /* sigfillset(&G.sa.sa_mask); - already done */
1570 /* G.sa.sa_flags = SA_RESTART; - already done */
1571 G.sa.sa_handler = handler;
1572 sigaction(sig, &G.sa, &old_sa);
1573 return old_sa.sa_handler;
1574}
1575
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001576static void hush_exit(int exitcode) NORETURN;
1577static void fflush_and__exit(void) NORETURN;
1578static void restore_ttypgrp_and__exit(void) NORETURN;
1579
1580static void restore_ttypgrp_and__exit(void)
1581{
1582 /* xfunc has failed! die die die */
1583 /* no EXIT traps, this is an escape hatch! */
1584 G.exiting = 1;
1585 hush_exit(xfunc_error_retval);
1586}
1587
1588/* Needed only on some libc:
1589 * It was observed that on exit(), fgetc'ed buffered data
1590 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1591 * With the net effect that even after fork(), not vfork(),
1592 * exit() in NOEXECed applet in "sh SCRIPT":
1593 * noexec_applet_here
1594 * echo END_OF_SCRIPT
1595 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1596 * This makes "echo END_OF_SCRIPT" executed twice.
1597 * Similar problems can be seen with die_if_script() -> xfunc_die()
1598 * and in `cmd` handling.
1599 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1600 */
1601static void fflush_and__exit(void)
1602{
1603 fflush_all();
1604 _exit(xfunc_error_retval);
1605}
1606
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001607#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001608
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001609/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001610# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001611/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001612# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001613
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001614/* Restores tty foreground process group, and exits.
1615 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001616 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001617 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001618 * We also call it if xfunc is exiting.
1619 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001620static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001621static void sigexit(int sig)
1622{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001623 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001624 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001625 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1626 /* Disable all signals: job control, SIGPIPE, etc.
1627 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1628 */
1629 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001630 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001631 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001632
1633 /* Not a signal, just exit */
1634 if (sig <= 0)
1635 _exit(- sig);
1636
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001637 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001638}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001639#else
1640
Denys Vlasenko8391c482010-05-22 17:50:43 +02001641# define disable_restore_tty_pgrp_on_exit() ((void)0)
1642# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001643
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001644#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001645
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001646static sighandler_t pick_sighandler(unsigned sig)
1647{
1648 sighandler_t handler = SIG_DFL;
1649 if (sig < sizeof(unsigned)*8) {
1650 unsigned sigmask = (1 << sig);
1651
1652#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001653 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001654 if (G_fatal_sig_mask & sigmask)
1655 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001656 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001657#endif
1658 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001659 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001660 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001661 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001662 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001663 * in an endless loop when we try to do some
1664 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001665 */
1666 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1667 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001668 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001669 }
1670 return handler;
1671}
1672
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001673/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001674static void hush_exit(int exitcode)
1675{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001676#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1677 save_history(G.line_input_state);
1678#endif
1679
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001680 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001681 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001682 char *argv[3];
1683 /* argv[0] is unused */
1684 argv[1] = G.traps[0];
1685 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001686 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001687 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001688 * "trap" will still show it, if executed
1689 * in the handler */
1690 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001691 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001692
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001693#if ENABLE_FEATURE_CLEAN_UP
1694 {
1695 struct variable *cur_var;
1696 if (G.cwd != bb_msg_unknown)
1697 free((char*)G.cwd);
1698 cur_var = G.top_var;
1699 while (cur_var) {
1700 struct variable *tmp = cur_var;
1701 if (!cur_var->max_len)
1702 free(cur_var->varstr);
1703 cur_var = cur_var->next;
1704 free(tmp);
1705 }
1706 }
1707#endif
1708
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001709 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001710#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001711 sigexit(- (exitcode & 0xff));
1712#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001713 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001714#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001715}
1716
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001717
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001718//TODO: return a mask of ALL handled sigs?
1719static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001720{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001721 int last_sig = 0;
1722
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001723 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001724 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001725
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001726 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001727 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001728 sig = 0;
1729 do {
1730 sig++;
1731 if (sigismember(&G.pending_set, sig)) {
1732 sigdelset(&G.pending_set, sig);
1733 goto got_sig;
1734 }
1735 } while (sig < NSIG);
1736 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001737 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001738 if (G.traps && G.traps[sig]) {
1739 if (G.traps[sig][0]) {
1740 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001741 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001742 char *argv[3];
1743 /* argv[0] is unused */
1744 argv[1] = G.traps[sig];
1745 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001746 save_rcode = G.last_exitcode;
1747 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001748 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001749 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001750 } /* else: "" trap, ignoring signal */
1751 continue;
1752 }
1753 /* not a trap: special action */
1754 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001755 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001756 /* Builtin was ^C'ed, make it look prettier: */
1757 bb_putchar('\n');
1758 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001759 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001760 break;
1761#if ENABLE_HUSH_JOB
1762 case SIGHUP: {
1763 struct pipe *job;
1764 /* bash is observed to signal whole process groups,
1765 * not individual processes */
1766 for (job = G.job_list; job; job = job->next) {
1767 if (job->pgrp <= 0)
1768 continue;
1769 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1770 if (kill(- job->pgrp, SIGHUP) == 0)
1771 kill(- job->pgrp, SIGCONT);
1772 }
1773 sigexit(SIGHUP);
1774 }
1775#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001776#if ENABLE_HUSH_FAST
1777 case SIGCHLD:
1778 G.count_SIGCHLD++;
1779//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1780 /* Note:
1781 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1782 * This simplifies wait builtin a bit.
1783 */
1784 break;
1785#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001786 default: /* ignored: */
1787 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001788 /* Note:
1789 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1790 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001791 * in interactive shell, because TERM is ignored.
1792 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001793 break;
1794 }
1795 }
1796 return last_sig;
1797}
1798
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001799
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001800static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001801{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001802 if (force || G.cwd == NULL) {
1803 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1804 * we must not try to free(bb_msg_unknown) */
1805 if (G.cwd == bb_msg_unknown)
1806 G.cwd = NULL;
1807 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1808 if (!G.cwd)
1809 G.cwd = bb_msg_unknown;
1810 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001811 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001812}
1813
Denis Vlasenko83506862007-11-23 13:11:42 +00001814
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001815/*
1816 * Shell and environment variable support
1817 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001818static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001819{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001820 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001821 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001822
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001823 pp = &G.top_var;
1824 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001825 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001826 return pp;
1827 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001828 }
1829 return NULL;
1830}
1831
Denys Vlasenko03dad222010-01-12 23:29:57 +01001832static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001833{
Denys Vlasenko29082232010-07-16 13:52:32 +02001834 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001835 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001836
1837 if (G.expanded_assignments) {
1838 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001839 while (*cpp) {
1840 char *cp = *cpp;
1841 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1842 return cp + len + 1;
1843 cpp++;
1844 }
1845 }
1846
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001847 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001848 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001849 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001850
Denys Vlasenkodea47882009-10-09 15:40:49 +02001851 if (strcmp(name, "PPID") == 0)
1852 return utoa(G.root_ppid);
1853 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001854#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001855 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001856 return utoa(next_random(&G.random_gen));
1857#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001858 return NULL;
1859}
1860
1861/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001862 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001863 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001864 * 0: do not change export flag
1865 * (if creating new variable, flag will be 0)
1866 * 1: set export flag and putenv the variable
1867 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001868 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001869 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001870#if !BB_MMU && ENABLE_HUSH_LOCAL
1871/* all params are used */
1872#elif BB_MMU && ENABLE_HUSH_LOCAL
1873#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1874 set_local_var(str, flg_export, local_lvl)
1875#elif BB_MMU && !ENABLE_HUSH_LOCAL
1876#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001877 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001878#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1879#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1880 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001881#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001882static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001883{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001884 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001885 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001886 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001887 int name_len;
1888
Denis Vlasenko950bd722009-04-21 11:23:56 +00001889 eq_sign = strchr(str, '=');
1890 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001891 free(str);
1892 return -1;
1893 }
1894
Denis Vlasenko950bd722009-04-21 11:23:56 +00001895 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001896 var_pp = &G.top_var;
1897 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001898 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001899 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001900 continue;
1901 }
1902 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001903 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001904#if !BB_MMU
1905 if (!flg_read_only)
1906#endif
1907 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001908 free(str);
1909 return -1;
1910 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001911 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001912 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1913 *eq_sign = '\0';
1914 unsetenv(str);
1915 *eq_sign = '=';
1916 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001917#if ENABLE_HUSH_LOCAL
1918 if (cur->func_nest_level < local_lvl) {
1919 /* New variable is declared as local,
1920 * and existing one is global, or local
1921 * from enclosing function.
1922 * Remove and save old one: */
1923 *var_pp = cur->next;
1924 cur->next = *G.shadowed_vars_pp;
1925 *G.shadowed_vars_pp = cur;
1926 /* bash 3.2.33(1) and exported vars:
1927 * # export z=z
1928 * # f() { local z=a; env | grep ^z; }
1929 * # f
1930 * z=a
1931 * # env | grep ^z
1932 * z=z
1933 */
1934 if (cur->flg_export)
1935 flg_export = 1;
1936 break;
1937 }
1938#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001939 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001940 free_and_exp:
1941 free(str);
1942 goto exp;
1943 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001944 if (cur->max_len != 0) {
1945 if (cur->max_len >= strlen(str)) {
1946 /* This one is from startup env, reuse space */
1947 strcpy(cur->varstr, str);
1948 goto free_and_exp;
1949 }
1950 } else {
1951 /* max_len == 0 signifies "malloced" var, which we can
1952 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001953 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001954 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001955 cur->max_len = 0;
1956 goto set_str_and_exp;
1957 }
1958
Denys Vlasenko295fef82009-06-03 12:47:26 +02001959 /* Not found - create new variable struct */
1960 cur = xzalloc(sizeof(*cur));
1961#if ENABLE_HUSH_LOCAL
1962 cur->func_nest_level = local_lvl;
1963#endif
1964 cur->next = *var_pp;
1965 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001966
1967 set_str_and_exp:
1968 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001969#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001970 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001971#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001972 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001973 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001974 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001975 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1976 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001977 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001978 if (flg_export == -1) {
1979 cur->flg_export = 0;
1980 /* unsetenv was already done */
1981 } else {
1982 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1983 return putenv(cur->varstr);
1984 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001985 }
1986 return 0;
1987}
1988
Denys Vlasenko6db47842009-09-05 20:15:17 +02001989/* Used at startup and after each cd */
1990static void set_pwd_var(int exp)
1991{
1992 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1993 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1994}
1995
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001996static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001997{
1998 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001999 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002000
2001 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002002 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002003 var_pp = &G.top_var;
2004 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002005 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2006 if (cur->flg_read_only) {
2007 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002008 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002009 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002010 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002011 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2012 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002013 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2014 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002015 if (!cur->max_len)
2016 free(cur->varstr);
2017 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002018 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002019 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002020 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002021 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002022 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002023}
2024
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002025static int unset_local_var(const char *name)
2026{
2027 return unset_local_var_len(name, strlen(name));
2028}
2029
2030static void unset_vars(char **strings)
2031{
2032 char **v;
2033
2034 if (!strings)
2035 return;
2036 v = strings;
2037 while (*v) {
2038 const char *eq = strchrnul(*v, '=');
2039 unset_local_var_len(*v, (int)(eq - *v));
2040 v++;
2041 }
2042 free(strings);
2043}
2044
Denys Vlasenko03dad222010-01-12 23:29:57 +01002045static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002046{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002047 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01002048 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002049}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002050
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002051
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002052/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002053 * Helpers for "var1=val1 var2=val2 cmd" feature
2054 */
2055static void add_vars(struct variable *var)
2056{
2057 struct variable *next;
2058
2059 while (var) {
2060 next = var->next;
2061 var->next = G.top_var;
2062 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002063 if (var->flg_export) {
2064 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002065 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002066 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002067 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002068 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002069 var = next;
2070 }
2071}
2072
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002073static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002074{
2075 char **s;
2076 struct variable *old = NULL;
2077
2078 if (!strings)
2079 return old;
2080 s = strings;
2081 while (*s) {
2082 struct variable *var_p;
2083 struct variable **var_pp;
2084 char *eq;
2085
2086 eq = strchr(*s, '=');
2087 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002088 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002089 if (var_pp) {
2090 /* Remove variable from global linked list */
2091 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002092 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002093 *var_pp = var_p->next;
2094 /* Add it to returned list */
2095 var_p->next = old;
2096 old = var_p;
2097 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002098 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002099 }
2100 s++;
2101 }
2102 return old;
2103}
2104
2105
2106/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002107 * Unicode helper
2108 */
2109static void reinit_unicode_for_hush(void)
2110{
2111 /* Unicode support should be activated even if LANG is set
2112 * _during_ shell execution, not only if it was set when
2113 * shell was started. Therefore, re-check LANG every time:
2114 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002115 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2116 || ENABLE_UNICODE_USING_LOCALE
2117 ) {
2118 const char *s = get_local_var_value("LC_ALL");
2119 if (!s) s = get_local_var_value("LC_CTYPE");
2120 if (!s) s = get_local_var_value("LANG");
2121 reinit_unicode(s);
2122 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002123}
2124
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002125/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002126 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002127 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002128
2129#if ENABLE_HUSH_INTERACTIVE
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002130static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002131{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002132 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002133 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002134 if (G.PS1 == NULL)
2135 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002136 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002137 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002138 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002139 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002140 if (G.PS2 == NULL)
2141 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002142}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002143static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002144{
2145 const char *prompt_str;
2146 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002147 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2148 /* Set up the prompt */
2149 if (promptmode == 0) { /* PS1 */
2150 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002151 /* bash uses $PWD value, even if it is set by user.
2152 * It uses current dir only if PWD is unset.
2153 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002154 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002155 prompt_str = G.PS1;
2156 } else
2157 prompt_str = G.PS2;
2158 } else
2159 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002160 debug_printf("result '%s'\n", prompt_str);
2161 return prompt_str;
2162}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002163static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002164{
2165 int r;
2166 const char *prompt_str;
2167
2168 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002169# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002170 /* Enable command line editing only while a command line
2171 * is actually being read */
2172 do {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002173 reinit_unicode_for_hush();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002174 G.flag_SIGINT = 0;
2175 /* buglet: SIGINT will not make new prompt to appear _at once_,
2176 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002177 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002178 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002179 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002180 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002181 i->p = G.user_input_buf;
2182 if (r < 0) {
2183 /* EOF/error detected */
2184 G.user_input_buf[0] = '\0';
2185 i->peek_buf[1] = i->peek_buf[0] = r = EOF;
2186 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002187 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002188 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002189# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002190 do {
2191 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002192 if (i->last_char == '\0' || i->last_char == '\n') {
2193 /* Why check_and_run_traps here? Try this interactively:
2194 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2195 * $ <[enter], repeatedly...>
2196 * Without check_and_run_traps, handler never runs.
2197 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002198 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002199 fputs(prompt_str, stdout);
2200 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002201 fflush_all();
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002202 r = fgetc(i->file);
2203 } while (G.flag_SIGINT || r == '\0');
2204 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002205# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002206}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002207#endif /* INTERACTIVE */
2208
2209/* This is the magic location that prints prompts
2210 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002211static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002212{
2213 int ch;
2214
2215 /* If there is data waiting, eat it up */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002216 /* peek_buf[] is an int array, not char. Can contain EOF. */
2217 ch = i->peek_buf[0];
2218 if (ch != '\0') {
2219 int ch2 = i->peek_buf[1];
2220 i->peek_buf[0] = ch2;
2221 if (ch2 == 0) /* very likely, avoid redundant write */
2222 goto out;
2223 i->peek_buf[1] = 0;
2224 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002225 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002226
2227#if ENABLE_HUSH_INTERACTIVE
2228 /* This can be stdin, check line editing char[] buffer */
2229 if (i->p && *i->p != '\0') {
2230 ch = (unsigned char)*i->p++;
2231 goto out;
2232 }
2233 /* It's empty.
2234 * If it's interactive stdin, get new line.
2235 */
2236 if (G_interactive_fd && i->file == stdin) {
2237 /* Returns first char (or EOF), the rest are in i->p[] */
2238 ch = get_user_input(i);
2239 i->promptmode = 1; /* PS2 */
2240 goto out;
2241 }
2242 /* Not stdin: script file */
2243#endif
2244 do ch = fgetc(i->file); while (ch == '\0');
2245 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002246 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002247 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002248 return ch;
2249}
2250
Denis Vlasenko913a2012009-04-05 22:17:04 +00002251/* All callers guarantee this routine will never
2252 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002253 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002254static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002255{
2256 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002257
2258 /* peek_buf[] is an int array, not char. Can contain EOF. */
2259 ch = i->peek_buf[0];
2260 if (ch != '\0')
2261 return ch;
2262
2263#if ENABLE_HUSH_INTERACTIVE
2264 /* This can be stdin, check line editing char[] buffer */
2265 if (i->p && *i->p != '\0')
2266 return (unsigned char)*i->p;
2267#endif
2268
Denis Vlasenko913a2012009-04-05 22:17:04 +00002269 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002270 i->peek_buf[0] = ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002271 i->peek_buf[1] = 0;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002272 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002273 return ch;
2274}
2275
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002276/* Only ever called if i_peek() was called, and did not return EOF */
2277static int FAST_FUNC file_peek2(struct in_str *i)
2278{
2279 int ch;
2280
2281 /* peek_buf[] is an int array, not char. Can contain EOF. */
2282 ch = i->peek_buf[0];
2283 if (ch != 0) {
2284 /* peek_buf[] is not empty. Is there 2nd char? */
2285 ch = i->peek_buf[1];
2286 if (ch == 0) {
2287 /* We did not read it yet, get it now */
2288 do ch = fgetc(i->file); while (ch == '\0');
2289 i->peek_buf[1] = ch;
2290 }
2291 goto out;
2292 }
2293
2294#if ENABLE_HUSH_INTERACTIVE
2295 /* This can be stdin, check line editing char[] buffer */
2296 if (i->p && i->p[0] != '\0')
2297 ch = i->p[1];
2298#endif
2299 out:
2300 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2301 return ch;
2302}
2303
2304static int FAST_FUNC static_get(struct in_str *i)
2305{
2306 int ch = *i->p;
2307 if (ch != '\0') {
2308 i->p++;
2309 i->last_char = ch;
2310 return ch;
2311 }
2312 return EOF;
2313}
2314
2315static int FAST_FUNC static_peek(struct in_str *i)
2316{
2317 /* Doesn't report EOF on NUL. None of the callers care. */
2318 return *i->p;
2319}
2320
2321/* Only ever called if i_peek() was called, and did not return EOF */
2322static int FAST_FUNC static_peek2(struct in_str *i)
2323{
2324 return i->p[1];
2325}
2326
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002327static void setup_file_in_str(struct in_str *i, FILE *f)
2328{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002329 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002330 i->get = file_get;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002331 i->peek = file_peek;
2332 i->peek2 = file_peek2;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002333 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002334 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002335 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002336}
2337
2338static void setup_string_in_str(struct in_str *i, const char *s)
2339{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002340 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002341 i->get = static_get;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002342 i->peek = static_peek;
2343 i->peek2 = static_peek2;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002344 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002345 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002346}
2347
2348
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002349/*
2350 * o_string support
2351 */
2352#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002353
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002354static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002355{
2356 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002357 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002358 if (o->data)
2359 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002360}
2361
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002362static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002363{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002364 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002365 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002366}
2367
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002368static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2369{
2370 free(o->data);
2371}
2372
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002373static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002374{
2375 if (o->length + len > o->maxlen) {
2376 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2377 o->data = xrealloc(o->data, 1 + o->maxlen);
2378 }
2379}
2380
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002381static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002382{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002383 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2384 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002385 o->data[o->length] = ch;
2386 o->length++;
2387 o->data[o->length] = '\0';
2388}
2389
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002390static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002391{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002392 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002393 memcpy(&o->data[o->length], str, len);
2394 o->length += len;
2395 o->data[o->length] = '\0';
2396}
2397
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002398static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002399{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002400 o_addblock(o, str, strlen(str));
2401}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002402
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002403#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002404static void nommu_addchr(o_string *o, int ch)
2405{
2406 if (o)
2407 o_addchr(o, ch);
2408}
2409#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002410# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002411#endif
2412
2413static void o_addstr_with_NUL(o_string *o, const char *str)
2414{
2415 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002416}
2417
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002418/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002419 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002420 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2421 * Apparently, on unquoted $v bash still does globbing
2422 * ("v='*.txt'; echo $v" prints all .txt files),
2423 * but NOT brace expansion! Thus, there should be TWO independent
2424 * quoting mechanisms on $v expansion side: one protects
2425 * $v from brace expansion, and other additionally protects "$v" against globbing.
2426 * We have only second one.
2427 */
2428
Denys Vlasenko9e800222010-10-03 14:28:04 +02002429#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002430# define MAYBE_BRACES "{}"
2431#else
2432# define MAYBE_BRACES ""
2433#endif
2434
Eric Andersen25f27032001-04-26 23:22:31 +00002435/* My analysis of quoting semantics tells me that state information
2436 * is associated with a destination, not a source.
2437 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002438static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002439{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002440 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002441 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002442 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002443 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002444 o_grow_by(o, sz);
2445 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002446 o->data[o->length] = '\\';
2447 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002448 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002449 o->data[o->length] = ch;
2450 o->length++;
2451 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002452}
2453
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002454static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002455{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002456 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002457 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2458 && strchr("*?[\\" MAYBE_BRACES, ch)
2459 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002460 sz++;
2461 o->data[o->length] = '\\';
2462 o->length++;
2463 }
2464 o_grow_by(o, sz);
2465 o->data[o->length] = ch;
2466 o->length++;
2467 o->data[o->length] = '\0';
2468}
2469
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002470static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002471{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002472 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002473 char ch;
2474 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002475 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002476 if (ordinary_cnt > len) /* paranoia */
2477 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002478 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002479 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002480 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002481 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002482 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002483
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002484 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002485 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002486 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002487 sz++;
2488 o->data[o->length] = '\\';
2489 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002490 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002491 o_grow_by(o, sz);
2492 o->data[o->length] = ch;
2493 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002494 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002495 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002496}
2497
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002498static void o_addQblock(o_string *o, const char *str, int len)
2499{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002500 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002501 o_addblock(o, str, len);
2502 return;
2503 }
2504 o_addqblock(o, str, len);
2505}
2506
Denys Vlasenko38292b62010-09-05 14:49:40 +02002507static void o_addQstr(o_string *o, const char *str)
2508{
2509 o_addQblock(o, str, strlen(str));
2510}
2511
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002512/* A special kind of o_string for $VAR and `cmd` expansion.
2513 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002514 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002515 * list[i] contains an INDEX (int!) into this string data.
2516 * It means that if list[] needs to grow, data needs to be moved higher up
2517 * but list[i]'s need not be modified.
2518 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002519 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002520 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2521 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002522#if DEBUG_EXPAND || DEBUG_GLOB
2523static void debug_print_list(const char *prefix, o_string *o, int n)
2524{
2525 char **list = (char**)o->data;
2526 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2527 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002528
2529 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002530 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 +02002531 prefix, list, n, string_start, o->length, o->maxlen,
2532 !!(o->o_expflags & EXP_FLAG_GLOB),
2533 o->has_quoted_part,
2534 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002535 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002536 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002537 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2538 o->data + (int)(uintptr_t)list[i] + string_start,
2539 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002540 i++;
2541 }
2542 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002543 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002544 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002545 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002546 }
2547}
2548#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002549# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002550#endif
2551
2552/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2553 * in list[n] so that it points past last stored byte so far.
2554 * It returns n+1. */
2555static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002556{
2557 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002558 int string_start;
2559 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002560
2561 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002562 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2563 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002564 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002565 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002566 /* list[n] points to string_start, make space for 16 more pointers */
2567 o->maxlen += 0x10 * sizeof(list[0]);
2568 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002569 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002570 memmove(list + n + 0x10, list + n, string_len);
2571 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002572 } else {
2573 debug_printf_list("list[%d]=%d string_start=%d\n",
2574 n, string_len, string_start);
2575 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002576 } else {
2577 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002578 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2579 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002580 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2581 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002582 o->has_empty_slot = 0;
2583 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002584 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002585 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002586 return n + 1;
2587}
2588
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002589/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002590static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002591{
2592 char **list = (char**)o->data;
2593 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2594
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002595 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002596}
2597
Denys Vlasenko9e800222010-10-03 14:28:04 +02002598#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002599/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2600 * first, it processes even {a} (no commas), second,
2601 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002602 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002603 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002604
2605/* Helper */
2606static int glob_needed(const char *s)
2607{
2608 while (*s) {
2609 if (*s == '\\') {
2610 if (!s[1])
2611 return 0;
2612 s += 2;
2613 continue;
2614 }
2615 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2616 return 1;
2617 s++;
2618 }
2619 return 0;
2620}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002621/* Return pointer to next closing brace or to comma */
2622static const char *next_brace_sub(const char *cp)
2623{
2624 unsigned depth = 0;
2625 cp++;
2626 while (*cp != '\0') {
2627 if (*cp == '\\') {
2628 if (*++cp == '\0')
2629 break;
2630 cp++;
2631 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002632 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002633 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002634 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002635 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002636 depth++;
2637 }
2638
2639 return *cp != '\0' ? cp : NULL;
2640}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002641/* Recursive brace globber. Note: may garble pattern[]. */
2642static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002643{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002644 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002645 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002646 const char *next;
2647 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002648 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002649 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002650
2651 debug_printf_glob("glob_brace('%s')\n", pattern);
2652
2653 begin = pattern;
2654 while (1) {
2655 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002656 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002657 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002658 /* Find the first sub-pattern and at the same time
2659 * find the rest after the closing brace */
2660 next = next_brace_sub(begin);
2661 if (next == NULL) {
2662 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002663 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002664 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002665 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002666 /* "{abc}" with no commas - illegal
2667 * brace expr, disregard and skip it */
2668 begin = next + 1;
2669 continue;
2670 }
2671 break;
2672 }
2673 if (*begin == '\\' && begin[1] != '\0')
2674 begin++;
2675 begin++;
2676 }
2677 debug_printf_glob("begin:%s\n", begin);
2678 debug_printf_glob("next:%s\n", next);
2679
2680 /* Now find the end of the whole brace expression */
2681 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002682 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002683 rest = next_brace_sub(rest);
2684 if (rest == NULL) {
2685 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002686 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002687 }
2688 debug_printf_glob("rest:%s\n", rest);
2689 }
2690 rest_len = strlen(++rest) + 1;
2691
2692 /* We are sure the brace expression is well-formed */
2693
2694 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002695 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002696
2697 /* We have a brace expression. BEGIN points to the opening {,
2698 * NEXT points past the terminator of the first element, and REST
2699 * points past the final }. We will accumulate result names from
2700 * recursive runs for each brace alternative in the buffer using
2701 * GLOB_APPEND. */
2702
2703 p = begin + 1;
2704 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002705 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002706 memcpy(
2707 mempcpy(
2708 mempcpy(new_pattern_buf,
2709 /* We know the prefix for all sub-patterns */
2710 pattern, begin - pattern),
2711 p, next - p),
2712 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002713
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002714 /* Note: glob_brace() may garble new_pattern_buf[].
2715 * That's why we re-copy prefix every time (1st memcpy above).
2716 */
2717 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002718 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002719 /* We saw the last entry */
2720 break;
2721 }
2722 p = next + 1;
2723 next = next_brace_sub(next);
2724 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002725 free(new_pattern_buf);
2726 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002727
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002728 simple_glob:
2729 {
2730 int gr;
2731 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002732
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002733 memset(&globdata, 0, sizeof(globdata));
2734 gr = glob(pattern, 0, NULL, &globdata);
2735 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2736 if (gr != 0) {
2737 if (gr == GLOB_NOMATCH) {
2738 globfree(&globdata);
2739 /* NB: garbles parameter */
2740 unbackslash(pattern);
2741 o_addstr_with_NUL(o, pattern);
2742 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2743 return o_save_ptr_helper(o, n);
2744 }
2745 if (gr == GLOB_NOSPACE)
2746 bb_error_msg_and_die(bb_msg_memory_exhausted);
2747 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2748 * but we didn't specify it. Paranoia again. */
2749 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2750 }
2751 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2752 char **argv = globdata.gl_pathv;
2753 while (1) {
2754 o_addstr_with_NUL(o, *argv);
2755 n = o_save_ptr_helper(o, n);
2756 argv++;
2757 if (!*argv)
2758 break;
2759 }
2760 }
2761 globfree(&globdata);
2762 }
2763 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002764}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002765/* Performs globbing on last list[],
2766 * saving each result as a new list[].
2767 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002768static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002769{
2770 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002771
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002772 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002773 if (!o->data)
2774 return o_save_ptr_helper(o, n);
2775 pattern = o->data + o_get_last_ptr(o, n);
2776 debug_printf_glob("glob pattern '%s'\n", pattern);
2777 if (!glob_needed(pattern)) {
2778 /* unbackslash last string in o in place, fix length */
2779 o->length = unbackslash(pattern) - o->data;
2780 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2781 return o_save_ptr_helper(o, n);
2782 }
2783
2784 copy = xstrdup(pattern);
2785 /* "forget" pattern in o */
2786 o->length = pattern - o->data;
2787 n = glob_brace(copy, o, n);
2788 free(copy);
2789 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002790 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002791 return n;
2792}
2793
Denys Vlasenko238081f2010-10-03 14:26:26 +02002794#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002795
2796/* Helper */
2797static int glob_needed(const char *s)
2798{
2799 while (*s) {
2800 if (*s == '\\') {
2801 if (!s[1])
2802 return 0;
2803 s += 2;
2804 continue;
2805 }
2806 if (*s == '*' || *s == '[' || *s == '?')
2807 return 1;
2808 s++;
2809 }
2810 return 0;
2811}
2812/* Performs globbing on last list[],
2813 * saving each result as a new list[].
2814 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002815static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002816{
2817 glob_t globdata;
2818 int gr;
2819 char *pattern;
2820
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002821 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002822 if (!o->data)
2823 return o_save_ptr_helper(o, n);
2824 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002825 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002826 if (!glob_needed(pattern)) {
2827 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002828 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002829 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002830 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002831 return o_save_ptr_helper(o, n);
2832 }
2833
2834 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002835 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2836 * If we glob "*.\*" and don't find anything, we need
2837 * to fall back to using literal "*.*", but GLOB_NOCHECK
2838 * will return "*.\*"!
2839 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002840 gr = glob(pattern, 0, NULL, &globdata);
2841 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002842 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002843 if (gr == GLOB_NOMATCH) {
2844 globfree(&globdata);
2845 goto literal;
2846 }
2847 if (gr == GLOB_NOSPACE)
2848 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002849 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2850 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002851 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002852 }
2853 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2854 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002855 /* "forget" pattern in o */
2856 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002857 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002858 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002859 n = o_save_ptr_helper(o, n);
2860 argv++;
2861 if (!*argv)
2862 break;
2863 }
2864 }
2865 globfree(&globdata);
2866 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002867 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002868 return n;
2869}
2870
Denys Vlasenko238081f2010-10-03 14:26:26 +02002871#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002872
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002873/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002874 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002875static int o_save_ptr(o_string *o, int n)
2876{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002877 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002878 /* If o->has_empty_slot, list[n] was already globbed
2879 * (if it was requested back then when it was filled)
2880 * so don't do that again! */
2881 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002882 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002883 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002884 return o_save_ptr_helper(o, n);
2885}
2886
2887/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002888static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002889{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002890 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002891 int string_start;
2892
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002893 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2894 if (DEBUG_EXPAND)
2895 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002896 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002897 list = (char**)o->data;
2898 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2899 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002900 while (n) {
2901 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002902 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002903 }
2904 return list;
2905}
2906
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002907static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002908
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002909/* Returns pi->next - next pipe in the list */
2910static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002911{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002912 struct pipe *next;
2913 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002914
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002915 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002916 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002917 struct command *command;
2918 struct redir_struct *r, *rnext;
2919
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002920 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002921 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002922 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002923 if (DEBUG_CLEAN) {
2924 int a;
2925 char **p;
2926 for (a = 0, p = command->argv; *p; a++, p++) {
2927 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2928 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002929 }
2930 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002931 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002932 }
2933 /* not "else if": on syntax error, we may have both! */
2934 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002935 debug_printf_clean(" begin group (cmd_type:%d)\n",
2936 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002937 free_pipe_list(command->group);
2938 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002939 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002940 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002941 /* else is crucial here.
2942 * If group != NULL, child_func is meaningless */
2943#if ENABLE_HUSH_FUNCTIONS
2944 else if (command->child_func) {
2945 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2946 command->child_func->parent_cmd = NULL;
2947 }
2948#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002949#if !BB_MMU
2950 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002951 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002952#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002953 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002954 debug_printf_clean(" redirect %d%s",
2955 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002956 /* guard against the case >$FOO, where foo is unset or blank */
2957 if (r->rd_filename) {
2958 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2959 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002960 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002961 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002962 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002963 rnext = r->next;
2964 free(r);
2965 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002966 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002967 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002968 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002969 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002970#if ENABLE_HUSH_JOB
2971 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002972 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002973#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002974
2975 next = pi->next;
2976 free(pi);
2977 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002978}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002979
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002980static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002981{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002982 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002983#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002984 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002985#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002986 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002987 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002988 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002989}
2990
2991
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002992/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002993
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002994#ifndef debug_print_tree
2995static void debug_print_tree(struct pipe *pi, int lvl)
2996{
2997 static const char *const PIPE[] = {
2998 [PIPE_SEQ] = "SEQ",
2999 [PIPE_AND] = "AND",
3000 [PIPE_OR ] = "OR" ,
3001 [PIPE_BG ] = "BG" ,
3002 };
3003 static const char *RES[] = {
3004 [RES_NONE ] = "NONE" ,
3005# if ENABLE_HUSH_IF
3006 [RES_IF ] = "IF" ,
3007 [RES_THEN ] = "THEN" ,
3008 [RES_ELIF ] = "ELIF" ,
3009 [RES_ELSE ] = "ELSE" ,
3010 [RES_FI ] = "FI" ,
3011# endif
3012# if ENABLE_HUSH_LOOPS
3013 [RES_FOR ] = "FOR" ,
3014 [RES_WHILE] = "WHILE",
3015 [RES_UNTIL] = "UNTIL",
3016 [RES_DO ] = "DO" ,
3017 [RES_DONE ] = "DONE" ,
3018# endif
3019# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3020 [RES_IN ] = "IN" ,
3021# endif
3022# if ENABLE_HUSH_CASE
3023 [RES_CASE ] = "CASE" ,
3024 [RES_CASE_IN ] = "CASE_IN" ,
3025 [RES_MATCH] = "MATCH",
3026 [RES_CASE_BODY] = "CASE_BODY",
3027 [RES_ESAC ] = "ESAC" ,
3028# endif
3029 [RES_XXXX ] = "XXXX" ,
3030 [RES_SNTX ] = "SNTX" ,
3031 };
3032 static const char *const CMDTYPE[] = {
3033 "{}",
3034 "()",
3035 "[noglob]",
3036# if ENABLE_HUSH_FUNCTIONS
3037 "func()",
3038# endif
3039 };
3040
3041 int pin, prn;
3042
3043 pin = 0;
3044 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003045 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003046 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3047 prn = 0;
3048 while (prn < pi->num_cmds) {
3049 struct command *command = &pi->cmds[prn];
3050 char **argv = command->argv;
3051
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003052 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003053 lvl*2, "", prn,
3054 command->assignment_cnt);
3055 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003056 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003057 CMDTYPE[command->cmd_type],
3058 argv
3059# if !BB_MMU
3060 , " group_as_string:", command->group_as_string
3061# else
3062 , "", ""
3063# endif
3064 );
3065 debug_print_tree(command->group, lvl+1);
3066 prn++;
3067 continue;
3068 }
3069 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003070 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003071 argv++;
3072 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003073 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003074 prn++;
3075 }
3076 pi = pi->next;
3077 pin++;
3078 }
3079}
3080#endif /* debug_print_tree */
3081
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003082static struct pipe *new_pipe(void)
3083{
Eric Andersen25f27032001-04-26 23:22:31 +00003084 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003085 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003086 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003087 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003088 return pi;
3089}
3090
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003091/* Command (member of a pipe) is complete, or we start a new pipe
3092 * if ctx->command is NULL.
3093 * No errors possible here.
3094 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003095static int done_command(struct parse_context *ctx)
3096{
3097 /* The command is really already in the pipe structure, so
3098 * advance the pipe counter and make a new, null command. */
3099 struct pipe *pi = ctx->pipe;
3100 struct command *command = ctx->command;
3101
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003102#if 0 /* Instead we emit error message at run time */
3103 if (ctx->pending_redirect) {
3104 /* For example, "cmd >" (no filename to redirect to) */
3105 die_if_script("syntax error: %s", "invalid redirect");
3106 ctx->pending_redirect = NULL;
3107 }
3108#endif
3109
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003110 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003111 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003112 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003113 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003114 }
3115 pi->num_cmds++;
3116 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003117 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003118 } else {
3119 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3120 }
3121
3122 /* Only real trickiness here is that the uncommitted
3123 * command structure is not counted in pi->num_cmds. */
3124 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003125 ctx->command = command = &pi->cmds[pi->num_cmds];
3126 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003127 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003128 return pi->num_cmds; /* used only for 0/nonzero check */
3129}
3130
3131static void done_pipe(struct parse_context *ctx, pipe_style type)
3132{
3133 int not_null;
3134
3135 debug_printf_parse("done_pipe entered, followup %d\n", type);
3136 /* Close previous command */
3137 not_null = done_command(ctx);
3138 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003139#if HAS_KEYWORDS
3140 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3141 ctx->ctx_inverted = 0;
3142 ctx->pipe->res_word = ctx->ctx_res_w;
3143#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003144
3145 /* Without this check, even just <enter> on command line generates
3146 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003147 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003148 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003149#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003150 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003151#endif
3152#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003153 || ctx->ctx_res_w == RES_DONE
3154 || ctx->ctx_res_w == RES_FOR
3155 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003156#endif
3157#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003158 || ctx->ctx_res_w == RES_ESAC
3159#endif
3160 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003161 struct pipe *new_p;
3162 debug_printf_parse("done_pipe: adding new pipe: "
3163 "not_null:%d ctx->ctx_res_w:%d\n",
3164 not_null, ctx->ctx_res_w);
3165 new_p = new_pipe();
3166 ctx->pipe->next = new_p;
3167 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003168 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003169 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003170 * This is used to control execution.
3171 * RES_FOR and RES_IN are NOT sticky (needed to support
3172 * cases where variable or value happens to match a keyword):
3173 */
3174#if ENABLE_HUSH_LOOPS
3175 if (ctx->ctx_res_w == RES_FOR
3176 || ctx->ctx_res_w == RES_IN)
3177 ctx->ctx_res_w = RES_NONE;
3178#endif
3179#if ENABLE_HUSH_CASE
3180 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003181 ctx->ctx_res_w = RES_CASE_BODY;
3182 if (ctx->ctx_res_w == RES_CASE)
3183 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003184#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003185 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003186 /* Create the memory for command, roughly:
3187 * ctx->pipe->cmds = new struct command;
3188 * ctx->command = &ctx->pipe->cmds[0];
3189 */
3190 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003191 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003192 }
3193 debug_printf_parse("done_pipe return\n");
3194}
3195
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003196static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003197{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003198 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003199 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003200 /* Create the memory for command, roughly:
3201 * ctx->pipe->cmds = new struct command;
3202 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003203 */
3204 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003205}
3206
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003207/* If a reserved word is found and processed, parse context is modified
3208 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003209 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003210#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003211struct reserved_combo {
3212 char literal[6];
3213 unsigned char res;
3214 unsigned char assignment_flag;
3215 int flag;
3216};
3217enum {
3218 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003219# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003220 FLAG_IF = (1 << RES_IF ),
3221 FLAG_THEN = (1 << RES_THEN ),
3222 FLAG_ELIF = (1 << RES_ELIF ),
3223 FLAG_ELSE = (1 << RES_ELSE ),
3224 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003225# endif
3226# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003227 FLAG_FOR = (1 << RES_FOR ),
3228 FLAG_WHILE = (1 << RES_WHILE),
3229 FLAG_UNTIL = (1 << RES_UNTIL),
3230 FLAG_DO = (1 << RES_DO ),
3231 FLAG_DONE = (1 << RES_DONE ),
3232 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003233# endif
3234# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003235 FLAG_MATCH = (1 << RES_MATCH),
3236 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003237# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003238 FLAG_START = (1 << RES_XXXX ),
3239};
3240
3241static const struct reserved_combo* match_reserved_word(o_string *word)
3242{
Eric Andersen25f27032001-04-26 23:22:31 +00003243 /* Mostly a list of accepted follow-up reserved words.
3244 * FLAG_END means we are done with the sequence, and are ready
3245 * to turn the compound list into a command.
3246 * FLAG_START means the word must start a new compound list.
3247 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003248 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003249# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003250 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3251 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3252 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3253 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3254 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3255 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003256# endif
3257# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003258 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3259 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3260 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3261 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3262 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3263 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003264# endif
3265# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003266 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3267 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003268# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003269 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003270 const struct reserved_combo *r;
3271
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003272 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003273 if (strcmp(word->data, r->literal) == 0)
3274 return r;
3275 }
3276 return NULL;
3277}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003278/* Return 0: not a keyword, 1: keyword
3279 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003280static int reserved_word(o_string *word, struct parse_context *ctx)
3281{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003282# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003283 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003284 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003285 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003286# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003287 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003288
Denys Vlasenko38292b62010-09-05 14:49:40 +02003289 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003290 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003291 r = match_reserved_word(word);
3292 if (!r)
3293 return 0;
3294
3295 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003296# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003297 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3298 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003299 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003300 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003301# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003302 if (r->flag == 0) { /* '!' */
3303 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003304 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003305 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003306 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003307 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003308 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003309 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003310 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003311 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003312
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003313 old = xmalloc(sizeof(*old));
3314 debug_printf_parse("push stack %p\n", old);
3315 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003316 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003317 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003318 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003319 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003320 ctx->ctx_res_w = RES_SNTX;
3321 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003322 } else {
3323 /* "{...} fi" is ok. "{...} if" is not
3324 * Example:
3325 * if { echo foo; } then { echo bar; } fi */
3326 if (ctx->command->group)
3327 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003328 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003329
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003330 ctx->ctx_res_w = r->res;
3331 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003332 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003333 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003334
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003335 if (ctx->old_flag & FLAG_END) {
3336 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003337
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003338 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003339 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003340 old = ctx->stack;
3341 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003342 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003343# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003344 /* At this point, the compound command's string is in
3345 * ctx->as_string... except for the leading keyword!
3346 * Consider this example: "echo a | if true; then echo a; fi"
3347 * ctx->as_string will contain "true; then echo a; fi",
3348 * with "if " remaining in old->as_string!
3349 */
3350 {
3351 char *str;
3352 int len = old->as_string.length;
3353 /* Concatenate halves */
3354 o_addstr(&old->as_string, ctx->as_string.data);
3355 o_free_unsafe(&ctx->as_string);
3356 /* Find where leading keyword starts in first half */
3357 str = old->as_string.data + len;
3358 if (str > old->as_string.data)
3359 str--; /* skip whitespace after keyword */
3360 while (str > old->as_string.data && isalpha(str[-1]))
3361 str--;
3362 /* Ugh, we're done with this horrid hack */
3363 old->command->group_as_string = xstrdup(str);
3364 debug_printf_parse("pop, remembering as:'%s'\n",
3365 old->command->group_as_string);
3366 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003367# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003368 *ctx = *old; /* physical copy */
3369 free(old);
3370 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003371 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003372}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003373#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003374
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003375/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003376 * Normal return is 0. Syntax errors return 1.
3377 * Note: on return, word is reset, but not o_free'd!
3378 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003379static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003380{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003381 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003382
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003383 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003384 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003385 debug_printf_parse("done_word return 0: true null, ignored\n");
3386 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003387 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003388
Eric Andersen25f27032001-04-26 23:22:31 +00003389 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003390 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3391 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003392 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3393 * "2.7 Redirection
3394 * ...the word that follows the redirection operator
3395 * shall be subjected to tilde expansion, parameter expansion,
3396 * command substitution, arithmetic expansion, and quote
3397 * removal. Pathname expansion shall not be performed
3398 * on the word by a non-interactive shell; an interactive
3399 * shell may perform it, but shall do so only when
3400 * the expansion would result in one word."
3401 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003402 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003403 /* Cater for >\file case:
3404 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3405 * Same with heredocs:
3406 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3407 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003408 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3409 unbackslash(ctx->pending_redirect->rd_filename);
3410 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003411 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003412 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3413 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003414 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003415 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003416 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003417 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003418#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003419# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003420 if (ctx->ctx_dsemicolon
3421 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3422 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003423 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003424 /* ctx->ctx_res_w = RES_MATCH; */
3425 ctx->ctx_dsemicolon = 0;
3426 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003427# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003428 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003429# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003430 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3431 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003432# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003433# if ENABLE_HUSH_CASE
3434 && ctx->ctx_res_w != RES_CASE
3435# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003436 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003437 int reserved = reserved_word(word, ctx);
3438 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3439 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003440 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003441 debug_printf_parse("done_word return %d\n",
3442 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003443 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003444 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003445# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003446 if (strcmp(word->data, "[[") == 0) {
3447 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3448 }
3449 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003450# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003451 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003452#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003453 if (command->group) {
3454 /* "{ echo foo; } echo bar" - bad */
3455 syntax_error_at(word->data);
3456 debug_printf_parse("done_word return 1: syntax error, "
3457 "groups and arglists don't mix\n");
3458 return 1;
3459 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003460
3461 /* If this word wasn't an assignment, next ones definitely
3462 * can't be assignments. Even if they look like ones. */
3463 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3464 && word->o_assignment != WORD_IS_KEYWORD
3465 ) {
3466 word->o_assignment = NOT_ASSIGNMENT;
3467 } else {
3468 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3469 command->assignment_cnt++;
3470 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3471 }
3472 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3473 word->o_assignment = MAYBE_ASSIGNMENT;
3474 }
3475 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3476
Denys Vlasenko38292b62010-09-05 14:49:40 +02003477 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003478 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3479 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003480 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003481 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003482 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003483 char *p = word->data;
3484 while (p[0] == SPECIAL_VAR_SYMBOL
3485 && (p[1] & 0x7f) == '@'
3486 && p[2] == SPECIAL_VAR_SYMBOL
3487 ) {
3488 p += 3;
3489 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003490 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003491 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003492 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003493 }
Eric Andersen25f27032001-04-26 23:22:31 +00003494
Denis Vlasenko06810332007-05-21 23:30:54 +00003495#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003496 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003497 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003498 || !is_well_formed_var_name(command->argv[0], '\0')
3499 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003500 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003501 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003502 return 1;
3503 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003504 /* Force FOR to have just one word (variable name) */
3505 /* NB: basically, this makes hush see "for v in ..."
3506 * syntax as if it is "for v; in ...". FOR and IN become
3507 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003508 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003509 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003510#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003511#if ENABLE_HUSH_CASE
3512 /* Force CASE to have just one word */
3513 if (ctx->ctx_res_w == RES_CASE) {
3514 done_pipe(ctx, PIPE_SEQ);
3515 }
3516#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003517
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003518 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003519
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003520 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003521 return 0;
3522}
3523
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003524
3525/* Peek ahead in the input to find out if we have a "&n" construct,
3526 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003527 * Return:
3528 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3529 * REDIRFD_SYNTAX_ERR if syntax error,
3530 * REDIRFD_TO_FILE if no & was seen,
3531 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003532 */
3533#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003534#define parse_redir_right_fd(as_string, input) \
3535 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003536#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003537static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003538{
3539 int ch, d, ok;
3540
3541 ch = i_peek(input);
3542 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003543 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003544
3545 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003546 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003547 ch = i_peek(input);
3548 if (ch == '-') {
3549 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003550 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003551 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003552 }
3553 d = 0;
3554 ok = 0;
3555 while (ch != EOF && isdigit(ch)) {
3556 d = d*10 + (ch-'0');
3557 ok = 1;
3558 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003559 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003560 ch = i_peek(input);
3561 }
3562 if (ok) return d;
3563
3564//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3565
3566 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003567 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003568}
3569
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003570/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003571 */
3572static int parse_redirect(struct parse_context *ctx,
3573 int fd,
3574 redir_type style,
3575 struct in_str *input)
3576{
3577 struct command *command = ctx->command;
3578 struct redir_struct *redir;
3579 struct redir_struct **redirp;
3580 int dup_num;
3581
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003582 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003583 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003584 /* Check for a '>&1' type redirect */
3585 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3586 if (dup_num == REDIRFD_SYNTAX_ERR)
3587 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003588 } else {
3589 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003590 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003591 if (dup_num) { /* <<-... */
3592 ch = i_getch(input);
3593 nommu_addchr(&ctx->as_string, ch);
3594 ch = i_peek(input);
3595 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003596 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003597
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003598 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003599 int ch = i_peek(input);
3600 if (ch == '|') {
3601 /* >|FILE redirect ("clobbering" >).
3602 * Since we do not support "set -o noclobber" yet,
3603 * >| and > are the same for now. Just eat |.
3604 */
3605 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003606 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003607 }
3608 }
3609
3610 /* Create a new redir_struct and append it to the linked list */
3611 redirp = &command->redirects;
3612 while ((redir = *redirp) != NULL) {
3613 redirp = &(redir->next);
3614 }
3615 *redirp = redir = xzalloc(sizeof(*redir));
3616 /* redir->next = NULL; */
3617 /* redir->rd_filename = NULL; */
3618 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003619 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003620
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003621 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3622 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003623
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003624 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003625 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003626 /* Erik had a check here that the file descriptor in question
3627 * is legit; I postpone that to "run time"
3628 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003629 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3630 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003631 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003632#if 0 /* Instead we emit error message at run time */
3633 if (ctx->pending_redirect) {
3634 /* For example, "cmd > <file" */
3635 die_if_script("syntax error: %s", "invalid redirect");
3636 }
3637#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003638 /* Set ctx->pending_redirect, so we know what to do at the
3639 * end of the next parsed word. */
3640 ctx->pending_redirect = redir;
3641 }
3642 return 0;
3643}
3644
Eric Andersen25f27032001-04-26 23:22:31 +00003645/* If a redirect is immediately preceded by a number, that number is
3646 * supposed to tell which file descriptor to redirect. This routine
3647 * looks for such preceding numbers. In an ideal world this routine
3648 * needs to handle all the following classes of redirects...
3649 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3650 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3651 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3652 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003653 *
3654 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3655 * "2.7 Redirection
3656 * ... If n is quoted, the number shall not be recognized as part of
3657 * the redirection expression. For example:
3658 * echo \2>a
3659 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003660 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003661 *
3662 * A -1 return means no valid number was found,
3663 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003664 */
3665static int redirect_opt_num(o_string *o)
3666{
3667 int num;
3668
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003669 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003670 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003671 num = bb_strtou(o->data, NULL, 10);
3672 if (errno || num < 0)
3673 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003674 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003675 return num;
3676}
3677
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003678#if BB_MMU
3679#define fetch_till_str(as_string, input, word, skip_tabs) \
3680 fetch_till_str(input, word, skip_tabs)
3681#endif
3682static char *fetch_till_str(o_string *as_string,
3683 struct in_str *input,
3684 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003685 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003686{
3687 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003688 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003689 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003690 int ch;
3691
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003692 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003693
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003694 while (1) {
3695 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003696 if (ch != EOF)
3697 nommu_addchr(as_string, ch);
3698 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003699 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3700 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003701 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3702 heredoc.data[past_EOL] = '\0';
3703 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3704 return heredoc.data;
3705 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003706 while (ch == '\n') {
3707 o_addchr(&heredoc, ch);
3708 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003709 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003710 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003711 do {
3712 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003713 if (ch != EOF)
3714 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003715 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003716 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003717 }
3718 if (ch == EOF) {
3719 o_free_unsafe(&heredoc);
3720 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003721 }
3722 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003723 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003724 if (prev == '\\' && ch == '\\')
3725 /* Correctly handle foo\\<eol> (not a line cont.) */
3726 prev = 0; /* not \ */
3727 else
3728 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003729 }
3730}
3731
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003732/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3733 * and load them all. There should be exactly heredoc_cnt of them.
3734 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003735static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3736{
3737 struct pipe *pi = ctx->list_head;
3738
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003739 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003740 int i;
3741 struct command *cmd = pi->cmds;
3742
3743 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3744 pi->num_cmds,
3745 cmd->argv ? cmd->argv[0] : "NONE");
3746 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003747 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003748
3749 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3750 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003751 while (redir) {
3752 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003753 char *p;
3754
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003755 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003756 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003757 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003758 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003759 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003760 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003761 return 1;
3762 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003763 free(redir->rd_filename);
3764 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003765 heredoc_cnt--;
3766 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003767 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003768 }
3769 cmd++;
3770 }
3771 pi = pi->next;
3772 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003773#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003774 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003775 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003776 bb_error_msg_and_die("heredoc BUG 2");
3777#endif
3778 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003779}
3780
3781
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003782static int run_list(struct pipe *pi);
3783#if BB_MMU
3784#define parse_stream(pstring, input, end_trigger) \
3785 parse_stream(input, end_trigger)
3786#endif
3787static struct pipe *parse_stream(char **pstring,
3788 struct in_str *input,
3789 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003790
Eric Andersen25f27032001-04-26 23:22:31 +00003791
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003792#if !ENABLE_HUSH_FUNCTIONS
3793#define parse_group(dest, ctx, input, ch) \
3794 parse_group(ctx, input, ch)
3795#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003796static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003797 struct in_str *input, int ch)
3798{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003799 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003800 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003801 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003802 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003803 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003804 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003805
3806 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003807#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003808 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003809 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003810 if (done_word(dest, ctx))
3811 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003812 if (!command->argv)
3813 goto skip; /* (... */
3814 if (command->argv[1]) { /* word word ... (... */
3815 syntax_error_unexpected_ch('(');
3816 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003817 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003818 /* it is "word(..." or "word (..." */
3819 do
3820 ch = i_getch(input);
3821 while (ch == ' ' || ch == '\t');
3822 if (ch != ')') {
3823 syntax_error_unexpected_ch(ch);
3824 return 1;
3825 }
3826 nommu_addchr(&ctx->as_string, ch);
3827 do
3828 ch = i_getch(input);
3829 while (ch == ' ' || ch == '\t' || ch == '\n');
3830 if (ch != '{') {
3831 syntax_error_unexpected_ch(ch);
3832 return 1;
3833 }
3834 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003835 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003836 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003837 }
3838#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003839
3840#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003841 if (command->argv /* word [word]{... */
3842 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003843 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003844 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003845 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003846 debug_printf_parse("parse_group return 1: "
3847 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003848 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003849 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003850#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003851
3852#if ENABLE_HUSH_FUNCTIONS
3853 skip:
3854#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003855 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003856 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003857 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003858 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003859 } else {
3860 /* bash does not allow "{echo...", requires whitespace */
3861 ch = i_getch(input);
3862 if (ch != ' ' && ch != '\t' && ch != '\n') {
3863 syntax_error_unexpected_ch(ch);
3864 return 1;
3865 }
3866 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003867 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003868
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003869 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003870#if BB_MMU
3871# define as_string NULL
3872#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003873 char *as_string = NULL;
3874#endif
3875 pipe_list = parse_stream(&as_string, input, endch);
3876#if !BB_MMU
3877 if (as_string)
3878 o_addstr(&ctx->as_string, as_string);
3879#endif
3880 /* empty ()/{} or parse error? */
3881 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003882 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003883 if (!BB_MMU)
3884 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003885 debug_printf_parse("parse_group return 1: "
3886 "parse_stream returned %p\n", pipe_list);
3887 return 1;
3888 }
3889 command->group = pipe_list;
3890#if !BB_MMU
3891 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3892 command->group_as_string = as_string;
3893 debug_printf_parse("end of group, remembering as:'%s'\n",
3894 command->group_as_string);
3895#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003896#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003897 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003898 debug_printf_parse("parse_group return 0\n");
3899 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003900 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003901}
3902
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003903#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003904/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003905static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003906/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003907static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003908{
3909 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003910 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003911 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003912 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003913 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003914 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003915 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003916 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003917 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003918 }
3919}
3920/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003921static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003922{
3923 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003924 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003925 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003926 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003927 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003928 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003929 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003930 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003931 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003932 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003933 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003934 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003935 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003936 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003937 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3938 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003939 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003940 continue;
3941 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003942 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003943 }
3944}
3945/* Process `cmd` - copy contents until "`" is seen. Complicated by
3946 * \` quoting.
3947 * "Within the backquoted style of command substitution, backslash
3948 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3949 * The search for the matching backquote shall be satisfied by the first
3950 * backquote found without a preceding backslash; during this search,
3951 * if a non-escaped backquote is encountered within a shell comment,
3952 * a here-document, an embedded command substitution of the $(command)
3953 * form, or a quoted string, undefined results occur. A single-quoted
3954 * or double-quoted string that begins, but does not end, within the
3955 * "`...`" sequence produces undefined results."
3956 * Example Output
3957 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3958 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003959static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003960{
3961 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003962 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003963 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003964 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003965 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003966 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3967 ch = i_getch(input);
3968 if (ch != '`'
3969 && ch != '$'
3970 && ch != '\\'
3971 && (!in_dquote || ch != '"')
3972 ) {
3973 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003974 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003975 }
3976 if (ch == EOF) {
3977 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003978 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003979 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003980 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003981 }
3982}
3983/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3984 * quoting and nested ()s.
3985 * "With the $(command) style of command substitution, all characters
3986 * following the open parenthesis to the matching closing parenthesis
3987 * constitute the command. Any valid shell script can be used for command,
3988 * except a script consisting solely of redirections which produces
3989 * unspecified results."
3990 * Example Output
3991 * echo $(echo '(TEST)' BEST) (TEST) BEST
3992 * echo $(echo 'TEST)' BEST) TEST) BEST
3993 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003994 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003995 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003996 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003997 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3998 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003999 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004000#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004001static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004002{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004003 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004004 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004005# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004006 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004007# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004008 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4009
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004010 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004011 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004012 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004013 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004014 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004015 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004016 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004017 if (!dbl)
4018 break;
4019 /* we look for closing )) of $((EXPR)) */
4020 if (i_peek(input) == end_ch) {
4021 i_getch(input); /* eat second ')' */
4022 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004023 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004024 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004025 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004026 if (ch == '(' || ch == '{') {
4027 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004028 if (!add_till_closing_bracket(dest, input, ch))
4029 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004030 o_addchr(dest, ch);
4031 continue;
4032 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004033 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004034 if (!add_till_single_quote(dest, input))
4035 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004036 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004037 continue;
4038 }
4039 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004040 if (!add_till_double_quote(dest, input))
4041 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004042 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004043 continue;
4044 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004045 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004046 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4047 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004048 o_addchr(dest, ch);
4049 continue;
4050 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004051 if (ch == '\\') {
4052 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004053 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004054 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004055 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004056 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004057 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004058 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004059 continue;
4060 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004061 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004062 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004063}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004064#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004065
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004066/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004067#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004068#define parse_dollar(as_string, dest, input, quote_mask) \
4069 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004070#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004071#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004072static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004073 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004074 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004075{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004076 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004077
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004078 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004079 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004080 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004081 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004082 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004083 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004084 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004085 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004086 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004087 quote_mask = 0;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004088 next_ch:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004089 ch = i_peek(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004090 if (!isalnum(ch) && ch != '_') {
4091 if (ch == '\\') {
4092 /* If backslash+newline, skip it */
4093 int ch2 = i_peek2(input);
4094 if (ch2 == '\n') {
4095 i_getch(input);
4096 i_getch(input);
4097 goto next_ch;
4098 }
4099 }
4100 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004101 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004102 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004103 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004104 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004105 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004106 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004107 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004108 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004109 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004110 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004111 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004112 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004113 o_addchr(dest, ch | quote_mask);
4114 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004115 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004116 case '$': /* pid */
4117 case '!': /* last bg pid */
4118 case '?': /* last exit code */
4119 case '#': /* number of args */
4120 case '*': /* args */
4121 case '@': /* args */
4122 goto make_one_char_var;
4123 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004124 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4125
Denys Vlasenko74369502010-05-21 19:52:01 +02004126 ch = i_getch(input); /* eat '{' */
4127 nommu_addchr(as_string, ch);
4128
4129 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004130 /* It should be ${?}, or ${#var},
4131 * or even ${?+subst} - operator acting on a special variable,
4132 * or the beginning of variable name.
4133 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004134 if (ch == EOF
4135 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4136 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004137 bad_dollar_syntax:
4138 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004139 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4140 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004141 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004142 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004143 ch |= quote_mask;
4144
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004145 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004146 * However, this regresses some of our testsuite cases
4147 * which check invalid constructs like ${%}.
4148 * Oh well... let's check that the var name part is fine... */
4149
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004150 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004151 unsigned pos;
4152
Denys Vlasenko74369502010-05-21 19:52:01 +02004153 o_addchr(dest, ch);
4154 debug_printf_parse(": '%c'\n", ch);
4155
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004156 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004157 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004158 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004159 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004160
Denys Vlasenko74369502010-05-21 19:52:01 +02004161 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004162 unsigned end_ch;
4163 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004164 /* handle parameter expansions
4165 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4166 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004167 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02004168 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004169
4170 /* Eat everything until closing '}' (or ':') */
4171 end_ch = '}';
4172 if (ENABLE_HUSH_BASH_COMPAT
4173 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004174 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004175 ) {
4176 /* It's ${var:N[:M]} thing */
4177 end_ch = '}' * 0x100 + ':';
4178 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004179 if (ENABLE_HUSH_BASH_COMPAT
4180 && ch == '/'
4181 ) {
4182 /* It's ${var/[/]pattern[/repl]} thing */
4183 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4184 i_getch(input);
4185 nommu_addchr(as_string, '/');
4186 ch = '\\';
4187 }
4188 end_ch = '}' * 0x100 + '/';
4189 }
4190 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004191 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004192 if (!BB_MMU)
4193 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004194#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004195 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004196 if (last_ch == 0) /* error? */
4197 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004198#else
4199#error Simple code to only allow ${var} is not implemented
4200#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004201 if (as_string) {
4202 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004203 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004204 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004205
4206 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4207 /* close the first block: */
4208 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004209 /* while parsing N from ${var:N[:M]}
4210 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004211 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004212 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004213 end_ch = '}';
4214 goto again;
4215 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004216 /* got '}' */
4217 if (end_ch == '}' * 0x100 + ':') {
4218 /* it's ${var:N} - emulate :999999999 */
4219 o_addstr(dest, "999999999");
4220 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004221 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004222 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004223 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004224 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004225 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4226 break;
4227 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004228#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004229 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004230 unsigned pos;
4231
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004232 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004233 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004234# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004235 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004236 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004237 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004238 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4239 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004240 if (!BB_MMU)
4241 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004242 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4243 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004244 if (as_string) {
4245 o_addstr(as_string, dest->data + pos);
4246 o_addchr(as_string, ')');
4247 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004248 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004249 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004250 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004251 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004252# endif
4253# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004254 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4255 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004256 if (!BB_MMU)
4257 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004258 if (!add_till_closing_bracket(dest, input, ')'))
4259 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004260 if (as_string) {
4261 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004262 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004263 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004264 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004265# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004266 break;
4267 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004268#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004269 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004270 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004271 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004272 ch = i_peek(input);
4273 if (isalnum(ch)) { /* it's $_name or $_123 */
4274 ch = '_';
4275 goto make_var;
4276 }
4277 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004278 /* TODO: $_ and $-: */
4279 /* $_ Shell or shell script name; or last argument of last command
4280 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4281 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004282 /* $- Option flags set by set builtin or shell options (-i etc) */
4283 default:
4284 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004285 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004286 debug_printf_parse("parse_dollar return 1 (ok)\n");
4287 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004288#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004289}
4290
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004291#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004292# if ENABLE_HUSH_BASH_COMPAT
4293#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4294 encode_string(dest, input, dquote_end, process_bkslash)
4295# else
4296/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4297#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4298 encode_string(dest, input, dquote_end)
4299# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004300#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004301
4302#else /* !MMU */
4303
4304# if ENABLE_HUSH_BASH_COMPAT
4305/* all parameters are needed, no macro tricks */
4306# else
4307#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4308 encode_string(as_string, dest, input, dquote_end)
4309# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004310#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004311static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004312 o_string *dest,
4313 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004314 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004315 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004316{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004317#if !ENABLE_HUSH_BASH_COMPAT
4318 const int process_bkslash = 1;
4319#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004320 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004321 int next;
4322
4323 again:
4324 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004325 if (ch != EOF)
4326 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004327 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004328 debug_printf_parse("encode_string return 1 (ok)\n");
4329 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004330 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004331 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004332 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004333 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004334 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004335 }
4336 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004337 if (ch != '\n') {
4338 next = i_peek(input);
4339 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004340 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004341 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004342 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004343 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004344 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004345 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004346 }
4347 /* bash:
4348 * "The backslash retains its special meaning [in "..."]
4349 * only when followed by one of the following characters:
4350 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004351 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004352 * NB: in (unquoted) heredoc, above does not apply to ",
4353 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004354 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004355 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004356 ch = i_getch(input); /* eat next */
4357 if (ch == '\n')
4358 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004359 } /* else: ch remains == '\\', and we double it below: */
4360 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004361 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004362 goto again;
4363 }
4364 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004365 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4366 debug_printf_parse("encode_string return 0: "
4367 "parse_dollar returned 0 (error)\n");
4368 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004369 }
4370 goto again;
4371 }
4372#if ENABLE_HUSH_TICK
4373 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004374 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004375 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4376 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004377 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4378 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004379 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4380 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004381 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004382 }
4383#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004384 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004385 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004386#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004387}
4388
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004389/*
4390 * Scan input until EOF or end_trigger char.
4391 * Return a list of pipes to execute, or NULL on EOF
4392 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004393 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004394 * reset parsing machinery and start parsing anew,
4395 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004396 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004397static struct pipe *parse_stream(char **pstring,
4398 struct in_str *input,
4399 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004400{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004401 struct parse_context ctx;
4402 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004403 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004404
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004405 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004406 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004407 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004408 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004409 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004410 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004411
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004412 /* If very first arg is "" or '', dest.data may end up NULL.
4413 * Preventing this: */
4414 o_addchr(&dest, '\0');
4415 dest.length = 0;
4416
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004417 /* We used to separate words on $IFS here. This was wrong.
4418 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004419 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004420 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004421
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004422 if (MAYBE_ASSIGNMENT != 0)
4423 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004424 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004425 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004426 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004427 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004428 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004429 int ch;
4430 int next;
4431 int redir_fd;
4432 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004433
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004434 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004435 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004436 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004437 if (ch == EOF) {
4438 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004439
4440 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004441 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004442 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004443 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004444 /* end_trigger == '}' case errors out earlier,
4445 * checking only ')' */
4446 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004447 syntax_error_unterm_ch('(');
4448 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004449 }
4450
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004451 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004452 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004453 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004454 o_free(&dest);
4455 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004456 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004457 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004458 /* (this makes bare "&" cmd a no-op.
4459 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004460 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004461 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004462 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004463 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004464 pi = NULL;
4465 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004466#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004467 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004468 if (pstring)
4469 *pstring = ctx.as_string.data;
4470 else
4471 o_free_unsafe(&ctx.as_string);
4472#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004473 debug_leave();
4474 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004475 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004476 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004477 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004478
4479 next = '\0';
4480 if (ch != '\n')
4481 next = i_peek(input);
4482
4483 is_special = "{}<>;&|()#'" /* special outside of "str" */
4484 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4485 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004486 if (ctx.command->argv /* word [word]{... - non-special */
4487 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004488 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004489 || (next != ';' /* }; - special */
4490 && next != ')' /* }) - special */
4491 && next != '&' /* }& and }&& ... - special */
4492 && next != '|' /* }|| ... - special */
4493 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004494 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004495 ) {
4496 /* They are not special, skip "{}" */
4497 is_special += 2;
4498 }
4499 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004500 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004501
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004502 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004503 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004504 o_addQchr(&dest, ch);
4505 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4506 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004507 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004508 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004509 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004510 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004511 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004512 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004513 continue;
4514 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004515
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004516 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004517 if (done_word(&dest, &ctx)) {
4518 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004519 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004520 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004521 /* Is this a case when newline is simply ignored?
4522 * Some examples:
4523 * "cmd | <newline> cmd ..."
4524 * "case ... in <newline> word) ..."
4525 */
4526 if (IS_NULL_CMD(ctx.command)
4527 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004528 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004529 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004530 * Without check #1, interactive shell
4531 * ignores even bare <newline>,
4532 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004533 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004534 * ps2> _ <=== wrong, should be ps1
4535 * Without check #2, "cmd & <newline>"
4536 * is similarly mistreated.
4537 * (BTW, this makes "cmd & cmd"
4538 * and "cmd && cmd" non-orthogonal.
4539 * Really, ask yourself, why
4540 * "cmd && <newline>" doesn't start
4541 * cmd but waits for more input?
4542 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004543 */
4544 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004545 if (pi->num_cmds != 0 /* check #1 */
4546 && pi->followup != PIPE_BG /* check #2 */
4547 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004548 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004549 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004550 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004551 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004552 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004553 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4554 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004555 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004556 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004557 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004558 heredoc_cnt = 0;
4559 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004560 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004561 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004562 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004563 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004564 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004565 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004566 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004567
4568 /* "cmd}" or "cmd }..." without semicolon or &:
4569 * } is an ordinary char in this case, even inside { cmd; }
4570 * Pathological example: { ""}; } should exec "}" cmd
4571 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004572 if (ch == '}') {
4573 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4574 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004575 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004576 ) {
4577 goto ordinary_char;
4578 }
4579 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4580 goto skip_end_trigger;
4581 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004582 }
4583
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004584 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004585 && (ch != ';' || heredoc_cnt == 0)
4586#if ENABLE_HUSH_CASE
4587 && (ch != ')'
4588 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004589 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004590 )
4591#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004592 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004593 if (heredoc_cnt) {
4594 /* This is technically valid:
4595 * { cat <<HERE; }; echo Ok
4596 * heredoc
4597 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004598 * HERE
4599 * but we don't support this.
4600 * We require heredoc to be in enclosing {}/(),
4601 * if any.
4602 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004603 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004604 goto parse_error;
4605 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004606 if (done_word(&dest, &ctx)) {
4607 goto parse_error;
4608 }
4609 done_pipe(&ctx, PIPE_SEQ);
4610 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004611 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004612 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004613 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004614 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004615 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004616 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004617#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004618 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004619 if (pstring)
4620 *pstring = ctx.as_string.data;
4621 else
4622 o_free_unsafe(&ctx.as_string);
4623#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004624 debug_leave();
4625 debug_printf_parse("parse_stream return %p: "
4626 "end_trigger char found\n",
4627 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004628 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004629 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004630 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004631 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004632 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004633 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004634
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004635 /* Catch <, > before deciding whether this word is
4636 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4637 switch (ch) {
4638 case '>':
4639 redir_fd = redirect_opt_num(&dest);
4640 if (done_word(&dest, &ctx)) {
4641 goto parse_error;
4642 }
4643 redir_style = REDIRECT_OVERWRITE;
4644 if (next == '>') {
4645 redir_style = REDIRECT_APPEND;
4646 ch = i_getch(input);
4647 nommu_addchr(&ctx.as_string, ch);
4648 }
4649#if 0
4650 else if (next == '(') {
4651 syntax_error(">(process) not supported");
4652 goto parse_error;
4653 }
4654#endif
4655 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4656 goto parse_error;
4657 continue; /* back to top of while (1) */
4658 case '<':
4659 redir_fd = redirect_opt_num(&dest);
4660 if (done_word(&dest, &ctx)) {
4661 goto parse_error;
4662 }
4663 redir_style = REDIRECT_INPUT;
4664 if (next == '<') {
4665 redir_style = REDIRECT_HEREDOC;
4666 heredoc_cnt++;
4667 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4668 ch = i_getch(input);
4669 nommu_addchr(&ctx.as_string, ch);
4670 } else if (next == '>') {
4671 redir_style = REDIRECT_IO;
4672 ch = i_getch(input);
4673 nommu_addchr(&ctx.as_string, ch);
4674 }
4675#if 0
4676 else if (next == '(') {
4677 syntax_error("<(process) not supported");
4678 goto parse_error;
4679 }
4680#endif
4681 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4682 goto parse_error;
4683 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004684 case '#':
4685 if (dest.length == 0 && !dest.has_quoted_part) {
4686 /* skip "#comment" */
4687 while (1) {
4688 ch = i_peek(input);
4689 if (ch == EOF || ch == '\n')
4690 break;
4691 i_getch(input);
4692 /* note: we do not add it to &ctx.as_string */
4693 }
4694 nommu_addchr(&ctx.as_string, '\n');
4695 continue; /* back to top of while (1) */
4696 }
4697 break;
4698 case '\\':
4699 if (next == '\n') {
4700 /* It's "\<newline>" */
4701#if !BB_MMU
4702 /* Remove trailing '\' from ctx.as_string */
4703 ctx.as_string.data[--ctx.as_string.length] = '\0';
4704#endif
4705 ch = i_getch(input); /* eat it */
4706 continue; /* back to top of while (1) */
4707 }
4708 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004709 }
4710
4711 if (dest.o_assignment == MAYBE_ASSIGNMENT
4712 /* check that we are not in word in "a=1 2>word b=1": */
4713 && !ctx.pending_redirect
4714 ) {
4715 /* ch is a special char and thus this word
4716 * cannot be an assignment */
4717 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004718 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004719 }
4720
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004721 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4722
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004723 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004724 case '#': /* non-comment #: "echo a#b" etc */
4725 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004726 break;
4727 case '\\':
4728 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004729 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004730 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004731 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004732 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004733 /* note: ch != '\n' (that case does not reach this place) */
4734 o_addchr(&dest, '\\');
4735 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4736 o_addchr(&dest, ch);
4737 nommu_addchr(&ctx.as_string, ch);
4738 /* Example: echo Hello \2>file
4739 * we need to know that word 2 is quoted */
4740 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004741 break;
4742 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004743 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004744 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004745 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004746 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004747 }
Eric Andersen25f27032001-04-26 23:22:31 +00004748 break;
4749 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004750 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004751 if (next == '\'' && !ctx.pending_redirect) {
4752 insert_empty_quoted_str_marker:
4753 nommu_addchr(&ctx.as_string, next);
4754 i_getch(input); /* eat second ' */
4755 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4756 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4757 } else {
4758 while (1) {
4759 ch = i_getch(input);
4760 if (ch == EOF) {
4761 syntax_error_unterm_ch('\'');
4762 goto parse_error;
4763 }
4764 nommu_addchr(&ctx.as_string, ch);
4765 if (ch == '\'')
4766 break;
4767 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004768 }
Eric Andersen25f27032001-04-26 23:22:31 +00004769 }
Eric Andersen25f27032001-04-26 23:22:31 +00004770 break;
4771 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004772 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004773 if (next == '"' && !ctx.pending_redirect)
4774 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004775 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004776 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004777 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004778 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004779 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004780 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004781#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004782 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004783 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004784
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004785 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4786 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004787 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004788 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4789 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004790# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004791 o_addstr(&ctx.as_string, dest.data + pos);
4792 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004793# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004794 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4795 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004796 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004797 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004798#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004799 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004800#if ENABLE_HUSH_CASE
4801 case_semi:
4802#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004803 if (done_word(&dest, &ctx)) {
4804 goto parse_error;
4805 }
4806 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004807#if ENABLE_HUSH_CASE
4808 /* Eat multiple semicolons, detect
4809 * whether it means something special */
4810 while (1) {
4811 ch = i_peek(input);
4812 if (ch != ';')
4813 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004814 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004815 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004816 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004817 ctx.ctx_dsemicolon = 1;
4818 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004819 break;
4820 }
4821 }
4822#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004823 new_cmd:
4824 /* We just finished a cmd. New one may start
4825 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004826 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004827 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004828 break;
4829 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004830 if (done_word(&dest, &ctx)) {
4831 goto parse_error;
4832 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004833 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004834 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004835 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004836 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004837 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004838 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004839 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004840 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004841 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004842 if (done_word(&dest, &ctx)) {
4843 goto parse_error;
4844 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004845#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004846 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004847 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004848#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004849 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004850 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004851 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004852 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004853 } else {
4854 /* we could pick up a file descriptor choice here
4855 * with redirect_opt_num(), but bash doesn't do it.
4856 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004857 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004858 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004859 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004860 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004861#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004862 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004863 if (ctx.ctx_res_w == RES_MATCH
4864 && ctx.command->argv == NULL /* not (word|(... */
4865 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004866 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004867 ) {
4868 continue;
4869 }
4870#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004871 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004872 if (parse_group(&dest, &ctx, input, ch) != 0) {
4873 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004874 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004875 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004876 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004877#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004878 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004879 goto case_semi;
4880#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004881 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004882 /* proper use of this character is caught by end_trigger:
4883 * if we see {, we call parse_group(..., end_trigger='}')
4884 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004885 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004886 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004887 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004888 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004889 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004890 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004891 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004892
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004893 parse_error:
4894 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004895 struct parse_context *pctx;
4896 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004897
4898 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004899 * Sample for finding leaks on syntax error recovery path.
4900 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004901 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004902 * Samples to catch leaks at execution:
4903 * while if (true | {true;}); then echo ok; fi; do break; done
4904 * 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 +00004905 */
4906 pctx = &ctx;
4907 do {
4908 /* Update pipe/command counts,
4909 * otherwise freeing may miss some */
4910 done_pipe(pctx, PIPE_SEQ);
4911 debug_printf_clean("freeing list %p from ctx %p\n",
4912 pctx->list_head, pctx);
4913 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004914 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004915 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004916#if !BB_MMU
4917 o_free_unsafe(&pctx->as_string);
4918#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004919 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004920 if (pctx != &ctx) {
4921 free(pctx);
4922 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004923 IF_HAS_KEYWORDS(pctx = p2;)
4924 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004925
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004926 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004927 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004928#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004929 if (pstring)
4930 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004931#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004932 debug_leave();
4933 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004934 }
Eric Andersen25f27032001-04-26 23:22:31 +00004935}
4936
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004937
4938/*** Execution routines ***/
4939
4940/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004941#if !ENABLE_HUSH_BASH_COMPAT
4942/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4943#define expand_string_to_string(str, do_unbackslash) \
4944 expand_string_to_string(str)
4945#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004946static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004947#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004948static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004949#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004950
4951/* expand_strvec_to_strvec() takes a list of strings, expands
4952 * all variable references within and returns a pointer to
4953 * a list of expanded strings, possibly with larger number
4954 * of strings. (Think VAR="a b"; echo $VAR).
4955 * This new list is allocated as a single malloc block.
4956 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004957 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004958 * Caller can deallocate entire list by single free(list). */
4959
Denys Vlasenko238081f2010-10-03 14:26:26 +02004960/* A horde of its helpers come first: */
4961
4962static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4963{
4964 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004965 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004966
Denys Vlasenko9e800222010-10-03 14:28:04 +02004967#if ENABLE_HUSH_BRACE_EXPANSION
4968 if (c == '{' || c == '}') {
4969 /* { -> \{, } -> \} */
4970 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004971 /* And now we want to add { or } and continue:
4972 * o_addchr(o, c);
4973 * continue;
4974 * luckily, just falling throught achieves this.
4975 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004976 }
4977#endif
4978 o_addchr(o, c);
4979 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004980 /* \z -> \\\z; \<eol> -> \\<eol> */
4981 o_addchr(o, '\\');
4982 if (len) {
4983 len--;
4984 o_addchr(o, '\\');
4985 o_addchr(o, *str++);
4986 }
4987 }
4988 }
4989}
4990
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004991/* Store given string, finalizing the word and starting new one whenever
4992 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004993 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4994 * Return in *ended_with_ifs:
4995 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4996 */
4997static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004998{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004999 int last_is_ifs = 0;
5000
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005001 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005002 int word_len;
5003
5004 if (!*str) /* EOL - do not finalize word */
5005 break;
5006 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005007 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005008 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005009 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005010 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005011 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005012 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005013 * Example: "v='\*'; echo b$v" prints "b\*"
5014 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005015 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005016 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005017 /*/ Why can't we do it easier? */
5018 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5019 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5020 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005021 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005022 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005023 if (!*str) /* EOL - do not finalize word */
5024 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005025 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005026
5027 /* We know str here points to at least one IFS char */
5028 last_is_ifs = 1;
5029 str += strspn(str, G.ifs); /* skip IFS chars */
5030 if (!*str) /* EOL - do not finalize word */
5031 break;
5032
5033 /* Start new word... but not always! */
5034 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005035 if (output->has_quoted_part
5036 /* Case "v=' a'; echo $v":
5037 * here nothing precedes the space in $v expansion,
5038 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005039 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005040 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005041 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005042 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005043 o_addchr(output, '\0');
5044 debug_print_list("expand_on_ifs", output, n);
5045 n = o_save_ptr(output, n);
5046 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005047 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005048
5049 if (ended_with_ifs)
5050 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005051 debug_print_list("expand_on_ifs[1]", output, n);
5052 return n;
5053}
5054
5055/* Helper to expand $((...)) and heredoc body. These act as if
5056 * they are in double quotes, with the exception that they are not :).
5057 * Just the rules are similar: "expand only $var and `cmd`"
5058 *
5059 * Returns malloced string.
5060 * As an optimization, we return NULL if expansion is not needed.
5061 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005062#if !ENABLE_HUSH_BASH_COMPAT
5063/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5064#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5065 encode_then_expand_string(str)
5066#endif
5067static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005068{
5069 char *exp_str;
5070 struct in_str input;
5071 o_string dest = NULL_O_STRING;
5072
5073 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005074 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005075#if ENABLE_HUSH_TICK
5076 && !strchr(str, '`')
5077#endif
5078 ) {
5079 return NULL;
5080 }
5081
5082 /* We need to expand. Example:
5083 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5084 */
5085 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005086 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005087//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005088 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005089 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005090 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5091 o_free_unsafe(&dest);
5092 return exp_str;
5093}
5094
5095#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02005096static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005097{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005098 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005099 arith_t res;
5100 char *exp_str;
5101
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005102 math_state.lookupvar = get_local_var_value;
5103 math_state.setvar = set_local_var_from_halves;
5104 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005105 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005106 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005107 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005108 if (errmsg_p)
5109 *errmsg_p = math_state.errmsg;
5110 if (math_state.errmsg)
5111 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005112 return res;
5113}
5114#endif
5115
5116#if ENABLE_HUSH_BASH_COMPAT
5117/* ${var/[/]pattern[/repl]} helpers */
5118static char *strstr_pattern(char *val, const char *pattern, int *size)
5119{
5120 while (1) {
5121 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5122 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5123 if (end) {
5124 *size = end - val;
5125 return val;
5126 }
5127 if (*val == '\0')
5128 return NULL;
5129 /* Optimization: if "*pat" did not match the start of "string",
5130 * we know that "tring", "ring" etc will not match too:
5131 */
5132 if (pattern[0] == '*')
5133 return NULL;
5134 val++;
5135 }
5136}
5137static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5138{
5139 char *result = NULL;
5140 unsigned res_len = 0;
5141 unsigned repl_len = strlen(repl);
5142
5143 while (1) {
5144 int size;
5145 char *s = strstr_pattern(val, pattern, &size);
5146 if (!s)
5147 break;
5148
5149 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5150 memcpy(result + res_len, val, s - val);
5151 res_len += s - val;
5152 strcpy(result + res_len, repl);
5153 res_len += repl_len;
5154 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5155
5156 val = s + size;
5157 if (exp_op == '/')
5158 break;
5159 }
5160 if (val[0] && result) {
5161 result = xrealloc(result, res_len + strlen(val) + 1);
5162 strcpy(result + res_len, val);
5163 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5164 }
5165 debug_printf_varexp("result:'%s'\n", result);
5166 return result;
5167}
5168#endif
5169
5170/* Helper:
5171 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5172 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005173static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005174{
5175 const char *val = NULL;
5176 char *to_be_freed = NULL;
5177 char *p = *pp;
5178 char *var;
5179 char first_char;
5180 char exp_op;
5181 char exp_save = exp_save; /* for compiler */
5182 char *exp_saveptr; /* points to expansion operator */
5183 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005184 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005185
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005186 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005187 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005188 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005189 arg0 = arg[0];
5190 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005191 exp_op = 0;
5192
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005193 if (first_char == '#' /* ${#... */
5194 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5195 ) {
5196 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005197 var++;
5198 exp_op = 'L';
5199 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005200 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005201 if (exp_saveptr /* if 2nd char is one of expansion operators */
5202 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5203 ) {
5204 /* ${?:0}, ${#[:]%0} etc */
5205 exp_saveptr = var + 1;
5206 } else {
5207 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5208 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5209 }
5210 exp_op = exp_save = *exp_saveptr;
5211 if (exp_op) {
5212 exp_word = exp_saveptr + 1;
5213 if (exp_op == ':') {
5214 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005215//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005216 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005217 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005218 ) {
5219 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5220 exp_op = ':';
5221 exp_word--;
5222 }
5223 }
5224 *exp_saveptr = '\0';
5225 } /* else: it's not an expansion op, but bare ${var} */
5226 }
5227
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005228 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005229 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005230 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005231 int n = xatoi_positive(var);
5232 if (n < G.global_argc)
5233 val = G.global_argv[n];
5234 /* else val remains NULL: $N with too big N */
5235 } else {
5236 switch (var[0]) {
5237 case '$': /* pid */
5238 val = utoa(G.root_pid);
5239 break;
5240 case '!': /* bg pid */
5241 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5242 break;
5243 case '?': /* exitcode */
5244 val = utoa(G.last_exitcode);
5245 break;
5246 case '#': /* argc */
5247 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5248 break;
5249 default:
5250 val = get_local_var_value(var);
5251 }
5252 }
5253
5254 /* Handle any expansions */
5255 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005256 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005257 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005258 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005259 debug_printf_expand("%s\n", val);
5260 } else if (exp_op) {
5261 if (exp_op == '%' || exp_op == '#') {
5262 /* Standard-mandated substring removal ops:
5263 * ${parameter%word} - remove smallest suffix pattern
5264 * ${parameter%%word} - remove largest suffix pattern
5265 * ${parameter#word} - remove smallest prefix pattern
5266 * ${parameter##word} - remove largest prefix pattern
5267 *
5268 * Word is expanded to produce a glob pattern.
5269 * Then var's value is matched to it and matching part removed.
5270 */
5271 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005272 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005273 char *exp_exp_word;
5274 char *loc;
5275 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005276 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005277 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005278 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005279 if (exp_exp_word)
5280 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005281 /* HACK ALERT. We depend here on the fact that
5282 * G.global_argv and results of utoa and get_local_var_value
5283 * are actually in writable memory:
5284 * scan_and_match momentarily stores NULs there. */
5285 t = (char*)val;
5286 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005287 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005288 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005289 free(exp_exp_word);
5290 if (loc) { /* match was found */
5291 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005292 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005293 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005294 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005295 }
5296 }
5297 }
5298#if ENABLE_HUSH_BASH_COMPAT
5299 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005300 /* It's ${var/[/]pattern[/repl]} thing.
5301 * Note that in encoded form it has TWO parts:
5302 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005303 * and if // is used, it is encoded as \:
5304 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005305 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005306 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005307 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005308 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005309 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005310 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005311 * by the usual expansion rules:
5312 * >az; >bz;
5313 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5314 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5315 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5316 * v='a bz'; echo ${v/a*z/\z} prints "z"
5317 * (note that a*z _pattern_ is never globbed!)
5318 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005319 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005320 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005321 if (!pattern)
5322 pattern = xstrdup(exp_word);
5323 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5324 *p++ = SPECIAL_VAR_SYMBOL;
5325 exp_word = p;
5326 p = strchr(p, SPECIAL_VAR_SYMBOL);
5327 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005328 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005329 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5330 /* HACK ALERT. We depend here on the fact that
5331 * G.global_argv and results of utoa and get_local_var_value
5332 * are actually in writable memory:
5333 * replace_pattern momentarily stores NULs there. */
5334 t = (char*)val;
5335 to_be_freed = replace_pattern(t,
5336 pattern,
5337 (repl ? repl : exp_word),
5338 exp_op);
5339 if (to_be_freed) /* at least one replace happened */
5340 val = to_be_freed;
5341 free(pattern);
5342 free(repl);
5343 }
5344 }
5345#endif
5346 else if (exp_op == ':') {
5347#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5348 /* It's ${var:N[:M]} bashism.
5349 * Note that in encoded form it has TWO parts:
5350 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5351 */
5352 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005353 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005354
Denys Vlasenko063847d2010-09-15 13:33:02 +02005355 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5356 if (errmsg)
5357 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005358 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5359 *p++ = SPECIAL_VAR_SYMBOL;
5360 exp_word = p;
5361 p = strchr(p, SPECIAL_VAR_SYMBOL);
5362 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005363 len = expand_and_evaluate_arith(exp_word, &errmsg);
5364 if (errmsg)
5365 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005366 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005367 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005368 if (beg < 0) /* bash compat */
5369 beg = 0;
5370 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005371 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005372 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005373 val = NULL;
5374 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005375 /* Paranoia. What if user entered 9999999999999
5376 * which fits in arith_t but not int? */
5377 if (len >= INT_MAX)
5378 len = INT_MAX;
5379 val = to_be_freed = xstrndup(val + beg, len);
5380 }
5381 debug_printf_varexp("val:'%s'\n", val);
5382 } else
5383#endif
5384 {
5385 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005386 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005387 }
5388 } else { /* one of "-=+?" */
5389 /* Standard-mandated substitution ops:
5390 * ${var?word} - indicate error if unset
5391 * If var is unset, word (or a message indicating it is unset
5392 * if word is null) is written to standard error
5393 * and the shell exits with a non-zero exit status.
5394 * Otherwise, the value of var is substituted.
5395 * ${var-word} - use default value
5396 * If var is unset, word is substituted.
5397 * ${var=word} - assign and use default value
5398 * If var is unset, word is assigned to var.
5399 * In all cases, final value of var is substituted.
5400 * ${var+word} - use alternative value
5401 * If var is unset, null is substituted.
5402 * Otherwise, word is substituted.
5403 *
5404 * Word is subjected to tilde expansion, parameter expansion,
5405 * command substitution, and arithmetic expansion.
5406 * If word is not needed, it is not expanded.
5407 *
5408 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5409 * but also treat null var as if it is unset.
5410 */
5411 int use_word = (!val || ((exp_save == ':') && !val[0]));
5412 if (exp_op == '+')
5413 use_word = !use_word;
5414 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5415 (exp_save == ':') ? "true" : "false", use_word);
5416 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005417 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005418 if (to_be_freed)
5419 exp_word = to_be_freed;
5420 if (exp_op == '?') {
5421 /* mimic bash message */
5422 die_if_script("%s: %s",
5423 var,
5424 exp_word[0] ? exp_word : "parameter null or not set"
5425 );
5426//TODO: how interactive bash aborts expansion mid-command?
5427 } else {
5428 val = exp_word;
5429 }
5430
5431 if (exp_op == '=') {
5432 /* ${var=[word]} or ${var:=[word]} */
5433 if (isdigit(var[0]) || var[0] == '#') {
5434 /* mimic bash message */
5435 die_if_script("$%s: cannot assign in this way", var);
5436 val = NULL;
5437 } else {
5438 char *new_var = xasprintf("%s=%s", var, val);
5439 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5440 }
5441 }
5442 }
5443 } /* one of "-=+?" */
5444
5445 *exp_saveptr = exp_save;
5446 } /* if (exp_op) */
5447
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005448 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005449
5450 *pp = p;
5451 *to_be_freed_pp = to_be_freed;
5452 return val;
5453}
5454
5455/* Expand all variable references in given string, adding words to list[]
5456 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5457 * to be filled). This routine is extremely tricky: has to deal with
5458 * variables/parameters with whitespace, $* and $@, and constructs like
5459 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005460static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005461{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005462 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005463 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005464 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005465 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005466 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005467 char *p;
5468
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005469 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5470 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005471 debug_print_list("expand_vars_to_list", output, n);
5472 n = o_save_ptr(output, n);
5473 debug_print_list("expand_vars_to_list[0]", output, n);
5474
5475 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5476 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005477 char *to_be_freed = NULL;
5478 const char *val = NULL;
5479#if ENABLE_HUSH_TICK
5480 o_string subst_result = NULL_O_STRING;
5481#endif
5482#if ENABLE_SH_MATH_SUPPORT
5483 char arith_buf[sizeof(arith_t)*3 + 2];
5484#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005485
5486 if (ended_in_ifs) {
5487 o_addchr(output, '\0');
5488 n = o_save_ptr(output, n);
5489 ended_in_ifs = 0;
5490 }
5491
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005492 o_addblock(output, arg, p - arg);
5493 debug_print_list("expand_vars_to_list[1]", output, n);
5494 arg = ++p;
5495 p = strchr(p, SPECIAL_VAR_SYMBOL);
5496
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005497 /* Fetch special var name (if it is indeed one of them)
5498 * and quote bit, force the bit on if singleword expansion -
5499 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005500 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005501
5502 /* Is this variable quoted and thus expansion can't be null?
5503 * "$@" is special. Even if quoted, it can still
5504 * expand to nothing (not even an empty string),
5505 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005506 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005507 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005508
5509 switch (first_ch & 0x7f) {
5510 /* Highest bit in first_ch indicates that var is double-quoted */
5511 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005512 case '@': {
5513 int i;
5514 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005515 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005516 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005517 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005518 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005519 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005520 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005521 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5522 if (G.global_argv[i++][0] && G.global_argv[i]) {
5523 /* this argv[] is not empty and not last:
5524 * put terminating NUL, start new word */
5525 o_addchr(output, '\0');
5526 debug_print_list("expand_vars_to_list[2]", output, n);
5527 n = o_save_ptr(output, n);
5528 debug_print_list("expand_vars_to_list[3]", output, n);
5529 }
5530 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005531 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005532 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005533 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005534 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005535 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005536 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005537 while (1) {
5538 o_addQstr(output, G.global_argv[i]);
5539 if (++i >= G.global_argc)
5540 break;
5541 o_addchr(output, '\0');
5542 debug_print_list("expand_vars_to_list[4]", output, n);
5543 n = o_save_ptr(output, n);
5544 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005545 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005546 while (1) {
5547 o_addQstr(output, G.global_argv[i]);
5548 if (!G.global_argv[++i])
5549 break;
5550 if (G.ifs[0])
5551 o_addchr(output, G.ifs[0]);
5552 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005553 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005554 }
5555 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005556 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005557 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5558 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005559 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005560 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005561 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005562 break;
5563#if ENABLE_HUSH_TICK
5564 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005565 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005566 arg++;
5567 /* Can't just stuff it into output o_string,
5568 * expanded result may need to be globbed
5569 * and $IFS-splitted */
5570 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5571 G.last_exitcode = process_command_subs(&subst_result, arg);
5572 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5573 val = subst_result.data;
5574 goto store_val;
5575#endif
5576#if ENABLE_SH_MATH_SUPPORT
5577 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5578 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005579
5580 arg++; /* skip '+' */
5581 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5582 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005583 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005584 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5585 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005586 val = arith_buf;
5587 break;
5588 }
5589#endif
5590 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005591 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005592 IF_HUSH_TICK(store_val:)
5593 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005594 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5595 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005596 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005597 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005598 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005599 }
5600 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005601 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005602 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5603 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005604 }
5605 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005606 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5607
5608 if (val && val[0]) {
5609 o_addQstr(output, val);
5610 }
5611 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005612
5613 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5614 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005615 if (*p != SPECIAL_VAR_SYMBOL)
5616 *p = SPECIAL_VAR_SYMBOL;
5617
5618#if ENABLE_HUSH_TICK
5619 o_free(&subst_result);
5620#endif
5621 arg = ++p;
5622 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5623
5624 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005625 if (ended_in_ifs) {
5626 o_addchr(output, '\0');
5627 n = o_save_ptr(output, n);
5628 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005629 debug_print_list("expand_vars_to_list[a]", output, n);
5630 /* this part is literal, and it was already pre-quoted
5631 * if needed (much earlier), do not use o_addQstr here! */
5632 o_addstr_with_NUL(output, arg);
5633 debug_print_list("expand_vars_to_list[b]", output, n);
5634 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005635 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005636 ) {
5637 n--;
5638 /* allow to reuse list[n] later without re-growth */
5639 output->has_empty_slot = 1;
5640 } else {
5641 o_addchr(output, '\0');
5642 }
5643
5644 return n;
5645}
5646
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005647static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005648{
5649 int n;
5650 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005651 o_string output = NULL_O_STRING;
5652
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005653 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005654
5655 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005656 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005657 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005658 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005659 }
5660 debug_print_list("expand_variables", &output, n);
5661
5662 /* output.data (malloced in one block) gets returned in "list" */
5663 list = o_finalize_list(&output, n);
5664 debug_print_strings("expand_variables[1]", list);
5665 return list;
5666}
5667
5668static char **expand_strvec_to_strvec(char **argv)
5669{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005670 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005671}
5672
5673#if ENABLE_HUSH_BASH_COMPAT
5674static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5675{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005676 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005677}
5678#endif
5679
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005680/* Used for expansion of right hand of assignments,
5681 * $((...)), heredocs, variable espansion parts.
5682 *
5683 * NB: should NOT do globbing!
5684 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5685 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005686static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005687{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005688#if !ENABLE_HUSH_BASH_COMPAT
5689 const int do_unbackslash = 1;
5690#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005691 char *argv[2], **list;
5692
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005693 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005694 /* This is generally an optimization, but it also
5695 * handles "", which otherwise trips over !list[0] check below.
5696 * (is this ever happens that we actually get str="" here?)
5697 */
5698 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5699 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005700 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005701 return xstrdup(str);
5702 }
5703
5704 argv[0] = (char*)str;
5705 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005706 list = expand_variables(argv, do_unbackslash
5707 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5708 : EXP_FLAG_SINGLEWORD
5709 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005710 if (HUSH_DEBUG)
5711 if (!list[0] || list[1])
5712 bb_error_msg_and_die("BUG in varexp2");
5713 /* actually, just move string 2*sizeof(char*) bytes back */
5714 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005715 if (do_unbackslash)
5716 unbackslash((char*)list);
5717 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005718 return (char*)list;
5719}
5720
5721/* Used for "eval" builtin */
5722static char* expand_strvec_to_string(char **argv)
5723{
5724 char **list;
5725
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005726 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005727 /* Convert all NULs to spaces */
5728 if (list[0]) {
5729 int n = 1;
5730 while (list[n]) {
5731 if (HUSH_DEBUG)
5732 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5733 bb_error_msg_and_die("BUG in varexp3");
5734 /* bash uses ' ' regardless of $IFS contents */
5735 list[n][-1] = ' ';
5736 n++;
5737 }
5738 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02005739 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005740 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5741 return (char*)list;
5742}
5743
5744static char **expand_assignments(char **argv, int count)
5745{
5746 int i;
5747 char **p;
5748
5749 G.expanded_assignments = p = NULL;
5750 /* Expand assignments into one string each */
5751 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005752 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005753 }
5754 G.expanded_assignments = NULL;
5755 return p;
5756}
5757
5758
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005759static void switch_off_special_sigs(unsigned mask)
5760{
5761 unsigned sig = 0;
5762 while ((mask >>= 1) != 0) {
5763 sig++;
5764 if (!(mask & 1))
5765 continue;
5766 if (G.traps) {
5767 if (G.traps[sig] && !G.traps[sig][0])
5768 /* trap is '', has to remain SIG_IGN */
5769 continue;
5770 free(G.traps[sig]);
5771 G.traps[sig] = NULL;
5772 }
5773 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005774 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005775 }
5776}
5777
Denys Vlasenkob347df92011-08-09 22:49:15 +02005778#if BB_MMU
5779/* never called */
5780void re_execute_shell(char ***to_free, const char *s,
5781 char *g_argv0, char **g_argv,
5782 char **builtin_argv) NORETURN;
5783
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005784static void reset_traps_to_defaults(void)
5785{
5786 /* This function is always called in a child shell
5787 * after fork (not vfork, NOMMU doesn't use this function).
5788 */
5789 unsigned sig;
5790 unsigned mask;
5791
5792 /* Child shells are not interactive.
5793 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5794 * Testcase: (while :; do :; done) + ^Z should background.
5795 * Same goes for SIGTERM, SIGHUP, SIGINT.
5796 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005797 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5798 if (!G.traps && !mask)
5799 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005800
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005801 /* Switch off special sigs */
5802 switch_off_special_sigs(mask);
5803#if ENABLE_HUSH_JOB
5804 G_fatal_sig_mask = 0;
5805#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005806 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005807 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5808 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005809
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005810 if (!G.traps)
5811 return;
5812
5813 /* Reset all sigs to default except ones with empty traps */
5814 for (sig = 0; sig < NSIG; sig++) {
5815 if (!G.traps[sig])
5816 continue; /* no trap: nothing to do */
5817 if (!G.traps[sig][0])
5818 continue; /* empty trap: has to remain SIG_IGN */
5819 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005820 free(G.traps[sig]);
5821 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005822 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005823 if (sig == 0)
5824 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005825 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005826 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005827}
5828
5829#else /* !BB_MMU */
5830
5831static void re_execute_shell(char ***to_free, const char *s,
5832 char *g_argv0, char **g_argv,
5833 char **builtin_argv) NORETURN;
5834static void re_execute_shell(char ***to_free, const char *s,
5835 char *g_argv0, char **g_argv,
5836 char **builtin_argv)
5837{
5838# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5839 /* delims + 2 * (number of bytes in printed hex numbers) */
5840 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5841 char *heredoc_argv[4];
5842 struct variable *cur;
5843# if ENABLE_HUSH_FUNCTIONS
5844 struct function *funcp;
5845# endif
5846 char **argv, **pp;
5847 unsigned cnt;
5848 unsigned long long empty_trap_mask;
5849
5850 if (!g_argv0) { /* heredoc */
5851 argv = heredoc_argv;
5852 argv[0] = (char *) G.argv0_for_re_execing;
5853 argv[1] = (char *) "-<";
5854 argv[2] = (char *) s;
5855 argv[3] = NULL;
5856 pp = &argv[3]; /* used as pointer to empty environment */
5857 goto do_exec;
5858 }
5859
5860 cnt = 0;
5861 pp = builtin_argv;
5862 if (pp) while (*pp++)
5863 cnt++;
5864
5865 empty_trap_mask = 0;
5866 if (G.traps) {
5867 int sig;
5868 for (sig = 1; sig < NSIG; sig++) {
5869 if (G.traps[sig] && !G.traps[sig][0])
5870 empty_trap_mask |= 1LL << sig;
5871 }
5872 }
5873
5874 sprintf(param_buf, NOMMU_HACK_FMT
5875 , (unsigned) G.root_pid
5876 , (unsigned) G.root_ppid
5877 , (unsigned) G.last_bg_pid
5878 , (unsigned) G.last_exitcode
5879 , cnt
5880 , empty_trap_mask
5881 IF_HUSH_LOOPS(, G.depth_of_loop)
5882 );
5883# undef NOMMU_HACK_FMT
5884 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5885 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5886 */
5887 cnt += 6;
5888 for (cur = G.top_var; cur; cur = cur->next) {
5889 if (!cur->flg_export || cur->flg_read_only)
5890 cnt += 2;
5891 }
5892# if ENABLE_HUSH_FUNCTIONS
5893 for (funcp = G.top_func; funcp; funcp = funcp->next)
5894 cnt += 3;
5895# endif
5896 pp = g_argv;
5897 while (*pp++)
5898 cnt++;
5899 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5900 *pp++ = (char *) G.argv0_for_re_execing;
5901 *pp++ = param_buf;
5902 for (cur = G.top_var; cur; cur = cur->next) {
5903 if (strcmp(cur->varstr, hush_version_str) == 0)
5904 continue;
5905 if (cur->flg_read_only) {
5906 *pp++ = (char *) "-R";
5907 *pp++ = cur->varstr;
5908 } else if (!cur->flg_export) {
5909 *pp++ = (char *) "-V";
5910 *pp++ = cur->varstr;
5911 }
5912 }
5913# if ENABLE_HUSH_FUNCTIONS
5914 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5915 *pp++ = (char *) "-F";
5916 *pp++ = funcp->name;
5917 *pp++ = funcp->body_as_string;
5918 }
5919# endif
5920 /* We can pass activated traps here. Say, -Tnn:trap_string
5921 *
5922 * However, POSIX says that subshells reset signals with traps
5923 * to SIG_DFL.
5924 * I tested bash-3.2 and it not only does that with true subshells
5925 * of the form ( list ), but with any forked children shells.
5926 * I set trap "echo W" WINCH; and then tried:
5927 *
5928 * { echo 1; sleep 20; echo 2; } &
5929 * while true; do echo 1; sleep 20; echo 2; break; done &
5930 * true | { echo 1; sleep 20; echo 2; } | cat
5931 *
5932 * In all these cases sending SIGWINCH to the child shell
5933 * did not run the trap. If I add trap "echo V" WINCH;
5934 * _inside_ group (just before echo 1), it works.
5935 *
5936 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005937 */
5938 *pp++ = (char *) "-c";
5939 *pp++ = (char *) s;
5940 if (builtin_argv) {
5941 while (*++builtin_argv)
5942 *pp++ = *builtin_argv;
5943 *pp++ = (char *) "";
5944 }
5945 *pp++ = g_argv0;
5946 while (*g_argv)
5947 *pp++ = *g_argv++;
5948 /* *pp = NULL; - is already there */
5949 pp = environ;
5950
5951 do_exec:
5952 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02005953 /* Don't propagate SIG_IGN to the child */
5954 if (SPECIAL_JOBSTOP_SIGS != 0)
5955 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005956 execve(bb_busybox_exec_path, argv, pp);
5957 /* Fallback. Useful for init=/bin/hush usage etc */
5958 if (argv[0][0] == '/')
5959 execve(argv[0], argv, pp);
5960 xfunc_error_retval = 127;
5961 bb_error_msg_and_die("can't re-execute the shell");
5962}
5963#endif /* !BB_MMU */
5964
5965
5966static int run_and_free_list(struct pipe *pi);
5967
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005968/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005969 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5970 * end_trigger controls how often we stop parsing
5971 * NUL: parse all, execute, return
5972 * ';': parse till ';' or newline, execute, repeat till EOF
5973 */
5974static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005975{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005976 /* Why we need empty flag?
5977 * An obscure corner case "false; ``; echo $?":
5978 * empty command in `` should still set $? to 0.
5979 * But we can't just set $? to 0 at the start,
5980 * this breaks "false; echo `echo $?`" case.
5981 */
5982 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005983 while (1) {
5984 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005985
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005986#if ENABLE_HUSH_INTERACTIVE
5987 if (end_trigger == ';')
5988 inp->promptmode = 0; /* PS1 */
5989#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005990 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005991 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5992 /* If we are in "big" script
5993 * (not in `cmd` or something similar)...
5994 */
5995 if (pipe_list == ERR_PTR && end_trigger == ';') {
5996 /* Discard cached input (rest of line) */
5997 int ch = inp->last_char;
5998 while (ch != EOF && ch != '\n') {
5999 //bb_error_msg("Discarded:'%c'", ch);
6000 ch = i_getch(inp);
6001 }
6002 /* Force prompt */
6003 inp->p = NULL;
6004 /* This stream isn't empty */
6005 empty = 0;
6006 continue;
6007 }
6008 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006009 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006010 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006011 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006012 debug_print_tree(pipe_list, 0);
6013 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6014 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006015 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006016#if ENABLE_HUSH_FUNCTIONS
6017 if (G.flag_return_in_progress == 1)
6018 break;
6019#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006020 }
Eric Andersen25f27032001-04-26 23:22:31 +00006021}
6022
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006023static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006024{
6025 struct in_str input;
6026 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006027 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006028}
6029
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006030static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006031{
Eric Andersen25f27032001-04-26 23:22:31 +00006032 struct in_str input;
6033 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006034 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006035}
6036
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006037#if ENABLE_HUSH_TICK
6038static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6039{
6040 pid_t pid;
6041 int channel[2];
6042# if !BB_MMU
6043 char **to_free = NULL;
6044# endif
6045
6046 xpipe(channel);
6047 pid = BB_MMU ? xfork() : xvfork();
6048 if (pid == 0) { /* child */
6049 disable_restore_tty_pgrp_on_exit();
6050 /* Process substitution is not considered to be usual
6051 * 'command execution'.
6052 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6053 */
6054 bb_signals(0
6055 + (1 << SIGTSTP)
6056 + (1 << SIGTTIN)
6057 + (1 << SIGTTOU)
6058 , SIG_IGN);
6059 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6060 close(channel[0]); /* NB: close _first_, then move fd! */
6061 xmove_fd(channel[1], 1);
6062 /* Prevent it from trying to handle ctrl-z etc */
6063 IF_HUSH_JOB(G.run_list_level = 1;)
6064 /* Awful hack for `trap` or $(trap).
6065 *
6066 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6067 * contains an example where "trap" is executed in a subshell:
6068 *
6069 * save_traps=$(trap)
6070 * ...
6071 * eval "$save_traps"
6072 *
6073 * Standard does not say that "trap" in subshell shall print
6074 * parent shell's traps. It only says that its output
6075 * must have suitable form, but then, in the above example
6076 * (which is not supposed to be normative), it implies that.
6077 *
6078 * bash (and probably other shell) does implement it
6079 * (traps are reset to defaults, but "trap" still shows them),
6080 * but as a result, "trap" logic is hopelessly messed up:
6081 *
6082 * # trap
6083 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6084 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6085 * # true | trap <--- trap is in subshell - no output (ditto)
6086 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6087 * trap -- 'echo Ho' SIGWINCH
6088 * # echo `(trap)` <--- in subshell in subshell - output
6089 * trap -- 'echo Ho' SIGWINCH
6090 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6091 * trap -- 'echo Ho' SIGWINCH
6092 *
6093 * The rules when to forget and when to not forget traps
6094 * get really complex and nonsensical.
6095 *
6096 * Our solution: ONLY bare $(trap) or `trap` is special.
6097 */
6098 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006099 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006100 && skip_whitespace(s + 4)[0] == '\0'
6101 ) {
6102 static const char *const argv[] = { NULL, NULL };
6103 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006104 fflush_all(); /* important */
6105 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006106 }
6107# if BB_MMU
6108 reset_traps_to_defaults();
6109 parse_and_run_string(s);
6110 _exit(G.last_exitcode);
6111# else
6112 /* We re-execute after vfork on NOMMU. This makes this script safe:
6113 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6114 * huge=`cat BIG` # was blocking here forever
6115 * echo OK
6116 */
6117 re_execute_shell(&to_free,
6118 s,
6119 G.global_argv[0],
6120 G.global_argv + 1,
6121 NULL);
6122# endif
6123 }
6124
6125 /* parent */
6126 *pid_p = pid;
6127# if ENABLE_HUSH_FAST
6128 G.count_SIGCHLD++;
6129//bb_error_msg("[%d] fork in generate_stream_from_string:"
6130// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6131// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6132# endif
6133 enable_restore_tty_pgrp_on_exit();
6134# if !BB_MMU
6135 free(to_free);
6136# endif
6137 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006138 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006139}
6140
6141/* Return code is exit status of the process that is run. */
6142static int process_command_subs(o_string *dest, const char *s)
6143{
6144 FILE *fp;
6145 struct in_str pipe_str;
6146 pid_t pid;
6147 int status, ch, eol_cnt;
6148
6149 fp = generate_stream_from_string(s, &pid);
6150
6151 /* Now send results of command back into original context */
6152 setup_file_in_str(&pipe_str, fp);
6153 eol_cnt = 0;
6154 while ((ch = i_getch(&pipe_str)) != EOF) {
6155 if (ch == '\n') {
6156 eol_cnt++;
6157 continue;
6158 }
6159 while (eol_cnt) {
6160 o_addchr(dest, '\n');
6161 eol_cnt--;
6162 }
6163 o_addQchr(dest, ch);
6164 }
6165
6166 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006167 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006168 /* We need to extract exitcode. Test case
6169 * "true; echo `sleep 1; false` $?"
6170 * should print 1 */
6171 safe_waitpid(pid, &status, 0);
6172 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6173 return WEXITSTATUS(status);
6174}
6175#endif /* ENABLE_HUSH_TICK */
6176
6177
6178static void setup_heredoc(struct redir_struct *redir)
6179{
6180 struct fd_pair pair;
6181 pid_t pid;
6182 int len, written;
6183 /* the _body_ of heredoc (misleading field name) */
6184 const char *heredoc = redir->rd_filename;
6185 char *expanded;
6186#if !BB_MMU
6187 char **to_free;
6188#endif
6189
6190 expanded = NULL;
6191 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006192 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006193 if (expanded)
6194 heredoc = expanded;
6195 }
6196 len = strlen(heredoc);
6197
6198 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6199 xpiped_pair(pair);
6200 xmove_fd(pair.rd, redir->rd_fd);
6201
6202 /* Try writing without forking. Newer kernels have
6203 * dynamically growing pipes. Must use non-blocking write! */
6204 ndelay_on(pair.wr);
6205 while (1) {
6206 written = write(pair.wr, heredoc, len);
6207 if (written <= 0)
6208 break;
6209 len -= written;
6210 if (len == 0) {
6211 close(pair.wr);
6212 free(expanded);
6213 return;
6214 }
6215 heredoc += written;
6216 }
6217 ndelay_off(pair.wr);
6218
6219 /* Okay, pipe buffer was not big enough */
6220 /* Note: we must not create a stray child (bastard? :)
6221 * for the unsuspecting parent process. Child creates a grandchild
6222 * and exits before parent execs the process which consumes heredoc
6223 * (that exec happens after we return from this function) */
6224#if !BB_MMU
6225 to_free = NULL;
6226#endif
6227 pid = xvfork();
6228 if (pid == 0) {
6229 /* child */
6230 disable_restore_tty_pgrp_on_exit();
6231 pid = BB_MMU ? xfork() : xvfork();
6232 if (pid != 0)
6233 _exit(0);
6234 /* grandchild */
6235 close(redir->rd_fd); /* read side of the pipe */
6236#if BB_MMU
6237 full_write(pair.wr, heredoc, len); /* may loop or block */
6238 _exit(0);
6239#else
6240 /* Delegate blocking writes to another process */
6241 xmove_fd(pair.wr, STDOUT_FILENO);
6242 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6243#endif
6244 }
6245 /* parent */
6246#if ENABLE_HUSH_FAST
6247 G.count_SIGCHLD++;
6248//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6249#endif
6250 enable_restore_tty_pgrp_on_exit();
6251#if !BB_MMU
6252 free(to_free);
6253#endif
6254 close(pair.wr);
6255 free(expanded);
6256 wait(NULL); /* wait till child has died */
6257}
6258
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006259/* fd: redirect wants this fd to be used (e.g. 3>file).
6260 * Move all conflicting internally used fds,
6261 * and remember them so that we can restore them later.
6262 */
6263static int save_fds_on_redirect(int fd, int squirrel[3])
6264{
6265 if (squirrel) {
6266 /* Handle redirects of fds 0,1,2 */
6267
6268 /* If we collide with an already moved stdio fd... */
6269 if (fd == squirrel[0]) {
6270 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6271 return 1;
6272 }
6273 if (fd == squirrel[1]) {
6274 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6275 return 1;
6276 }
6277 if (fd == squirrel[2]) {
6278 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6279 return 1;
6280 }
6281 /* If we are about to redirect stdio fd, and did not yet move it... */
6282 if (fd <= 2 && squirrel[fd] < 0) {
6283 /* We avoid taking stdio fds */
6284 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6285 if (squirrel[fd] < 0 && errno != EBADF)
6286 xfunc_die();
6287 return 0; /* "we did not close fd" */
6288 }
6289 }
6290
6291#if ENABLE_HUSH_INTERACTIVE
6292 if (fd != 0 && fd == G.interactive_fd) {
6293 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6294 return 1;
6295 }
6296#endif
6297
6298 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6299 * (1) Redirect in a forked child. No need to save FILEs' fds,
6300 * we aren't going to use them anymore, ok to trash.
6301 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6302 * but how are we doing to use them?
6303 * "fileno(fd) = new_fd" can't be done.
6304 */
6305 if (!squirrel)
6306 return 0;
6307
6308 return save_FILEs_on_redirect(fd);
6309}
6310
6311static void restore_redirects(int squirrel[3])
6312{
6313 int i, fd;
6314 for (i = 0; i <= 2; i++) {
6315 fd = squirrel[i];
6316 if (fd != -1) {
6317 /* We simply die on error */
6318 xmove_fd(fd, i);
6319 }
6320 }
6321
6322 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6323
6324 restore_redirected_FILEs();
6325}
6326
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006327/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6328 * and stderr if they are redirected. */
6329static int setup_redirects(struct command *prog, int squirrel[])
6330{
6331 int openfd, mode;
6332 struct redir_struct *redir;
6333
6334 for (redir = prog->redirects; redir; redir = redir->next) {
6335 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006336 /* "rd_fd<<HERE" case */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006337 save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006338 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6339 * of the heredoc */
6340 debug_printf_parse("set heredoc '%s'\n",
6341 redir->rd_filename);
6342 setup_heredoc(redir);
6343 continue;
6344 }
6345
6346 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006347 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006348 char *p;
6349 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02006350 /*
6351 * Examples:
6352 * "cmd >" (no filename)
6353 * "cmd > <file" (2nd redirect starts too early)
6354 */
6355 die_if_script("syntax error: %s", "invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006356 continue;
6357 }
6358 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006359 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006360 openfd = open_or_warn(p, mode);
6361 free(p);
6362 if (openfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006363 /* Error message from open_or_warn can be lost
6364 * if stderr has been redirected, but bash
6365 * and ash both lose it as well
6366 * (though zsh doesn't!)
6367 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006368 return 1;
6369 }
6370 } else {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006371 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006372 openfd = redir->rd_dup;
6373 }
6374
6375 if (openfd != redir->rd_fd) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006376 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006377 if (openfd == REDIRFD_CLOSE) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006378 /* "rd_fd >&-" means "close me" */
6379 if (!closed) {
6380 /* ^^^ optimization: saving may already
6381 * have closed it. If not... */
6382 close(redir->rd_fd);
6383 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006384 } else {
6385 xdup2(openfd, redir->rd_fd);
6386 if (redir->rd_dup == REDIRFD_TO_FILE)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006387 /* "rd_fd > FILE" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006388 close(openfd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006389 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006390 }
6391 }
6392 }
6393 return 0;
6394}
6395
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006396static char *find_in_path(const char *arg)
6397{
6398 char *ret = NULL;
6399 const char *PATH = get_local_var_value("PATH");
6400
6401 if (!PATH)
6402 return NULL;
6403
6404 while (1) {
6405 const char *end = strchrnul(PATH, ':');
6406 int sz = end - PATH; /* must be int! */
6407
6408 free(ret);
6409 if (sz != 0) {
6410 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6411 } else {
6412 /* We have xxx::yyyy in $PATH,
6413 * it means "use current dir" */
6414 ret = xstrdup(arg);
6415 }
6416 if (access(ret, F_OK) == 0)
6417 break;
6418
6419 if (*end == '\0') {
6420 free(ret);
6421 return NULL;
6422 }
6423 PATH = end + 1;
6424 }
6425
6426 return ret;
6427}
6428
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006429static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006430 const struct built_in_command *x,
6431 const struct built_in_command *end)
6432{
6433 while (x != end) {
6434 if (strcmp(name, x->b_cmd) != 0) {
6435 x++;
6436 continue;
6437 }
6438 debug_printf_exec("found builtin '%s'\n", name);
6439 return x;
6440 }
6441 return NULL;
6442}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006443static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006444{
6445 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6446}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006447static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006448{
6449 const struct built_in_command *x = find_builtin1(name);
6450 if (x)
6451 return x;
6452 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6453}
6454
6455#if ENABLE_HUSH_FUNCTIONS
6456static struct function **find_function_slot(const char *name)
6457{
6458 struct function **funcpp = &G.top_func;
6459 while (*funcpp) {
6460 if (strcmp(name, (*funcpp)->name) == 0) {
6461 break;
6462 }
6463 funcpp = &(*funcpp)->next;
6464 }
6465 return funcpp;
6466}
6467
6468static const struct function *find_function(const char *name)
6469{
6470 const struct function *funcp = *find_function_slot(name);
6471 if (funcp)
6472 debug_printf_exec("found function '%s'\n", name);
6473 return funcp;
6474}
6475
6476/* Note: takes ownership on name ptr */
6477static struct function *new_function(char *name)
6478{
6479 struct function **funcpp = find_function_slot(name);
6480 struct function *funcp = *funcpp;
6481
6482 if (funcp != NULL) {
6483 struct command *cmd = funcp->parent_cmd;
6484 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6485 if (!cmd) {
6486 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6487 free(funcp->name);
6488 /* Note: if !funcp->body, do not free body_as_string!
6489 * This is a special case of "-F name body" function:
6490 * body_as_string was not malloced! */
6491 if (funcp->body) {
6492 free_pipe_list(funcp->body);
6493# if !BB_MMU
6494 free(funcp->body_as_string);
6495# endif
6496 }
6497 } else {
6498 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6499 cmd->argv[0] = funcp->name;
6500 cmd->group = funcp->body;
6501# if !BB_MMU
6502 cmd->group_as_string = funcp->body_as_string;
6503# endif
6504 }
6505 } else {
6506 debug_printf_exec("remembering new function '%s'\n", name);
6507 funcp = *funcpp = xzalloc(sizeof(*funcp));
6508 /*funcp->next = NULL;*/
6509 }
6510
6511 funcp->name = name;
6512 return funcp;
6513}
6514
6515static void unset_func(const char *name)
6516{
6517 struct function **funcpp = find_function_slot(name);
6518 struct function *funcp = *funcpp;
6519
6520 if (funcp != NULL) {
6521 debug_printf_exec("freeing function '%s'\n", funcp->name);
6522 *funcpp = funcp->next;
6523 /* funcp is unlinked now, deleting it.
6524 * Note: if !funcp->body, the function was created by
6525 * "-F name body", do not free ->body_as_string
6526 * and ->name as they were not malloced. */
6527 if (funcp->body) {
6528 free_pipe_list(funcp->body);
6529 free(funcp->name);
6530# if !BB_MMU
6531 free(funcp->body_as_string);
6532# endif
6533 }
6534 free(funcp);
6535 }
6536}
6537
6538# if BB_MMU
6539#define exec_function(to_free, funcp, argv) \
6540 exec_function(funcp, argv)
6541# endif
6542static void exec_function(char ***to_free,
6543 const struct function *funcp,
6544 char **argv) NORETURN;
6545static void exec_function(char ***to_free,
6546 const struct function *funcp,
6547 char **argv)
6548{
6549# if BB_MMU
6550 int n = 1;
6551
6552 argv[0] = G.global_argv[0];
6553 G.global_argv = argv;
6554 while (*++argv)
6555 n++;
6556 G.global_argc = n;
6557 /* On MMU, funcp->body is always non-NULL */
6558 n = run_list(funcp->body);
6559 fflush_all();
6560 _exit(n);
6561# else
6562 re_execute_shell(to_free,
6563 funcp->body_as_string,
6564 G.global_argv[0],
6565 argv + 1,
6566 NULL);
6567# endif
6568}
6569
6570static int run_function(const struct function *funcp, char **argv)
6571{
6572 int rc;
6573 save_arg_t sv;
6574 smallint sv_flg;
6575
6576 save_and_replace_G_args(&sv, argv);
6577
6578 /* "we are in function, ok to use return" */
6579 sv_flg = G.flag_return_in_progress;
6580 G.flag_return_in_progress = -1;
6581# if ENABLE_HUSH_LOCAL
6582 G.func_nest_level++;
6583# endif
6584
6585 /* On MMU, funcp->body is always non-NULL */
6586# if !BB_MMU
6587 if (!funcp->body) {
6588 /* Function defined by -F */
6589 parse_and_run_string(funcp->body_as_string);
6590 rc = G.last_exitcode;
6591 } else
6592# endif
6593 {
6594 rc = run_list(funcp->body);
6595 }
6596
6597# if ENABLE_HUSH_LOCAL
6598 {
6599 struct variable *var;
6600 struct variable **var_pp;
6601
6602 var_pp = &G.top_var;
6603 while ((var = *var_pp) != NULL) {
6604 if (var->func_nest_level < G.func_nest_level) {
6605 var_pp = &var->next;
6606 continue;
6607 }
6608 /* Unexport */
6609 if (var->flg_export)
6610 bb_unsetenv(var->varstr);
6611 /* Remove from global list */
6612 *var_pp = var->next;
6613 /* Free */
6614 if (!var->max_len)
6615 free(var->varstr);
6616 free(var);
6617 }
6618 G.func_nest_level--;
6619 }
6620# endif
6621 G.flag_return_in_progress = sv_flg;
6622
6623 restore_G_args(&sv, argv);
6624
6625 return rc;
6626}
6627#endif /* ENABLE_HUSH_FUNCTIONS */
6628
6629
6630#if BB_MMU
6631#define exec_builtin(to_free, x, argv) \
6632 exec_builtin(x, argv)
6633#else
6634#define exec_builtin(to_free, x, argv) \
6635 exec_builtin(to_free, argv)
6636#endif
6637static void exec_builtin(char ***to_free,
6638 const struct built_in_command *x,
6639 char **argv) NORETURN;
6640static void exec_builtin(char ***to_free,
6641 const struct built_in_command *x,
6642 char **argv)
6643{
6644#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006645 int rcode;
6646 fflush_all();
6647 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006648 fflush_all();
6649 _exit(rcode);
6650#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006651 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006652 /* On NOMMU, we must never block!
6653 * Example: { sleep 99 | read line; } & echo Ok
6654 */
6655 re_execute_shell(to_free,
6656 argv[0],
6657 G.global_argv[0],
6658 G.global_argv + 1,
6659 argv);
6660#endif
6661}
6662
6663
6664static void execvp_or_die(char **argv) NORETURN;
6665static void execvp_or_die(char **argv)
6666{
6667 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006668 /* Don't propagate SIG_IGN to the child */
6669 if (SPECIAL_JOBSTOP_SIGS != 0)
6670 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006671 execvp(argv[0], argv);
6672 bb_perror_msg("can't execute '%s'", argv[0]);
6673 _exit(127); /* bash compat */
6674}
6675
6676#if ENABLE_HUSH_MODE_X
6677static void dump_cmd_in_x_mode(char **argv)
6678{
6679 if (G_x_mode && argv) {
6680 /* We want to output the line in one write op */
6681 char *buf, *p;
6682 int len;
6683 int n;
6684
6685 len = 3;
6686 n = 0;
6687 while (argv[n])
6688 len += strlen(argv[n++]) + 1;
6689 buf = xmalloc(len);
6690 buf[0] = '+';
6691 p = buf + 1;
6692 n = 0;
6693 while (argv[n])
6694 p += sprintf(p, " %s", argv[n++]);
6695 *p++ = '\n';
6696 *p = '\0';
6697 fputs(buf, stderr);
6698 free(buf);
6699 }
6700}
6701#else
6702# define dump_cmd_in_x_mode(argv) ((void)0)
6703#endif
6704
6705#if BB_MMU
6706#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6707 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6708#define pseudo_exec(nommu_save, command, argv_expanded) \
6709 pseudo_exec(command, argv_expanded)
6710#endif
6711
6712/* Called after [v]fork() in run_pipe, or from builtin_exec.
6713 * Never returns.
6714 * Don't exit() here. If you don't exec, use _exit instead.
6715 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006716 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006717 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006718static void pseudo_exec_argv(nommu_save_t *nommu_save,
6719 char **argv, int assignment_cnt,
6720 char **argv_expanded) NORETURN;
6721static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6722 char **argv, int assignment_cnt,
6723 char **argv_expanded)
6724{
6725 char **new_env;
6726
6727 new_env = expand_assignments(argv, assignment_cnt);
6728 dump_cmd_in_x_mode(new_env);
6729
6730 if (!argv[assignment_cnt]) {
6731 /* Case when we are here: ... | var=val | ...
6732 * (note that we do not exit early, i.e., do not optimize out
6733 * expand_assignments(): think about ... | var=`sleep 1` | ...
6734 */
6735 free_strings(new_env);
6736 _exit(EXIT_SUCCESS);
6737 }
6738
6739#if BB_MMU
6740 set_vars_and_save_old(new_env);
6741 free(new_env); /* optional */
6742 /* we can also destroy set_vars_and_save_old's return value,
6743 * to save memory */
6744#else
6745 nommu_save->new_env = new_env;
6746 nommu_save->old_vars = set_vars_and_save_old(new_env);
6747#endif
6748
6749 if (argv_expanded) {
6750 argv = argv_expanded;
6751 } else {
6752 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6753#if !BB_MMU
6754 nommu_save->argv = argv;
6755#endif
6756 }
6757 dump_cmd_in_x_mode(argv);
6758
6759#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6760 if (strchr(argv[0], '/') != NULL)
6761 goto skip;
6762#endif
6763
6764 /* Check if the command matches any of the builtins.
6765 * Depending on context, this might be redundant. But it's
6766 * easier to waste a few CPU cycles than it is to figure out
6767 * if this is one of those cases.
6768 */
6769 {
6770 /* On NOMMU, it is more expensive to re-execute shell
6771 * just in order to run echo or test builtin.
6772 * It's better to skip it here and run corresponding
6773 * non-builtin later. */
6774 const struct built_in_command *x;
6775 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6776 if (x) {
6777 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6778 }
6779 }
6780#if ENABLE_HUSH_FUNCTIONS
6781 /* Check if the command matches any functions */
6782 {
6783 const struct function *funcp = find_function(argv[0]);
6784 if (funcp) {
6785 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6786 }
6787 }
6788#endif
6789
6790#if ENABLE_FEATURE_SH_STANDALONE
6791 /* Check if the command matches any busybox applets */
6792 {
6793 int a = find_applet_by_name(argv[0]);
6794 if (a >= 0) {
6795# if BB_MMU /* see above why on NOMMU it is not allowed */
6796 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006797 /* Do not leak open fds from opened script files etc */
6798 close_all_FILE_list();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006799 debug_printf_exec("running applet '%s'\n", argv[0]);
6800 run_applet_no_and_exit(a, argv);
6801 }
6802# endif
6803 /* Re-exec ourselves */
6804 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006805 /* Don't propagate SIG_IGN to the child */
6806 if (SPECIAL_JOBSTOP_SIGS != 0)
6807 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006808 execv(bb_busybox_exec_path, argv);
6809 /* If they called chroot or otherwise made the binary no longer
6810 * executable, fall through */
6811 }
6812 }
6813#endif
6814
6815#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6816 skip:
6817#endif
6818 execvp_or_die(argv);
6819}
6820
6821/* Called after [v]fork() in run_pipe
6822 */
6823static void pseudo_exec(nommu_save_t *nommu_save,
6824 struct command *command,
6825 char **argv_expanded) NORETURN;
6826static void pseudo_exec(nommu_save_t *nommu_save,
6827 struct command *command,
6828 char **argv_expanded)
6829{
6830 if (command->argv) {
6831 pseudo_exec_argv(nommu_save, command->argv,
6832 command->assignment_cnt, argv_expanded);
6833 }
6834
6835 if (command->group) {
6836 /* Cases when we are here:
6837 * ( list )
6838 * { list } &
6839 * ... | ( list ) | ...
6840 * ... | { list } | ...
6841 */
6842#if BB_MMU
6843 int rcode;
6844 debug_printf_exec("pseudo_exec: run_list\n");
6845 reset_traps_to_defaults();
6846 rcode = run_list(command->group);
6847 /* OK to leak memory by not calling free_pipe_list,
6848 * since this process is about to exit */
6849 _exit(rcode);
6850#else
6851 re_execute_shell(&nommu_save->argv_from_re_execing,
6852 command->group_as_string,
6853 G.global_argv[0],
6854 G.global_argv + 1,
6855 NULL);
6856#endif
6857 }
6858
6859 /* Case when we are here: ... | >file */
6860 debug_printf_exec("pseudo_exec'ed null command\n");
6861 _exit(EXIT_SUCCESS);
6862}
6863
6864#if ENABLE_HUSH_JOB
6865static const char *get_cmdtext(struct pipe *pi)
6866{
6867 char **argv;
6868 char *p;
6869 int len;
6870
6871 /* This is subtle. ->cmdtext is created only on first backgrounding.
6872 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6873 * On subsequent bg argv is trashed, but we won't use it */
6874 if (pi->cmdtext)
6875 return pi->cmdtext;
6876 argv = pi->cmds[0].argv;
6877 if (!argv || !argv[0]) {
6878 pi->cmdtext = xzalloc(1);
6879 return pi->cmdtext;
6880 }
6881
6882 len = 0;
6883 do {
6884 len += strlen(*argv) + 1;
6885 } while (*++argv);
6886 p = xmalloc(len);
6887 pi->cmdtext = p;
6888 argv = pi->cmds[0].argv;
6889 do {
6890 len = strlen(*argv);
6891 memcpy(p, *argv, len);
6892 p += len;
6893 *p++ = ' ';
6894 } while (*++argv);
6895 p[-1] = '\0';
6896 return pi->cmdtext;
6897}
6898
6899static void insert_bg_job(struct pipe *pi)
6900{
6901 struct pipe *job, **jobp;
6902 int i;
6903
6904 /* Linear search for the ID of the job to use */
6905 pi->jobid = 1;
6906 for (job = G.job_list; job; job = job->next)
6907 if (job->jobid >= pi->jobid)
6908 pi->jobid = job->jobid + 1;
6909
6910 /* Add job to the list of running jobs */
6911 jobp = &G.job_list;
6912 while ((job = *jobp) != NULL)
6913 jobp = &job->next;
6914 job = *jobp = xmalloc(sizeof(*job));
6915
6916 *job = *pi; /* physical copy */
6917 job->next = NULL;
6918 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6919 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6920 for (i = 0; i < pi->num_cmds; i++) {
6921 job->cmds[i].pid = pi->cmds[i].pid;
6922 /* all other fields are not used and stay zero */
6923 }
6924 job->cmdtext = xstrdup(get_cmdtext(pi));
6925
6926 if (G_interactive_fd)
6927 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6928 G.last_jobid = job->jobid;
6929}
6930
6931static void remove_bg_job(struct pipe *pi)
6932{
6933 struct pipe *prev_pipe;
6934
6935 if (pi == G.job_list) {
6936 G.job_list = pi->next;
6937 } else {
6938 prev_pipe = G.job_list;
6939 while (prev_pipe->next != pi)
6940 prev_pipe = prev_pipe->next;
6941 prev_pipe->next = pi->next;
6942 }
6943 if (G.job_list)
6944 G.last_jobid = G.job_list->jobid;
6945 else
6946 G.last_jobid = 0;
6947}
6948
6949/* Remove a backgrounded job */
6950static void delete_finished_bg_job(struct pipe *pi)
6951{
6952 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006953 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006954}
6955#endif /* JOB */
6956
6957/* Check to see if any processes have exited -- if they
6958 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006959static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006960{
6961 int attributes;
6962 int status;
6963#if ENABLE_HUSH_JOB
6964 struct pipe *pi;
6965#endif
6966 pid_t childpid;
6967 int rcode = 0;
6968
6969 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6970
6971 attributes = WUNTRACED;
6972 if (fg_pipe == NULL)
6973 attributes |= WNOHANG;
6974
6975 errno = 0;
6976#if ENABLE_HUSH_FAST
6977 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6978//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6979//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6980 /* There was neither fork nor SIGCHLD since last waitpid */
6981 /* Avoid doing waitpid syscall if possible */
6982 if (!G.we_have_children) {
6983 errno = ECHILD;
6984 return -1;
6985 }
6986 if (fg_pipe == NULL) { /* is WNOHANG set? */
6987 /* We have children, but they did not exit
6988 * or stop yet (we saw no SIGCHLD) */
6989 return 0;
6990 }
6991 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6992 }
6993#endif
6994
6995/* Do we do this right?
6996 * bash-3.00# sleep 20 | false
6997 * <ctrl-Z pressed>
6998 * [3]+ Stopped sleep 20 | false
6999 * bash-3.00# echo $?
7000 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7001 * [hush 1.14.0: yes we do it right]
7002 */
7003 wait_more:
7004 while (1) {
7005 int i;
7006 int dead;
7007
7008#if ENABLE_HUSH_FAST
7009 i = G.count_SIGCHLD;
7010#endif
7011 childpid = waitpid(-1, &status, attributes);
7012 if (childpid <= 0) {
7013 if (childpid && errno != ECHILD)
7014 bb_perror_msg("waitpid");
7015#if ENABLE_HUSH_FAST
7016 else { /* Until next SIGCHLD, waitpid's are useless */
7017 G.we_have_children = (childpid == 0);
7018 G.handled_SIGCHLD = i;
7019//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7020 }
7021#endif
7022 break;
7023 }
7024 dead = WIFEXITED(status) || WIFSIGNALED(status);
7025
7026#if DEBUG_JOBS
7027 if (WIFSTOPPED(status))
7028 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7029 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7030 if (WIFSIGNALED(status))
7031 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7032 childpid, WTERMSIG(status), WEXITSTATUS(status));
7033 if (WIFEXITED(status))
7034 debug_printf_jobs("pid %d exited, exitcode %d\n",
7035 childpid, WEXITSTATUS(status));
7036#endif
7037 /* Were we asked to wait for fg pipe? */
7038 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01007039 i = fg_pipe->num_cmds;
7040 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007041 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7042 if (fg_pipe->cmds[i].pid != childpid)
7043 continue;
7044 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007045 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007046 fg_pipe->cmds[i].pid = 0;
7047 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007048 ex = WEXITSTATUS(status);
7049 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01007050 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007051 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7052 */
7053 if (WIFSIGNALED(status)) {
7054 int sig = WTERMSIG(status);
7055 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01007056 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
Denys Vlasenkod60752f2015-10-07 22:42:45 +02007057 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01007058 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007059 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7060 * Maybe we need to use sig | 128? */
7061 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007062 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007063 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007064 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007065 fg_pipe->stopped_cmds++;
7066 }
7067 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7068 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01007069 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007070 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007071 i = fg_pipe->num_cmds;
7072 while (--i >= 0) {
7073 rcode = fg_pipe->cmds[i].cmd_exitcode;
7074 /* usually last process gives overall exitstatus,
7075 * but with "set -o pipefail", last *failed* process does */
7076 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7077 break;
7078 }
7079 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007080/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7081 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7082 * and "killall -STOP cat" */
7083 if (G_interactive_fd) {
7084#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01007085 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007086 insert_bg_job(fg_pipe);
7087#endif
7088 return rcode;
7089 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01007090 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007091 return rcode;
7092 }
7093 /* There are still running processes in the fg pipe */
7094 goto wait_more; /* do waitpid again */
7095 }
7096 /* it wasnt fg_pipe, look for process in bg pipes */
7097 }
7098
7099#if ENABLE_HUSH_JOB
7100 /* We asked to wait for bg or orphaned children */
7101 /* No need to remember exitcode in this case */
7102 for (pi = G.job_list; pi; pi = pi->next) {
7103 for (i = 0; i < pi->num_cmds; i++) {
7104 if (pi->cmds[i].pid == childpid)
7105 goto found_pi_and_prognum;
7106 }
7107 }
7108 /* Happens when shell is used as init process (init=/bin/sh) */
7109 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7110 continue; /* do waitpid again */
7111
7112 found_pi_and_prognum:
7113 if (dead) {
7114 /* child exited */
7115 pi->cmds[i].pid = 0;
7116 pi->alive_cmds--;
7117 if (!pi->alive_cmds) {
7118 if (G_interactive_fd)
7119 printf(JOB_STATUS_FORMAT, pi->jobid,
7120 "Done", pi->cmdtext);
7121 delete_finished_bg_job(pi);
7122 }
7123 } else {
7124 /* child stopped */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007125 pi->stopped_cmds++;
7126 }
7127#endif
7128 } /* while (waitpid succeeds)... */
7129
7130 return rcode;
7131}
7132
7133#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007134static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007135{
7136 pid_t p;
7137 int rcode = checkjobs(fg_pipe);
7138 if (G_saved_tty_pgrp) {
7139 /* Job finished, move the shell to the foreground */
7140 p = getpgrp(); /* our process group id */
7141 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7142 tcsetpgrp(G_interactive_fd, p);
7143 }
7144 return rcode;
7145}
7146#endif
7147
7148/* Start all the jobs, but don't wait for anything to finish.
7149 * See checkjobs().
7150 *
7151 * Return code is normally -1, when the caller has to wait for children
7152 * to finish to determine the exit status of the pipe. If the pipe
7153 * is a simple builtin command, however, the action is done by the
7154 * time run_pipe returns, and the exit code is provided as the
7155 * return value.
7156 *
7157 * Returns -1 only if started some children. IOW: we have to
7158 * mask out retvals of builtins etc with 0xff!
7159 *
7160 * The only case when we do not need to [v]fork is when the pipe
7161 * is single, non-backgrounded, non-subshell command. Examples:
7162 * cmd ; ... { list } ; ...
7163 * cmd && ... { list } && ...
7164 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007165 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007166 * or (if SH_STANDALONE) an applet, and we can run the { list }
7167 * with run_list. If it isn't one of these, we fork and exec cmd.
7168 *
7169 * Cases when we must fork:
7170 * non-single: cmd | cmd
7171 * backgrounded: cmd & { list } &
7172 * subshell: ( list ) [&]
7173 */
7174#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01007175#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007176 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7177#endif
7178static int redirect_and_varexp_helper(char ***new_env_p,
7179 struct variable **old_vars_p,
7180 struct command *command,
7181 int squirrel[3],
7182 char **argv_expanded)
7183{
7184 /* setup_redirects acts on file descriptors, not FILEs.
7185 * This is perfect for work that comes after exec().
7186 * Is it really safe for inline use? Experimentally,
7187 * things seem to work. */
7188 int rcode = setup_redirects(command, squirrel);
7189 if (rcode == 0) {
7190 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7191 *new_env_p = new_env;
7192 dump_cmd_in_x_mode(new_env);
7193 dump_cmd_in_x_mode(argv_expanded);
7194 if (old_vars_p)
7195 *old_vars_p = set_vars_and_save_old(new_env);
7196 }
7197 return rcode;
7198}
7199static NOINLINE int run_pipe(struct pipe *pi)
7200{
7201 static const char *const null_ptr = NULL;
7202
7203 int cmd_no;
7204 int next_infd;
7205 struct command *command;
7206 char **argv_expanded;
7207 char **argv;
7208 /* it is not always needed, but we aim to smaller code */
7209 int squirrel[] = { -1, -1, -1 };
7210 int rcode;
7211
7212 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7213 debug_enter();
7214
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007215 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7216 * Result should be 3 lines: q w e, qwe, q w e
7217 */
7218 G.ifs = get_local_var_value("IFS");
7219 if (!G.ifs)
7220 G.ifs = defifs;
7221
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007222 IF_HUSH_JOB(pi->pgrp = -1;)
7223 pi->stopped_cmds = 0;
7224 command = &pi->cmds[0];
7225 argv_expanded = NULL;
7226
7227 if (pi->num_cmds != 1
7228 || pi->followup == PIPE_BG
7229 || command->cmd_type == CMD_SUBSHELL
7230 ) {
7231 goto must_fork;
7232 }
7233
7234 pi->alive_cmds = 1;
7235
7236 debug_printf_exec(": group:%p argv:'%s'\n",
7237 command->group, command->argv ? command->argv[0] : "NONE");
7238
7239 if (command->group) {
7240#if ENABLE_HUSH_FUNCTIONS
7241 if (command->cmd_type == CMD_FUNCDEF) {
7242 /* "executing" func () { list } */
7243 struct function *funcp;
7244
7245 funcp = new_function(command->argv[0]);
7246 /* funcp->name is already set to argv[0] */
7247 funcp->body = command->group;
7248# if !BB_MMU
7249 funcp->body_as_string = command->group_as_string;
7250 command->group_as_string = NULL;
7251# endif
7252 command->group = NULL;
7253 command->argv[0] = NULL;
7254 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7255 funcp->parent_cmd = command;
7256 command->child_func = funcp;
7257
7258 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7259 debug_leave();
7260 return EXIT_SUCCESS;
7261 }
7262#endif
7263 /* { list } */
7264 debug_printf("non-subshell group\n");
7265 rcode = 1; /* exitcode if redir failed */
7266 if (setup_redirects(command, squirrel) == 0) {
7267 debug_printf_exec(": run_list\n");
7268 rcode = run_list(command->group) & 0xff;
7269 }
7270 restore_redirects(squirrel);
7271 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7272 debug_leave();
7273 debug_printf_exec("run_pipe: return %d\n", rcode);
7274 return rcode;
7275 }
7276
7277 argv = command->argv ? command->argv : (char **) &null_ptr;
7278 {
7279 const struct built_in_command *x;
7280#if ENABLE_HUSH_FUNCTIONS
7281 const struct function *funcp;
7282#else
7283 enum { funcp = 0 };
7284#endif
7285 char **new_env = NULL;
7286 struct variable *old_vars = NULL;
7287
7288 if (argv[command->assignment_cnt] == NULL) {
7289 /* Assignments, but no command */
7290 /* Ensure redirects take effect (that is, create files).
7291 * Try "a=t >file" */
7292#if 0 /* A few cases in testsuite fail with this code. FIXME */
7293 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7294 /* Set shell variables */
7295 if (new_env) {
7296 argv = new_env;
7297 while (*argv) {
7298 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7299 /* Do we need to flag set_local_var() errors?
7300 * "assignment to readonly var" and "putenv error"
7301 */
7302 argv++;
7303 }
7304 }
7305 /* Redirect error sets $? to 1. Otherwise,
7306 * if evaluating assignment value set $?, retain it.
7307 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7308 if (rcode == 0)
7309 rcode = G.last_exitcode;
7310 /* Exit, _skipping_ variable restoring code: */
7311 goto clean_up_and_ret0;
7312
7313#else /* Older, bigger, but more correct code */
7314
7315 rcode = setup_redirects(command, squirrel);
7316 restore_redirects(squirrel);
7317 /* Set shell variables */
7318 if (G_x_mode)
7319 bb_putchar_stderr('+');
7320 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007321 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007322 if (G_x_mode)
7323 fprintf(stderr, " %s", p);
7324 debug_printf_exec("set shell var:'%s'->'%s'\n",
7325 *argv, p);
7326 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7327 /* Do we need to flag set_local_var() errors?
7328 * "assignment to readonly var" and "putenv error"
7329 */
7330 argv++;
7331 }
7332 if (G_x_mode)
7333 bb_putchar_stderr('\n');
7334 /* Redirect error sets $? to 1. Otherwise,
7335 * if evaluating assignment value set $?, retain it.
7336 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7337 if (rcode == 0)
7338 rcode = G.last_exitcode;
7339 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7340 debug_leave();
7341 debug_printf_exec("run_pipe: return %d\n", rcode);
7342 return rcode;
7343#endif
7344 }
7345
7346 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007347#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007348 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007349 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007350 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007351#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007352 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007353 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7354 }
7355
7356 /* if someone gives us an empty string: `cmd with empty output` */
7357 if (!argv_expanded[0]) {
7358 free(argv_expanded);
7359 debug_leave();
7360 return G.last_exitcode;
7361 }
7362
7363 x = find_builtin(argv_expanded[0]);
7364#if ENABLE_HUSH_FUNCTIONS
7365 funcp = NULL;
7366 if (!x)
7367 funcp = find_function(argv_expanded[0]);
7368#endif
7369 if (x || funcp) {
7370 if (!funcp) {
7371 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7372 debug_printf("exec with redirects only\n");
7373 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007374 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007375 goto clean_up_and_ret1;
7376 }
7377 }
7378 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7379 if (rcode == 0) {
7380 if (!funcp) {
7381 debug_printf_exec(": builtin '%s' '%s'...\n",
7382 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007383 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007384 rcode = x->b_function(argv_expanded) & 0xff;
7385 fflush_all();
7386 }
7387#if ENABLE_HUSH_FUNCTIONS
7388 else {
7389# if ENABLE_HUSH_LOCAL
7390 struct variable **sv;
7391 sv = G.shadowed_vars_pp;
7392 G.shadowed_vars_pp = &old_vars;
7393# endif
7394 debug_printf_exec(": function '%s' '%s'...\n",
7395 funcp->name, argv_expanded[1]);
7396 rcode = run_function(funcp, argv_expanded) & 0xff;
7397# if ENABLE_HUSH_LOCAL
7398 G.shadowed_vars_pp = sv;
7399# endif
7400 }
7401#endif
7402 }
7403 clean_up_and_ret:
7404 unset_vars(new_env);
7405 add_vars(old_vars);
7406/* clean_up_and_ret0: */
7407 restore_redirects(squirrel);
7408 clean_up_and_ret1:
7409 free(argv_expanded);
7410 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7411 debug_leave();
7412 debug_printf_exec("run_pipe return %d\n", rcode);
7413 return rcode;
7414 }
7415
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007416 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007417 int n = find_applet_by_name(argv_expanded[0]);
7418 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7419 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7420 if (rcode == 0) {
7421 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7422 argv_expanded[0], argv_expanded[1]);
7423 rcode = run_nofork_applet(n, argv_expanded);
7424 }
7425 goto clean_up_and_ret;
7426 }
7427 }
7428 /* It is neither builtin nor applet. We must fork. */
7429 }
7430
7431 must_fork:
7432 /* NB: argv_expanded may already be created, and that
7433 * might include `cmd` runs! Do not rerun it! We *must*
7434 * use argv_expanded if it's non-NULL */
7435
7436 /* Going to fork a child per each pipe member */
7437 pi->alive_cmds = 0;
7438 next_infd = 0;
7439
7440 cmd_no = 0;
7441 while (cmd_no < pi->num_cmds) {
7442 struct fd_pair pipefds;
7443#if !BB_MMU
7444 volatile nommu_save_t nommu_save;
7445 nommu_save.new_env = NULL;
7446 nommu_save.old_vars = NULL;
7447 nommu_save.argv = NULL;
7448 nommu_save.argv_from_re_execing = NULL;
7449#endif
7450 command = &pi->cmds[cmd_no];
7451 cmd_no++;
7452 if (command->argv) {
7453 debug_printf_exec(": pipe member '%s' '%s'...\n",
7454 command->argv[0], command->argv[1]);
7455 } else {
7456 debug_printf_exec(": pipe member with no argv\n");
7457 }
7458
7459 /* pipes are inserted between pairs of commands */
7460 pipefds.rd = 0;
7461 pipefds.wr = 1;
7462 if (cmd_no < pi->num_cmds)
7463 xpiped_pair(pipefds);
7464
7465 command->pid = BB_MMU ? fork() : vfork();
7466 if (!command->pid) { /* child */
7467#if ENABLE_HUSH_JOB
7468 disable_restore_tty_pgrp_on_exit();
7469 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7470
7471 /* Every child adds itself to new process group
7472 * with pgid == pid_of_first_child_in_pipe */
7473 if (G.run_list_level == 1 && G_interactive_fd) {
7474 pid_t pgrp;
7475 pgrp = pi->pgrp;
7476 if (pgrp < 0) /* true for 1st process only */
7477 pgrp = getpid();
7478 if (setpgid(0, pgrp) == 0
7479 && pi->followup != PIPE_BG
7480 && G_saved_tty_pgrp /* we have ctty */
7481 ) {
7482 /* We do it in *every* child, not just first,
7483 * to avoid races */
7484 tcsetpgrp(G_interactive_fd, pgrp);
7485 }
7486 }
7487#endif
7488 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7489 /* 1st cmd in backgrounded pipe
7490 * should have its stdin /dev/null'ed */
7491 close(0);
7492 if (open(bb_dev_null, O_RDONLY))
7493 xopen("/", O_RDONLY);
7494 } else {
7495 xmove_fd(next_infd, 0);
7496 }
7497 xmove_fd(pipefds.wr, 1);
7498 if (pipefds.rd > 1)
7499 close(pipefds.rd);
7500 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02007501 * and the pipe fd (fd#1) is available for dup'ing:
7502 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7503 * of cmd1 goes into pipe.
7504 */
7505 if (setup_redirects(command, NULL)) {
7506 /* Happens when redir file can't be opened:
7507 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7508 * FOO
7509 * hush: can't open '/qwe/rty': No such file or directory
7510 * BAZ
7511 * (echo BAR is not executed, it hits _exit(1) below)
7512 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007513 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007514 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007515
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007516 /* Stores to nommu_save list of env vars putenv'ed
7517 * (NOMMU, on MMU we don't need that) */
7518 /* cast away volatility... */
7519 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7520 /* pseudo_exec() does not return */
7521 }
7522
7523 /* parent or error */
7524#if ENABLE_HUSH_FAST
7525 G.count_SIGCHLD++;
7526//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7527#endif
7528 enable_restore_tty_pgrp_on_exit();
7529#if !BB_MMU
7530 /* Clean up after vforked child */
7531 free(nommu_save.argv);
7532 free(nommu_save.argv_from_re_execing);
7533 unset_vars(nommu_save.new_env);
7534 add_vars(nommu_save.old_vars);
7535#endif
7536 free(argv_expanded);
7537 argv_expanded = NULL;
7538 if (command->pid < 0) { /* [v]fork failed */
7539 /* Clearly indicate, was it fork or vfork */
7540 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7541 } else {
7542 pi->alive_cmds++;
7543#if ENABLE_HUSH_JOB
7544 /* Second and next children need to know pid of first one */
7545 if (pi->pgrp < 0)
7546 pi->pgrp = command->pid;
7547#endif
7548 }
7549
7550 if (cmd_no > 1)
7551 close(next_infd);
7552 if (cmd_no < pi->num_cmds)
7553 close(pipefds.wr);
7554 /* Pass read (output) pipe end to next iteration */
7555 next_infd = pipefds.rd;
7556 }
7557
7558 if (!pi->alive_cmds) {
7559 debug_leave();
7560 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7561 return 1;
7562 }
7563
7564 debug_leave();
7565 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7566 return -1;
7567}
7568
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007569/* NB: called by pseudo_exec, and therefore must not modify any
7570 * global data until exec/_exit (we can be a child after vfork!) */
7571static int run_list(struct pipe *pi)
7572{
7573#if ENABLE_HUSH_CASE
7574 char *case_word = NULL;
7575#endif
7576#if ENABLE_HUSH_LOOPS
7577 struct pipe *loop_top = NULL;
7578 char **for_lcur = NULL;
7579 char **for_list = NULL;
7580#endif
7581 smallint last_followup;
7582 smalluint rcode;
7583#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7584 smalluint cond_code = 0;
7585#else
7586 enum { cond_code = 0 };
7587#endif
7588#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007589 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007590 smallint last_rword; /* ditto */
7591#endif
7592
7593 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7594 debug_enter();
7595
7596#if ENABLE_HUSH_LOOPS
7597 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007598 {
7599 struct pipe *cpipe;
7600 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7601 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7602 continue;
7603 /* current word is FOR or IN (BOLD in comments below) */
7604 if (cpipe->next == NULL) {
7605 syntax_error("malformed for");
7606 debug_leave();
7607 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7608 return 1;
7609 }
7610 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7611 if (cpipe->next->res_word == RES_DO)
7612 continue;
7613 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7614 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7615 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7616 ) {
7617 syntax_error("malformed for");
7618 debug_leave();
7619 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7620 return 1;
7621 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007622 }
7623 }
7624#endif
7625
7626 /* Past this point, all code paths should jump to ret: label
7627 * in order to return, no direct "return" statements please.
7628 * This helps to ensure that no memory is leaked. */
7629
7630#if ENABLE_HUSH_JOB
7631 G.run_list_level++;
7632#endif
7633
7634#if HAS_KEYWORDS
7635 rword = RES_NONE;
7636 last_rword = RES_XXXX;
7637#endif
7638 last_followup = PIPE_SEQ;
7639 rcode = G.last_exitcode;
7640
7641 /* Go through list of pipes, (maybe) executing them. */
7642 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7643 if (G.flag_SIGINT)
7644 break;
7645
7646 IF_HAS_KEYWORDS(rword = pi->res_word;)
7647 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7648 rword, cond_code, last_rword);
7649#if ENABLE_HUSH_LOOPS
7650 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7651 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7652 ) {
7653 /* start of a loop: remember where loop starts */
7654 loop_top = pi;
7655 G.depth_of_loop++;
7656 }
7657#endif
7658 /* Still in the same "if...", "then..." or "do..." branch? */
7659 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7660 if ((rcode == 0 && last_followup == PIPE_OR)
7661 || (rcode != 0 && last_followup == PIPE_AND)
7662 ) {
7663 /* It is "<true> || CMD" or "<false> && CMD"
7664 * and we should not execute CMD */
7665 debug_printf_exec("skipped cmd because of || or &&\n");
7666 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02007667 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007668 }
7669 }
7670 last_followup = pi->followup;
7671 IF_HAS_KEYWORDS(last_rword = rword;)
7672#if ENABLE_HUSH_IF
7673 if (cond_code) {
7674 if (rword == RES_THEN) {
7675 /* if false; then ... fi has exitcode 0! */
7676 G.last_exitcode = rcode = EXIT_SUCCESS;
7677 /* "if <false> THEN cmd": skip cmd */
7678 continue;
7679 }
7680 } else {
7681 if (rword == RES_ELSE || rword == RES_ELIF) {
7682 /* "if <true> then ... ELSE/ELIF cmd":
7683 * skip cmd and all following ones */
7684 break;
7685 }
7686 }
7687#endif
7688#if ENABLE_HUSH_LOOPS
7689 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7690 if (!for_lcur) {
7691 /* first loop through for */
7692
7693 static const char encoded_dollar_at[] ALIGN1 = {
7694 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7695 }; /* encoded representation of "$@" */
7696 static const char *const encoded_dollar_at_argv[] = {
7697 encoded_dollar_at, NULL
7698 }; /* argv list with one element: "$@" */
7699 char **vals;
7700
7701 vals = (char**)encoded_dollar_at_argv;
7702 if (pi->next->res_word == RES_IN) {
7703 /* if no variable values after "in" we skip "for" */
7704 if (!pi->next->cmds[0].argv) {
7705 G.last_exitcode = rcode = EXIT_SUCCESS;
7706 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7707 break;
7708 }
7709 vals = pi->next->cmds[0].argv;
7710 } /* else: "for var; do..." -> assume "$@" list */
7711 /* create list of variable values */
7712 debug_print_strings("for_list made from", vals);
7713 for_list = expand_strvec_to_strvec(vals);
7714 for_lcur = for_list;
7715 debug_print_strings("for_list", for_list);
7716 }
7717 if (!*for_lcur) {
7718 /* "for" loop is over, clean up */
7719 free(for_list);
7720 for_list = NULL;
7721 for_lcur = NULL;
7722 break;
7723 }
7724 /* Insert next value from for_lcur */
7725 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7726 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7727 continue;
7728 }
7729 if (rword == RES_IN) {
7730 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7731 }
7732 if (rword == RES_DONE) {
7733 continue; /* "done" has no cmds too */
7734 }
7735#endif
7736#if ENABLE_HUSH_CASE
7737 if (rword == RES_CASE) {
7738 case_word = expand_strvec_to_string(pi->cmds->argv);
7739 continue;
7740 }
7741 if (rword == RES_MATCH) {
7742 char **argv;
7743
7744 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7745 break;
7746 /* all prev words didn't match, does this one match? */
7747 argv = pi->cmds->argv;
7748 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007749 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007750 /* TODO: which FNM_xxx flags to use? */
7751 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7752 free(pattern);
7753 if (cond_code == 0) { /* match! we will execute this branch */
7754 free(case_word); /* make future "word)" stop */
7755 case_word = NULL;
7756 break;
7757 }
7758 argv++;
7759 }
7760 continue;
7761 }
7762 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7763 if (cond_code != 0)
7764 continue; /* not matched yet, skip this pipe */
7765 }
7766#endif
7767 /* Just pressing <enter> in shell should check for jobs.
7768 * OTOH, in non-interactive shell this is useless
7769 * and only leads to extra job checks */
7770 if (pi->num_cmds == 0) {
7771 if (G_interactive_fd)
7772 goto check_jobs_and_continue;
7773 continue;
7774 }
7775
7776 /* After analyzing all keywords and conditions, we decided
7777 * to execute this pipe. NB: have to do checkjobs(NULL)
7778 * after run_pipe to collect any background children,
7779 * even if list execution is to be stopped. */
7780 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7781 {
7782 int r;
7783#if ENABLE_HUSH_LOOPS
7784 G.flag_break_continue = 0;
7785#endif
7786 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7787 if (r != -1) {
7788 /* We ran a builtin, function, or group.
7789 * rcode is already known
7790 * and we don't need to wait for anything. */
7791 G.last_exitcode = rcode;
7792 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007793 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007794#if ENABLE_HUSH_LOOPS
7795 /* Was it "break" or "continue"? */
7796 if (G.flag_break_continue) {
7797 smallint fbc = G.flag_break_continue;
7798 /* We might fall into outer *loop*,
7799 * don't want to break it too */
7800 if (loop_top) {
7801 G.depth_break_continue--;
7802 if (G.depth_break_continue == 0)
7803 G.flag_break_continue = 0;
7804 /* else: e.g. "continue 2" should *break* once, *then* continue */
7805 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denys Vlasenko3beab832013-04-07 18:16:58 +02007806 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7807 checkjobs(NULL);
7808 break;
7809 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007810 /* "continue": simulate end of loop */
7811 rword = RES_DONE;
7812 continue;
7813 }
7814#endif
7815#if ENABLE_HUSH_FUNCTIONS
7816 if (G.flag_return_in_progress == 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007817 checkjobs(NULL);
7818 break;
7819 }
7820#endif
7821 } else if (pi->followup == PIPE_BG) {
7822 /* What does bash do with attempts to background builtins? */
7823 /* even bash 3.2 doesn't do that well with nested bg:
7824 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7825 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007826 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007827#if ENABLE_HUSH_JOB
7828 if (G.run_list_level == 1)
7829 insert_bg_job(pi);
7830#endif
7831 /* Last command's pid goes to $! */
7832 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7833 G.last_exitcode = rcode = EXIT_SUCCESS;
7834 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7835 } else {
7836#if ENABLE_HUSH_JOB
7837 if (G.run_list_level == 1 && G_interactive_fd) {
7838 /* Waits for completion, then fg's main shell */
7839 rcode = checkjobs_and_fg_shell(pi);
7840 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007841 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007842 } else
7843#endif
7844 { /* This one just waits for completion */
7845 rcode = checkjobs(pi);
7846 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007847 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007848 }
7849 G.last_exitcode = rcode;
7850 }
7851 }
7852
7853 /* Analyze how result affects subsequent commands */
7854#if ENABLE_HUSH_IF
7855 if (rword == RES_IF || rword == RES_ELIF)
7856 cond_code = rcode;
7857#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02007858 check_jobs_and_continue:
7859 checkjobs(NULL);
7860 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007861#if ENABLE_HUSH_LOOPS
7862 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007863 if (pi->next
7864 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02007865 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007866 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007867 if (rword == RES_WHILE) {
7868 if (rcode) {
7869 /* "while false; do...done" - exitcode 0 */
7870 G.last_exitcode = rcode = EXIT_SUCCESS;
7871 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02007872 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007873 }
7874 }
7875 if (rword == RES_UNTIL) {
7876 if (!rcode) {
7877 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007878 break;
7879 }
7880 }
7881 }
7882#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007883 } /* for (pi) */
7884
7885#if ENABLE_HUSH_JOB
7886 G.run_list_level--;
7887#endif
7888#if ENABLE_HUSH_LOOPS
7889 if (loop_top)
7890 G.depth_of_loop--;
7891 free(for_list);
7892#endif
7893#if ENABLE_HUSH_CASE
7894 free(case_word);
7895#endif
7896 debug_leave();
7897 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7898 return rcode;
7899}
7900
7901/* Select which version we will use */
7902static int run_and_free_list(struct pipe *pi)
7903{
7904 int rcode = 0;
7905 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007906 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007907 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7908 rcode = run_list(pi);
7909 }
7910 /* free_pipe_list has the side effect of clearing memory.
7911 * In the long run that function can be merged with run_list,
7912 * but doing that now would hobble the debugging effort. */
7913 free_pipe_list(pi);
7914 debug_printf_exec("run_and_free_list return %d\n", rcode);
7915 return rcode;
7916}
7917
7918
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007919static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007920{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007921 sighandler_t old_handler;
7922 unsigned sig = 0;
7923 while ((mask >>= 1) != 0) {
7924 sig++;
7925 if (!(mask & 1))
7926 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007927 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007928 /* POSIX allows shell to re-enable SIGCHLD
7929 * even if it was SIG_IGN on entry.
7930 * Therefore we skip IGN check for it:
7931 */
7932 if (sig == SIGCHLD)
7933 continue;
7934 if (old_handler == SIG_IGN) {
7935 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007936 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007937 if (!G.traps)
7938 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7939 free(G.traps[sig]);
7940 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7941 }
7942 }
7943}
7944
7945/* Called a few times only (or even once if "sh -c") */
7946static void install_special_sighandlers(void)
7947{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007948 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007949
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007950 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007951 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007952 if (G_interactive_fd) {
7953 mask |= SPECIAL_INTERACTIVE_SIGS;
7954 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007955 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007956 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007957 /* Careful, do not re-install handlers we already installed */
7958 if (G.special_sig_mask != mask) {
7959 unsigned diff = mask & ~G.special_sig_mask;
7960 G.special_sig_mask = mask;
7961 install_sighandlers(diff);
7962 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007963}
7964
7965#if ENABLE_HUSH_JOB
7966/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007967/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007968static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007969{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007970 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007971
7972 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007973 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007974 + (1 << SIGILL ) * HUSH_DEBUG
7975 + (1 << SIGFPE ) * HUSH_DEBUG
7976 + (1 << SIGBUS ) * HUSH_DEBUG
7977 + (1 << SIGSEGV) * HUSH_DEBUG
7978 + (1 << SIGTRAP) * HUSH_DEBUG
7979 + (1 << SIGABRT)
7980 /* bash 3.2 seems to handle these just like 'fatal' ones */
7981 + (1 << SIGPIPE)
7982 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007983 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007984 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007985 * we never want to restore pgrp on exit, and this fn is not called
7986 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007987 /*+ (1 << SIGHUP )*/
7988 /*+ (1 << SIGTERM)*/
7989 /*+ (1 << SIGINT )*/
7990 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007991 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007992
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007993 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007994}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007995#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007996
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007997static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007998{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007999 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008000 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008001 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08008002 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008003 break;
8004 case 'x':
8005 IF_HUSH_MODE_X(G_x_mode = state;)
8006 break;
8007 case 'o':
8008 if (!o_opt) {
8009 /* "set -+o" without parameter.
8010 * in bash, set -o produces this output:
8011 * pipefail off
8012 * and set +o:
8013 * set +o pipefail
8014 * We always use the second form.
8015 */
8016 const char *p = o_opt_strings;
8017 idx = 0;
8018 while (*p) {
8019 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8020 idx++;
8021 p += strlen(p) + 1;
8022 }
8023 break;
8024 }
8025 idx = index_in_strings(o_opt_strings, o_opt);
8026 if (idx >= 0) {
8027 G.o_opt[idx] = state;
8028 break;
8029 }
8030 default:
8031 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008032 }
8033 return EXIT_SUCCESS;
8034}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008035
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00008036int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00008037int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00008038{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008039 enum {
8040 OPT_login = (1 << 0),
8041 };
8042 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00008043 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008044 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008045 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008046 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008047 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00008048
Denis Vlasenko574f2f42008-02-27 18:41:59 +00008049 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02008050 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008051 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008052
Denys Vlasenko10c01312011-05-11 11:49:21 +02008053#if ENABLE_HUSH_FAST
8054 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8055#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008056#if !BB_MMU
8057 G.argv0_for_re_execing = argv[0];
8058#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008059 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008060 shell_ver = xzalloc(sizeof(*shell_ver));
8061 shell_ver->flg_export = 1;
8062 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02008063 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02008064 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008065 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02008066 /* Create shell local variables from the values
8067 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00008068 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008069 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008070 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008071 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008072 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008073 if (e) while (*e) {
8074 char *value = strchr(*e, '=');
8075 if (value) { /* paranoia */
8076 cur_var->next = xzalloc(sizeof(*cur_var));
8077 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00008078 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008079 cur_var->max_len = strlen(*e);
8080 cur_var->flg_export = 1;
8081 }
8082 e++;
8083 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02008084 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008085 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8086 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02008087
8088 /* Export PWD */
8089 set_pwd_var(/*exp:*/ 1);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008090
8091#if ENABLE_HUSH_BASH_COMPAT
8092 /* Set (but not export) HOSTNAME unless already set */
8093 if (!get_local_var_value("HOSTNAME")) {
8094 struct utsname uts;
8095 uname(&uts);
8096 set_local_var_from_halves("HOSTNAME", uts.nodename);
8097 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008098 /* bash also exports SHLVL and _,
8099 * and sets (but doesn't export) the following variables:
8100 * BASH=/bin/bash
8101 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8102 * BASH_VERSION='3.2.0(1)-release'
8103 * HOSTTYPE=i386
8104 * MACHTYPE=i386-pc-linux-gnu
8105 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02008106 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02008107 * EUID=<NNNNN>
8108 * UID=<NNNNN>
8109 * GROUPS=()
8110 * LINES=<NNN>
8111 * COLUMNS=<NNN>
8112 * BASH_ARGC=()
8113 * BASH_ARGV=()
8114 * BASH_LINENO=()
8115 * BASH_SOURCE=()
8116 * DIRSTACK=()
8117 * PIPESTATUS=([0]="0")
8118 * HISTFILE=/<xxx>/.bash_history
8119 * HISTFILESIZE=500
8120 * HISTSIZE=500
8121 * MAILCHECK=60
8122 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8123 * SHELL=/bin/bash
8124 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8125 * TERM=dumb
8126 * OPTERR=1
8127 * OPTIND=1
8128 * IFS=$' \t\n'
8129 * PS1='\s-\v\$ '
8130 * PS2='> '
8131 * PS4='+ '
8132 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008133#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02008134
Denis Vlasenko38f63192007-01-22 09:03:07 +00008135#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02008136 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008137#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02008138
Eric Andersen94ac2442001-05-22 19:05:18 +00008139 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00008140 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00008141
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008142 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00008143
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008144 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008145 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008146 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008147 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008148 * in order to intercept (more) signals.
8149 */
8150
8151 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008152 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008153 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008154 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008155 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008156 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008157#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00008158 "<:$:R:V:"
8159# if ENABLE_HUSH_FUNCTIONS
8160 "F:"
8161# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008162#endif
8163 );
8164 if (opt <= 0)
8165 break;
Eric Andersen25f27032001-04-26 23:22:31 +00008166 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008167 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008168 /* Possibilities:
8169 * sh ... -c 'script'
8170 * sh ... -c 'script' ARG0 [ARG1...]
8171 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01008172 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008173 * "" needs to be replaced with NULL
8174 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01008175 * Note: the form without ARG0 never happens:
8176 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008177 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02008178 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008179 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008180 G.root_ppid = getppid();
8181 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008182 G.global_argv = argv + optind;
8183 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008184 if (builtin_argc) {
8185 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8186 const struct built_in_command *x;
8187
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008188 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008189 x = find_builtin(optarg);
8190 if (x) { /* paranoia */
8191 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8192 G.global_argv += builtin_argc;
8193 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008194 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01008195 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008196 }
8197 goto final_return;
8198 }
8199 if (!G.global_argv[0]) {
8200 /* -c 'script' (no params): prevent empty $0 */
8201 G.global_argv--; /* points to argv[i] of 'script' */
8202 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02008203 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008204 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008205 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008206 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008207 goto final_return;
8208 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00008209 /* Well, we cannot just declare interactiveness,
8210 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008211 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008212 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008213 case 's':
8214 /* "-s" means "read from stdin", but this is how we always
8215 * operate, so simply do nothing here. */
8216 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008217 case 'l':
8218 flags |= OPT_login;
8219 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008220#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008221 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02008222 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008223 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008224 case '$': {
8225 unsigned long long empty_trap_mask;
8226
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008227 G.root_pid = bb_strtou(optarg, &optarg, 16);
8228 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02008229 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8230 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008231 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8232 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008233 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008234 optarg++;
8235 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008236 optarg++;
8237 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8238 if (empty_trap_mask != 0) {
8239 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008240 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008241 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8242 for (sig = 1; sig < NSIG; sig++) {
8243 if (empty_trap_mask & (1LL << sig)) {
8244 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008245 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008246 }
8247 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008248 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008249# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008250 optarg++;
8251 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008252# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008253 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008254 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008255 case 'R':
8256 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02008257 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008258 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00008259# if ENABLE_HUSH_FUNCTIONS
8260 case 'F': {
8261 struct function *funcp = new_function(optarg);
8262 /* funcp->name is already set to optarg */
8263 /* funcp->body is set to NULL. It's a special case. */
8264 funcp->body_as_string = argv[optind];
8265 optind++;
8266 break;
8267 }
8268# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008269#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008270 case 'n':
8271 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008272 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008273 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008274 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008275#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008276 fprintf(stderr, "Usage: sh [FILE]...\n"
8277 " or: sh -c command [args]...\n\n");
8278 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008279#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008280 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008281#endif
Eric Andersen25f27032001-04-26 23:22:31 +00008282 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008283 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008284
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008285 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8286 G.global_argc = argc - (optind - 1);
8287 G.global_argv = argv + (optind - 1);
8288 G.global_argv[0] = argv[0];
8289
Denys Vlasenkodea47882009-10-09 15:40:49 +02008290 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008291 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008292 G.root_ppid = getppid();
8293 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008294
8295 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008296 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008297 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008298 debug_printf("sourcing /etc/profile\n");
8299 input = fopen_for_read("/etc/profile");
8300 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008301 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008302 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008303 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008304 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008305 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008306 /* bash: after sourcing /etc/profile,
8307 * tries to source (in the given order):
8308 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008309 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008310 * bash also sources ~/.bash_logout on exit.
8311 * If called as sh, skips .bash_XXX files.
8312 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008313 }
8314
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008315 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008316 FILE *input;
8317 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008318 * "bash <script>" (which is never interactive (unless -i?))
8319 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008320 * If called as sh, does the same but with $ENV.
8321 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008322 G.global_argc--;
8323 G.global_argv++;
8324 debug_printf("running script '%s'\n", G.global_argv[0]);
8325 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008326 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008327 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008328 parse_and_run_file(input);
8329#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008330 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008331#endif
8332 goto final_return;
8333 }
8334
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008335 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008336 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008337 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008338
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008339 /* A shell is interactive if the '-i' flag was given,
8340 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008341 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008342 * no arguments remaining or the -s flag given
8343 * standard input is a terminal
8344 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008345 * Refer to Posix.2, the description of the 'sh' utility.
8346 */
8347#if ENABLE_HUSH_JOB
8348 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008349 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8350 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8351 if (G_saved_tty_pgrp < 0)
8352 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008353
8354 /* try to dup stdin to high fd#, >= 255 */
8355 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8356 if (G_interactive_fd < 0) {
8357 /* try to dup to any fd */
8358 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008359 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008360 /* give up */
8361 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008362 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008363 }
8364 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008365// TODO: track & disallow any attempts of user
8366// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008367 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008368 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008369 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008370 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008371
Mike Frysinger38478a62009-05-20 04:48:06 -04008372 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008373 /* If we were run as 'hush &', sleep until we are
8374 * in the foreground (tty pgrp == our pgrp).
8375 * If we get started under a job aware app (like bash),
8376 * make sure we are now in charge so we don't fight over
8377 * who gets the foreground */
8378 while (1) {
8379 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008380 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8381 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008382 break;
8383 /* send TTIN to ourself (should stop us) */
8384 kill(- shell_pgrp, SIGTTIN);
8385 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008386 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008387
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008388 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008389 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008390
Mike Frysinger38478a62009-05-20 04:48:06 -04008391 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008392 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008393 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008394 /* Put ourselves in our own process group
8395 * (bash, too, does this only if ctty is available) */
8396 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8397 /* Grab control of the terminal */
8398 tcsetpgrp(G_interactive_fd, getpid());
8399 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02008400 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008401
8402# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8403 {
8404 const char *hp = get_local_var_value("HISTFILE");
8405 if (!hp) {
8406 hp = get_local_var_value("HOME");
8407 if (hp)
8408 hp = concat_path_file(hp, ".hush_history");
8409 } else {
8410 hp = xstrdup(hp);
8411 }
8412 if (hp) {
8413 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008414 //set_local_var(xasprintf("HISTFILE=%s", ...));
8415 }
8416# if ENABLE_FEATURE_SH_HISTFILESIZE
8417 hp = get_local_var_value("HISTFILESIZE");
8418 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8419# endif
8420 }
8421# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008422 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008423 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008424 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008425#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008426 /* No job control compiled in, only prompt/line editing */
8427 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008428 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8429 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008430 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008431 G_interactive_fd = dup(STDIN_FILENO);
8432 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008433 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008434 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008435 }
8436 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008437 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008438 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008439 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008440 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008441#else
8442 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008443 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008444#endif
8445 /* bash:
8446 * if interactive but not a login shell, sources ~/.bashrc
8447 * (--norc turns this off, --rcfile <file> overrides)
8448 */
8449
8450 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008451 /* note: ash and hush share this string */
8452 printf("\n\n%s %s\n"
8453 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8454 "\n",
8455 bb_banner,
8456 "hush - the humble shell"
8457 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008458 }
8459
Denis Vlasenkof9375282009-04-05 19:13:39 +00008460 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008461
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008462 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008463 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008464}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008465
8466
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008467#if ENABLE_MSH
8468int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8469int msh_main(int argc, char **argv)
8470{
8471 //bb_error_msg("msh is deprecated, please use hush instead");
8472 return hush_main(argc, argv);
8473}
8474#endif
8475
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008476
8477/*
8478 * Built-ins
8479 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008480static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008481{
8482 return 0;
8483}
8484
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008485static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008486{
8487 int argc = 0;
8488 while (*argv) {
8489 argc++;
8490 argv++;
8491 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008492 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008493}
8494
8495static int FAST_FUNC builtin_test(char **argv)
8496{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008497 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008498}
8499
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008500static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008501{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008502 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008503}
8504
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008505#if ENABLE_PRINTF
8506static int FAST_FUNC builtin_printf(char **argv)
8507{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008508 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008509}
8510#endif
8511
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008512static char **skip_dash_dash(char **argv)
8513{
8514 argv++;
8515 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8516 argv++;
8517 return argv;
8518}
8519
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008520static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008521{
8522 int rcode = EXIT_SUCCESS;
8523
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008524 argv = skip_dash_dash(argv);
8525 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008526 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008527 /* bash:
8528 * eval "echo Hi; done" ("done" is syntax error):
8529 * "echo Hi" will not execute too.
8530 */
8531 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008532 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008533 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008534 }
8535 return rcode;
8536}
8537
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008538static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008539{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008540 const char *newdir;
8541
8542 argv = skip_dash_dash(argv);
8543 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008544 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008545 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008546 * bash says "bash: cd: HOME not set" and does nothing
8547 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008548 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008549 const char *home = get_local_var_value("HOME");
8550 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008551 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008552 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008553 /* Mimic bash message exactly */
8554 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008555 return EXIT_FAILURE;
8556 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008557 /* Read current dir (get_cwd(1) is inside) and set PWD.
8558 * Note: do not enforce exporting. If PWD was unset or unexported,
8559 * set it again, but do not export. bash does the same.
8560 */
8561 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008562 return EXIT_SUCCESS;
8563}
8564
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008565static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008566{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008567 argv = skip_dash_dash(argv);
8568 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008569 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008570
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008571 /* Careful: we can end up here after [v]fork. Do not restore
8572 * tty pgrp then, only top-level shell process does that */
8573 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8574 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8575
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008576 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008577 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008578 * and tcsetpgrp, and this is inherently racy.
8579 */
8580 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008581}
8582
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008583static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008584{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008585 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008586
8587 /* interactive bash:
8588 * # trap "echo EEE" EXIT
8589 * # exit
8590 * exit
8591 * There are stopped jobs.
8592 * (if there are _stopped_ jobs, running ones don't count)
8593 * # exit
8594 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01008595 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00008596 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008597 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008598 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008599
8600 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008601 argv = skip_dash_dash(argv);
8602 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008603 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008604 /* mimic bash: exit 123abc == exit 255 + error msg */
8605 xfunc_error_retval = 255;
8606 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008607 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008608}
8609
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008610static void print_escaped(const char *s)
8611{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008612 if (*s == '\'')
8613 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008614 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008615 const char *p = strchrnul(s, '\'');
8616 /* print 'xxxx', possibly just '' */
8617 printf("'%.*s'", (int)(p - s), s);
8618 if (*p == '\0')
8619 break;
8620 s = p;
8621 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008622 /* s points to '; print "'''...'''" */
8623 putchar('"');
8624 do putchar('\''); while (*++s == '\'');
8625 putchar('"');
8626 } while (*s);
8627}
8628
Denys Vlasenko295fef82009-06-03 12:47:26 +02008629#if !ENABLE_HUSH_LOCAL
8630#define helper_export_local(argv, exp, lvl) \
8631 helper_export_local(argv, exp)
8632#endif
8633static void helper_export_local(char **argv, int exp, int lvl)
8634{
8635 do {
8636 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008637 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008638
8639 /* So far we do not check that name is valid (TODO?) */
8640
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008641 if (*name_end == '\0') {
8642 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008643
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008644 vpp = get_ptr_to_local_var(name, name_end - name);
8645 var = vpp ? *vpp : NULL;
8646
Denys Vlasenko295fef82009-06-03 12:47:26 +02008647 if (exp == -1) { /* unexporting? */
8648 /* export -n NAME (without =VALUE) */
8649 if (var) {
8650 var->flg_export = 0;
8651 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8652 unsetenv(name);
8653 } /* else: export -n NOT_EXISTING_VAR: no-op */
8654 continue;
8655 }
8656 if (exp == 1) { /* exporting? */
8657 /* export NAME (without =VALUE) */
8658 if (var) {
8659 var->flg_export = 1;
8660 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8661 putenv(var->varstr);
8662 continue;
8663 }
8664 }
8665 /* Exporting non-existing variable.
8666 * bash does not put it in environment,
8667 * but remembers that it is exported,
8668 * and does put it in env when it is set later.
8669 * We just set it to "" and export. */
8670 /* Or, it's "local NAME" (without =VALUE).
8671 * bash sets the value to "". */
8672 name = xasprintf("%s=", name);
8673 } else {
8674 /* (Un)exporting/making local NAME=VALUE */
8675 name = xstrdup(name);
8676 }
8677 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8678 } while (*++argv);
8679}
8680
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008681static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008682{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008683 unsigned opt_unexport;
8684
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008685#if ENABLE_HUSH_EXPORT_N
8686 /* "!": do not abort on errors */
8687 opt_unexport = getopt32(argv, "!n");
8688 if (opt_unexport == (uint32_t)-1)
8689 return EXIT_FAILURE;
8690 argv += optind;
8691#else
8692 opt_unexport = 0;
8693 argv++;
8694#endif
8695
8696 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008697 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008698 if (e) {
8699 while (*e) {
8700#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008701 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008702#else
8703 /* ash emits: export VAR='VAL'
8704 * bash: declare -x VAR="VAL"
8705 * we follow ash example */
8706 const char *s = *e++;
8707 const char *p = strchr(s, '=');
8708
8709 if (!p) /* wtf? take next variable */
8710 continue;
8711 /* export var= */
8712 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008713 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008714 putchar('\n');
8715#endif
8716 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008717 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008718 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008719 return EXIT_SUCCESS;
8720 }
8721
Denys Vlasenko295fef82009-06-03 12:47:26 +02008722 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008723
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008724 return EXIT_SUCCESS;
8725}
8726
Denys Vlasenko295fef82009-06-03 12:47:26 +02008727#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008728static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008729{
8730 if (G.func_nest_level == 0) {
8731 bb_error_msg("%s: not in a function", argv[0]);
8732 return EXIT_FAILURE; /* bash compat */
8733 }
8734 helper_export_local(argv, 0, G.func_nest_level);
8735 return EXIT_SUCCESS;
8736}
8737#endif
8738
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008739static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008740{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008741 int sig;
8742 char *new_cmd;
8743
8744 if (!G.traps)
8745 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8746
8747 argv++;
8748 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008749 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008750 /* No args: print all trapped */
8751 for (i = 0; i < NSIG; ++i) {
8752 if (G.traps[i]) {
8753 printf("trap -- ");
8754 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008755 /* note: bash adds "SIG", but only if invoked
8756 * as "bash". If called as "sh", or if set -o posix,
8757 * then it prints short signal names.
8758 * We are printing short names: */
8759 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008760 }
8761 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008762 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008763 return EXIT_SUCCESS;
8764 }
8765
8766 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008767 /* If first arg is a number: reset all specified signals */
8768 sig = bb_strtou(*argv, NULL, 10);
8769 if (errno == 0) {
8770 int ret;
8771 process_sig_list:
8772 ret = EXIT_SUCCESS;
8773 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008774 sighandler_t handler;
8775
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008776 sig = get_signum(*argv++);
8777 if (sig < 0 || sig >= NSIG) {
8778 ret = EXIT_FAILURE;
8779 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008780 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008781 continue;
8782 }
8783
8784 free(G.traps[sig]);
8785 G.traps[sig] = xstrdup(new_cmd);
8786
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008787 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008788 get_signame(sig), sig, G.traps[sig]);
8789
8790 /* There is no signal for 0 (EXIT) */
8791 if (sig == 0)
8792 continue;
8793
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008794 if (new_cmd)
8795 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8796 else
8797 /* We are removing trap handler */
8798 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02008799 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008800 }
8801 return ret;
8802 }
8803
8804 if (!argv[1]) { /* no second arg */
8805 bb_error_msg("trap: invalid arguments");
8806 return EXIT_FAILURE;
8807 }
8808
8809 /* First arg is "-": reset all specified to default */
8810 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8811 /* Everything else: set arg as signal handler
8812 * (includes "" case, which ignores signal) */
8813 if (argv[0][0] == '-') {
8814 if (argv[0][1] == '\0') { /* "-" */
8815 /* new_cmd remains NULL: "reset these sigs" */
8816 goto reset_traps;
8817 }
8818 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8819 argv++;
8820 }
8821 /* else: "-something", no special meaning */
8822 }
8823 new_cmd = *argv;
8824 reset_traps:
8825 argv++;
8826 goto process_sig_list;
8827}
8828
Mike Frysinger93cadc22009-05-27 17:06:25 -04008829/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008830static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008831{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008832 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008833
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008834 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008835 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008836 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008837
8838 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008839 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008840 type = "an alias";*/
8841#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008842 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008843 type = "a function";
8844#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008845 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008846 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008847 else if ((path = find_in_path(*argv)) != NULL)
8848 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008849 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008850 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008851 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008852 continue;
8853 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008854
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008855 printf("%s is %s\n", *argv, type);
8856 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008857 }
8858
8859 return ret;
8860}
8861
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008862#if ENABLE_HUSH_JOB
8863/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008864static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008865{
8866 int i, jobnum;
8867 struct pipe *pi;
8868
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008869 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008870 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008871
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008872 /* If they gave us no args, assume they want the last backgrounded task */
8873 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008874 for (pi = G.job_list; pi; pi = pi->next) {
8875 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008876 goto found;
8877 }
8878 }
8879 bb_error_msg("%s: no current job", argv[0]);
8880 return EXIT_FAILURE;
8881 }
8882 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8883 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8884 return EXIT_FAILURE;
8885 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008886 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008887 if (pi->jobid == jobnum) {
8888 goto found;
8889 }
8890 }
8891 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8892 return EXIT_FAILURE;
8893 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008894 /* TODO: bash prints a string representation
8895 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008896 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008897 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008898 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008899 }
8900
8901 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008902 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8903 for (i = 0; i < pi->num_cmds; i++) {
8904 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008905 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008906 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008907
8908 i = kill(- pi->pgrp, SIGCONT);
8909 if (i < 0) {
8910 if (errno == ESRCH) {
8911 delete_finished_bg_job(pi);
8912 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008913 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008914 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008915 }
8916
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008917 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008918 remove_bg_job(pi);
8919 return checkjobs_and_fg_shell(pi);
8920 }
8921 return EXIT_SUCCESS;
8922}
8923#endif
8924
8925#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008926static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008927{
8928 const struct built_in_command *x;
8929
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008930 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008931 "Built-in commands:\n"
8932 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008933 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008934 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008935 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008936 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008937 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008938 return EXIT_SUCCESS;
8939}
8940#endif
8941
Denys Vlasenkoff463a82013-05-12 02:45:23 +02008942#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02008943static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
8944{
8945 show_history(G.line_input_state);
8946 return EXIT_SUCCESS;
8947}
8948#endif
8949
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008950#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008951static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008952{
8953 struct pipe *job;
8954 const char *status_string;
8955
Denis Vlasenko87a86552008-07-29 19:43:10 +00008956 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008957 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008958 status_string = "Stopped";
8959 else
8960 status_string = "Running";
8961
8962 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8963 }
8964 return EXIT_SUCCESS;
8965}
8966#endif
8967
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008968#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008969static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008970{
8971 void *p;
8972 unsigned long l;
8973
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008974# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008975 /* Optional. Reduces probability of false positives */
8976 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008977# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008978 /* Crude attempt to find where "free memory" starts,
8979 * sans fragmentation. */
8980 p = malloc(240);
8981 l = (unsigned long)p;
8982 free(p);
8983 p = malloc(3400);
8984 if (l < (unsigned long)p) l = (unsigned long)p;
8985 free(p);
8986
8987 if (!G.memleak_value)
8988 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008989
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008990 l -= G.memleak_value;
8991 if ((long)l < 0)
8992 l = 0;
8993 l /= 1024;
8994 if (l > 127)
8995 l = 127;
8996
8997 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8998 return l;
8999}
9000#endif
9001
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009002static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009003{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009004 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009005 return EXIT_SUCCESS;
9006}
9007
Denys Vlasenko80542ba2011-05-08 21:23:43 +02009008/* Interruptibility of read builtin in bash
9009 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9010 *
9011 * Empty trap makes read ignore corresponding signal, for any signal.
9012 *
9013 * SIGINT:
9014 * - terminates non-interactive shell;
9015 * - interrupts read in interactive shell;
9016 * if it has non-empty trap:
9017 * - executes trap and returns to command prompt in interactive shell;
9018 * - executes trap and returns to read in non-interactive shell;
9019 * SIGTERM:
9020 * - is ignored (does not interrupt) read in interactive shell;
9021 * - terminates non-interactive shell;
9022 * if it has non-empty trap:
9023 * - executes trap and returns to read;
9024 * SIGHUP:
9025 * - terminates shell (regardless of interactivity);
9026 * if it has non-empty trap:
9027 * - executes trap and returns to read;
9028 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009029static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009030{
Denys Vlasenko03dad222010-01-12 23:29:57 +01009031 const char *r;
9032 char *opt_n = NULL;
9033 char *opt_p = NULL;
9034 char *opt_t = NULL;
9035 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02009036 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01009037 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00009038
Denys Vlasenko03dad222010-01-12 23:29:57 +01009039 /* "!": do not abort on errors.
9040 * Option string must start with "sr" to match BUILTIN_READ_xxx
9041 */
9042 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9043 if (read_flags == (uint32_t)-1)
9044 return EXIT_FAILURE;
9045 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02009046 ifs = get_local_var_value("IFS"); /* can be NULL */
9047
9048 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01009049 r = shell_builtin_read(set_local_var_from_halves,
9050 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02009051 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01009052 read_flags,
9053 opt_n,
9054 opt_p,
9055 opt_t,
9056 opt_u
9057 );
9058
Denys Vlasenko80542ba2011-05-08 21:23:43 +02009059 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009060 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02009061 if (sig && sig != SIGINT)
9062 goto again;
9063 }
9064
Denys Vlasenko03dad222010-01-12 23:29:57 +01009065 if ((uintptr_t)r > 1) {
9066 bb_error_msg("%s", r);
9067 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00009068 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009069
Denys Vlasenko03dad222010-01-12 23:29:57 +01009070 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009071}
9072
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009073/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9074 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009075 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009076 * set [-abCefhmnuvx] [-o option] [argument...]
9077 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009078 * set -- [argument...]
9079 * set -o
9080 * set +o
9081 * Implementations shall support the options in both their hyphen and
9082 * plus-sign forms. These options can also be specified as options to sh.
9083 * Examples:
9084 * Write out all variables and their values: set
9085 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9086 * Turn on the -x and -v options: set -xv
9087 * Unset all positional parameters: set --
9088 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9089 * Set the positional parameters to the expansion of x, even if x expands
9090 * with a leading '-' or '+': set -- $x
9091 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009092 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009093 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009094static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009095{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009096 int n;
9097 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009098 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009099
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009100 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009101 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009102 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009103 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009104 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009105 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009106
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009107 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009108 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009109 ++argv;
9110 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009111 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00009112 if (arg[0] != '+' && arg[0] != '-')
9113 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009114 for (n = 1; arg[n]; ++n) {
9115 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00009116 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009117 if (arg[n] == 'o' && argv[1])
9118 argv++;
9119 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009120 } while ((arg = *++argv) != NULL);
9121 /* Now argv[0] is 1st argument */
9122
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009123 if (arg == NULL)
9124 return EXIT_SUCCESS;
9125 set_argv:
9126
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009127 /* NB: G.global_argv[0] ($0) is never freed/changed */
9128 g_argv = G.global_argv;
9129 if (G.global_args_malloced) {
9130 pp = g_argv;
9131 while (*++pp)
9132 free(*pp);
9133 g_argv[1] = NULL;
9134 } else {
9135 G.global_args_malloced = 1;
9136 pp = xzalloc(sizeof(pp[0]) * 2);
9137 pp[0] = g_argv[0]; /* retain $0 */
9138 g_argv = pp;
9139 }
9140 /* This realloc's G.global_argv */
9141 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9142
9143 n = 1;
9144 while (*++pp)
9145 n++;
9146 G.global_argc = n;
9147
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009148 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009149
9150 /* Nothing known, so abort */
9151 error:
9152 bb_error_msg("set: %s: invalid option", arg);
9153 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009154}
9155
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009156static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009157{
9158 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009159 argv = skip_dash_dash(argv);
9160 if (argv[0]) {
9161 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009162 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009163 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00009164 if (G.global_args_malloced) {
9165 int m = 1;
9166 while (m <= n)
9167 free(G.global_argv[m++]);
9168 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009169 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00009170 memmove(&G.global_argv[1], &G.global_argv[n+1],
9171 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009172 return EXIT_SUCCESS;
9173 }
9174 return EXIT_FAILURE;
9175}
9176
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009177static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009178{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009179 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009180 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009181 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009182#if ENABLE_HUSH_FUNCTIONS
9183 smallint sv_flg;
9184#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009185
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009186 argv = skip_dash_dash(argv);
9187 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009188 if (!filename) {
9189 /* bash says: "bash: .: filename argument required" */
9190 return 2; /* bash compat */
9191 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009192 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009193 if (!strchr(filename, '/')) {
9194 arg_path = find_in_path(filename);
9195 if (arg_path)
9196 filename = arg_path;
9197 }
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009198 input = remember_FILE(fopen_or_warn(filename, "r"));
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009199 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009200 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009201 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009202 /* POSIX: non-interactive shell should abort here,
9203 * not merely fail. So far no one complained :)
9204 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009205 return EXIT_FAILURE;
9206 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009207
Mike Frysinger885b6f22009-04-18 21:04:25 +00009208#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009209 sv_flg = G.flag_return_in_progress;
9210 /* "we are inside sourced file, ok to use return" */
9211 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009212#endif
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009213 if (argv[1])
9214 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009215
Denys Vlasenko992e0ff2016-09-29 01:27:09 +02009216 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9217 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009218 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009219 fclose_and_forget(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009220
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009221 if (argv[1])
9222 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00009223#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009224 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009225#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009226
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009227 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009228}
9229
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009230static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009231{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009232 int rc;
9233 mode_t mask;
9234
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009235 rc = 1;
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009236 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009237 argv = skip_dash_dash(argv);
9238 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009239 mode_t old_mask = mask;
9240
Denys Vlasenko6283f982015-10-07 16:56:20 +02009241 /* numeric umasks are taken as-is */
9242 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9243 if (!isdigit(argv[0][0]))
9244 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009245 mask = bb_parse_mode(argv[0], mask);
Denys Vlasenko6283f982015-10-07 16:56:20 +02009246 if (!isdigit(argv[0][0]))
9247 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009248 if ((unsigned)mask > 0777) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009249 mask = old_mask;
9250 /* bash messages:
9251 * bash: umask: 'q': invalid symbolic mode operator
9252 * bash: umask: 999: octal number out of range
9253 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02009254 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009255 rc = 0;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009256 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009257 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009258 /* Mimic bash */
9259 printf("%04o\n", (unsigned) mask);
9260 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009261 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009262 umask(mask);
9263
9264 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009265}
9266
Mike Frysingerd690f682009-03-30 06:50:54 +00009267/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009268static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009269{
Mike Frysingerd690f682009-03-30 06:50:54 +00009270 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00009271 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00009272
Denis Vlasenko28e67962009-04-26 23:22:40 +00009273 /* "!": do not abort on errors */
9274 /* "+": stop at 1st non-option */
9275 opts = getopt32(argv, "!+vf");
9276 if (opts == (unsigned)-1)
9277 return EXIT_FAILURE;
9278 if (opts == 3) {
9279 bb_error_msg("unset: -v and -f are exclusive");
9280 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00009281 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00009282 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00009283
9284 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009285 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00009286 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009287 if (unset_local_var(*argv)) {
9288 /* unset <nonexistent_var> doesn't fail.
9289 * Error is when one tries to unset RO var.
9290 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00009291 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009292 }
Mike Frysingerd690f682009-03-30 06:50:54 +00009293 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00009294#if ENABLE_HUSH_FUNCTIONS
9295 else {
9296 unset_func(*argv);
9297 }
9298#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009299 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00009300 }
9301 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009302}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009303
Mike Frysinger56bdea12009-03-28 20:01:58 +00009304/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009305static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00009306{
9307 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009308 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009309
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009310 argv = skip_dash_dash(argv);
9311 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009312 /* Don't care about wait results */
9313 /* Note 1: must wait until there are no more children */
9314 /* Note 2: must be interruptible */
9315 /* Examples:
9316 * $ sleep 3 & sleep 6 & wait
9317 * [1] 30934 sleep 3
9318 * [2] 30935 sleep 6
9319 * [1] Done sleep 3
9320 * [2] Done sleep 6
9321 * $ sleep 3 & sleep 6 & wait
9322 * [1] 30936 sleep 3
9323 * [2] 30937 sleep 6
9324 * [1] Done sleep 3
9325 * ^C <-- after ~4 sec from keyboard
9326 * $
9327 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009328 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009329 int sig;
9330 sigset_t oldset, allsigs;
9331
9332 /* waitpid is not interruptible by SA_RESTARTed
9333 * signals which we use. Thus, this ugly dance:
9334 */
9335
9336 /* Make sure possible SIGCHLD is stored in kernel's
9337 * pending signal mask before we call waitpid.
9338 * Or else we may race with SIGCHLD, lose it,
9339 * and get stuck in sigwaitinfo...
9340 */
9341 sigfillset(&allsigs);
9342 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9343
9344 if (!sigisemptyset(&G.pending_set)) {
9345 /* Crap! we raced with some signal! */
9346 // sig = 0;
9347 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009348 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009349
9350 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9351 if (errno == ECHILD) {
9352 sigprocmask(SIG_SETMASK, &oldset, NULL);
9353 break;
9354 }
9355
9356 /* Wait for SIGCHLD or any other signal */
9357 //sig = sigwaitinfo(&allsigs, NULL);
9358 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9359 /* Note: sigsuspend invokes signal handler */
9360 sigsuspend(&oldset);
9361 restore:
9362 sigprocmask(SIG_SETMASK, &oldset, NULL);
9363
9364 /* So, did we get a signal? */
9365 //if (sig > 0)
9366 // raise(sig); /* run handler */
9367 sig = check_and_run_traps();
9368 if (sig /*&& sig != SIGCHLD - always true */) {
9369 /* see note 2 */
9370 ret = 128 + sig;
9371 break;
9372 }
9373 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009374 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009375 return ret;
9376 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009377
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009378 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009379 while (*argv) {
9380 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00009381 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009382 /* mimic bash message */
9383 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009384 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009385 }
9386 if (waitpid(pid, &status, 0) == pid) {
Denys Vlasenko85378cd2015-10-11 21:47:11 +02009387 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009388 if (WIFSIGNALED(status))
9389 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009390 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009391 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009392 ret = 127;
9393 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00009394 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009395 }
9396
9397 return ret;
9398}
9399
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009400#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9401static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9402{
9403 if (argv[1]) {
9404 def = bb_strtou(argv[1], NULL, 10);
9405 if (errno || def < def_min || argv[2]) {
9406 bb_error_msg("%s: bad arguments", argv[0]);
9407 def = UINT_MAX;
9408 }
9409 }
9410 return def;
9411}
9412#endif
9413
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009414#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009415static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009416{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009417 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009418 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009419 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +02009420 /* if we came from builtin_continue(), need to undo "= 1" */
9421 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009422 return EXIT_SUCCESS; /* bash compat */
9423 }
Denys Vlasenko49117b42016-07-21 14:40:08 +02009424 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009425
9426 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9427 if (depth == UINT_MAX)
9428 G.flag_break_continue = BC_BREAK;
9429 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009430 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009431
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009432 return EXIT_SUCCESS;
9433}
9434
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009435static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009436{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009437 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9438 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009439}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009440#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009441
9442#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009443static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009444{
9445 int rc;
9446
9447 if (G.flag_return_in_progress != -1) {
9448 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9449 return EXIT_FAILURE; /* bash compat */
9450 }
9451
9452 G.flag_return_in_progress = 1;
9453
9454 /* bash:
9455 * out of range: wraps around at 256, does not error out
9456 * non-numeric param:
9457 * f() { false; return qwe; }; f; echo $?
9458 * bash: return: qwe: numeric argument required <== we do this
9459 * 255 <== we also do this
9460 */
9461 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9462 return rc;
9463}
9464#endif