blob: a8ec54ec06b17e8841c93c576b852948ccf8e14d [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;
465 /* eof_flag=1: last char in ->p is really an EOF */
466 char eof_flag; /* meaningless if ->p == NULL */
467 char peek_buf[2];
468#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000469 smallint promptmode; /* 0: PS1, 1: PS2 */
470#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200471 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000472 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200473 int (*get) (struct in_str *) FAST_FUNC;
474 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000475} in_str;
476#define i_getch(input) ((input)->get(input))
477#define i_peek(input) ((input)->peek(input))
478
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
2125
2126/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002127 * in_str support
2128 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002129static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002130{
Denys Vlasenko8391c482010-05-22 17:50:43 +02002131 int ch = *i->p;
2132 if (ch != '\0') {
2133 i->p++;
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002134 i->last_char = ch;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002135 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002136 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002137 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002138}
2139
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002140static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002141{
2142 return *i->p;
2143}
2144
2145#if ENABLE_HUSH_INTERACTIVE
2146
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002147static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002148{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002149 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002150 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002151 if (G.PS1 == NULL)
2152 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002153 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002154 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002155 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002156 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002157 if (G.PS2 == NULL)
2158 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002159}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002160
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002161static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002162{
2163 const char *prompt_str;
2164 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002165 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2166 /* Set up the prompt */
2167 if (promptmode == 0) { /* PS1 */
2168 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002169 /* bash uses $PWD value, even if it is set by user.
2170 * It uses current dir only if PWD is unset.
2171 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002172 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002173 prompt_str = G.PS1;
2174 } else
2175 prompt_str = G.PS2;
2176 } else
2177 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002178 debug_printf("result '%s'\n", prompt_str);
2179 return prompt_str;
2180}
2181
2182static void get_user_input(struct in_str *i)
2183{
2184 int r;
2185 const char *prompt_str;
2186
2187 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002188# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002189 /* Enable command line editing only while a command line
2190 * is actually being read */
2191 do {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002192 reinit_unicode_for_hush();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002193 G.flag_SIGINT = 0;
2194 /* buglet: SIGINT will not make new prompt to appear _at once_,
2195 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002196 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 +00002197 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002198 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002199 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002200 i->eof_flag = (r < 0);
2201 if (i->eof_flag) { /* EOF/error detected */
2202 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2203 G.user_input_buf[1] = '\0';
2204 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02002205# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002206 do {
2207 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002208 if (i->last_char == '\0' || i->last_char == '\n') {
2209 /* Why check_and_run_traps here? Try this interactively:
2210 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2211 * $ <[enter], repeatedly...>
2212 * Without check_and_run_traps, handler never runs.
2213 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002214 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002215 fputs(prompt_str, stdout);
2216 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002217 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002218 G.user_input_buf[0] = r = fgetc(i->file);
2219 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002220 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002221 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002222# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002223 i->p = G.user_input_buf;
2224}
2225
2226#endif /* INTERACTIVE */
2227
2228/* This is the magic location that prints prompts
2229 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002230static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002231{
2232 int ch;
2233
2234 /* If there is data waiting, eat it up */
2235 if (i->p && *i->p) {
2236#if ENABLE_HUSH_INTERACTIVE
2237 take_cached:
2238#endif
2239 ch = *i->p++;
2240 if (i->eof_flag && !*i->p)
2241 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002242 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002243 } else {
2244 /* need to double check i->file because we might be doing something
2245 * more complicated by now, like sourcing or substituting. */
2246#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002247 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002248 do {
2249 get_user_input(i);
2250 } while (!*i->p); /* need non-empty line */
2251 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002252 goto take_cached;
2253 }
2254#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00002255 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002256 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002257 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002258 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002259 return ch;
2260}
2261
Denis Vlasenko913a2012009-04-05 22:17:04 +00002262/* All callers guarantee this routine will never
2263 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002264 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002265static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002266{
2267 int ch;
2268 if (i->p && *i->p) {
2269 if (i->eof_flag && !i->p[1])
2270 return EOF;
2271 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002272 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002273 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002274 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002275 i->eof_flag = (ch == EOF);
2276 i->peek_buf[0] = ch;
2277 i->peek_buf[1] = '\0';
2278 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002279 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002280 return ch;
2281}
2282
2283static void setup_file_in_str(struct in_str *i, FILE *f)
2284{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002285 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002286 i->peek = file_peek;
2287 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002288 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002289 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002290 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002291}
2292
2293static void setup_string_in_str(struct in_str *i, const char *s)
2294{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002295 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002296 i->peek = static_peek;
2297 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002298 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002299 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002300 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002301}
2302
2303
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002304/*
2305 * o_string support
2306 */
2307#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002308
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002309static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002310{
2311 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002312 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002313 if (o->data)
2314 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002315}
2316
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002317static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002318{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002319 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002320 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002321}
2322
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002323static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2324{
2325 free(o->data);
2326}
2327
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002328static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002329{
2330 if (o->length + len > o->maxlen) {
2331 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2332 o->data = xrealloc(o->data, 1 + o->maxlen);
2333 }
2334}
2335
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002336static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002337{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002338 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2339 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002340 o->data[o->length] = ch;
2341 o->length++;
2342 o->data[o->length] = '\0';
2343}
2344
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002345static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002346{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002347 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002348 memcpy(&o->data[o->length], str, len);
2349 o->length += len;
2350 o->data[o->length] = '\0';
2351}
2352
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002353static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002354{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002355 o_addblock(o, str, strlen(str));
2356}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002357
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002358#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002359static void nommu_addchr(o_string *o, int ch)
2360{
2361 if (o)
2362 o_addchr(o, ch);
2363}
2364#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002365# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002366#endif
2367
2368static void o_addstr_with_NUL(o_string *o, const char *str)
2369{
2370 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002371}
2372
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002373/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002374 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002375 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2376 * Apparently, on unquoted $v bash still does globbing
2377 * ("v='*.txt'; echo $v" prints all .txt files),
2378 * but NOT brace expansion! Thus, there should be TWO independent
2379 * quoting mechanisms on $v expansion side: one protects
2380 * $v from brace expansion, and other additionally protects "$v" against globbing.
2381 * We have only second one.
2382 */
2383
Denys Vlasenko9e800222010-10-03 14:28:04 +02002384#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002385# define MAYBE_BRACES "{}"
2386#else
2387# define MAYBE_BRACES ""
2388#endif
2389
Eric Andersen25f27032001-04-26 23:22:31 +00002390/* My analysis of quoting semantics tells me that state information
2391 * is associated with a destination, not a source.
2392 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002393static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002394{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002395 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002396 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002397 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002398 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002399 o_grow_by(o, sz);
2400 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002401 o->data[o->length] = '\\';
2402 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002403 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002404 o->data[o->length] = ch;
2405 o->length++;
2406 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002407}
2408
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002409static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002410{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002411 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002412 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2413 && strchr("*?[\\" MAYBE_BRACES, ch)
2414 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002415 sz++;
2416 o->data[o->length] = '\\';
2417 o->length++;
2418 }
2419 o_grow_by(o, sz);
2420 o->data[o->length] = ch;
2421 o->length++;
2422 o->data[o->length] = '\0';
2423}
2424
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002425static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002426{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002427 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002428 char ch;
2429 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002430 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002431 if (ordinary_cnt > len) /* paranoia */
2432 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002433 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002434 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002435 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002436 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002437 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002438
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002439 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002440 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002441 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002442 sz++;
2443 o->data[o->length] = '\\';
2444 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002445 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002446 o_grow_by(o, sz);
2447 o->data[o->length] = ch;
2448 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002449 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002450 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002451}
2452
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002453static void o_addQblock(o_string *o, const char *str, int len)
2454{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002455 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002456 o_addblock(o, str, len);
2457 return;
2458 }
2459 o_addqblock(o, str, len);
2460}
2461
Denys Vlasenko38292b62010-09-05 14:49:40 +02002462static void o_addQstr(o_string *o, const char *str)
2463{
2464 o_addQblock(o, str, strlen(str));
2465}
2466
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002467/* A special kind of o_string for $VAR and `cmd` expansion.
2468 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002469 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002470 * list[i] contains an INDEX (int!) into this string data.
2471 * It means that if list[] needs to grow, data needs to be moved higher up
2472 * but list[i]'s need not be modified.
2473 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002474 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002475 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2476 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002477#if DEBUG_EXPAND || DEBUG_GLOB
2478static void debug_print_list(const char *prefix, o_string *o, int n)
2479{
2480 char **list = (char**)o->data;
2481 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2482 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002483
2484 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002485 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 +02002486 prefix, list, n, string_start, o->length, o->maxlen,
2487 !!(o->o_expflags & EXP_FLAG_GLOB),
2488 o->has_quoted_part,
2489 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002490 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002491 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002492 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2493 o->data + (int)(uintptr_t)list[i] + string_start,
2494 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002495 i++;
2496 }
2497 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002498 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002499 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002500 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002501 }
2502}
2503#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002504# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002505#endif
2506
2507/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2508 * in list[n] so that it points past last stored byte so far.
2509 * It returns n+1. */
2510static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002511{
2512 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002513 int string_start;
2514 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002515
2516 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002517 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2518 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002519 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002520 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002521 /* list[n] points to string_start, make space for 16 more pointers */
2522 o->maxlen += 0x10 * sizeof(list[0]);
2523 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002524 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002525 memmove(list + n + 0x10, list + n, string_len);
2526 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002527 } else {
2528 debug_printf_list("list[%d]=%d string_start=%d\n",
2529 n, string_len, string_start);
2530 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002531 } else {
2532 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002533 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2534 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002535 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2536 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002537 o->has_empty_slot = 0;
2538 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002539 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002540 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002541 return n + 1;
2542}
2543
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002544/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002545static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002546{
2547 char **list = (char**)o->data;
2548 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2549
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002550 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002551}
2552
Denys Vlasenko9e800222010-10-03 14:28:04 +02002553#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002554/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2555 * first, it processes even {a} (no commas), second,
2556 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002557 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002558 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002559
2560/* Helper */
2561static int glob_needed(const char *s)
2562{
2563 while (*s) {
2564 if (*s == '\\') {
2565 if (!s[1])
2566 return 0;
2567 s += 2;
2568 continue;
2569 }
2570 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2571 return 1;
2572 s++;
2573 }
2574 return 0;
2575}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002576/* Return pointer to next closing brace or to comma */
2577static const char *next_brace_sub(const char *cp)
2578{
2579 unsigned depth = 0;
2580 cp++;
2581 while (*cp != '\0') {
2582 if (*cp == '\\') {
2583 if (*++cp == '\0')
2584 break;
2585 cp++;
2586 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002587 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002588 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002589 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002590 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002591 depth++;
2592 }
2593
2594 return *cp != '\0' ? cp : NULL;
2595}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002596/* Recursive brace globber. Note: may garble pattern[]. */
2597static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002598{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002599 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002600 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002601 const char *next;
2602 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002603 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002604 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002605
2606 debug_printf_glob("glob_brace('%s')\n", pattern);
2607
2608 begin = pattern;
2609 while (1) {
2610 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002611 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002612 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002613 /* Find the first sub-pattern and at the same time
2614 * find the rest after the closing brace */
2615 next = next_brace_sub(begin);
2616 if (next == NULL) {
2617 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002618 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002619 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002620 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002621 /* "{abc}" with no commas - illegal
2622 * brace expr, disregard and skip it */
2623 begin = next + 1;
2624 continue;
2625 }
2626 break;
2627 }
2628 if (*begin == '\\' && begin[1] != '\0')
2629 begin++;
2630 begin++;
2631 }
2632 debug_printf_glob("begin:%s\n", begin);
2633 debug_printf_glob("next:%s\n", next);
2634
2635 /* Now find the end of the whole brace expression */
2636 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002637 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002638 rest = next_brace_sub(rest);
2639 if (rest == NULL) {
2640 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002641 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002642 }
2643 debug_printf_glob("rest:%s\n", rest);
2644 }
2645 rest_len = strlen(++rest) + 1;
2646
2647 /* We are sure the brace expression is well-formed */
2648
2649 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002650 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002651
2652 /* We have a brace expression. BEGIN points to the opening {,
2653 * NEXT points past the terminator of the first element, and REST
2654 * points past the final }. We will accumulate result names from
2655 * recursive runs for each brace alternative in the buffer using
2656 * GLOB_APPEND. */
2657
2658 p = begin + 1;
2659 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002660 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002661 memcpy(
2662 mempcpy(
2663 mempcpy(new_pattern_buf,
2664 /* We know the prefix for all sub-patterns */
2665 pattern, begin - pattern),
2666 p, next - p),
2667 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002668
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002669 /* Note: glob_brace() may garble new_pattern_buf[].
2670 * That's why we re-copy prefix every time (1st memcpy above).
2671 */
2672 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002673 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002674 /* We saw the last entry */
2675 break;
2676 }
2677 p = next + 1;
2678 next = next_brace_sub(next);
2679 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002680 free(new_pattern_buf);
2681 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002682
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002683 simple_glob:
2684 {
2685 int gr;
2686 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002687
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002688 memset(&globdata, 0, sizeof(globdata));
2689 gr = glob(pattern, 0, NULL, &globdata);
2690 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2691 if (gr != 0) {
2692 if (gr == GLOB_NOMATCH) {
2693 globfree(&globdata);
2694 /* NB: garbles parameter */
2695 unbackslash(pattern);
2696 o_addstr_with_NUL(o, pattern);
2697 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2698 return o_save_ptr_helper(o, n);
2699 }
2700 if (gr == GLOB_NOSPACE)
2701 bb_error_msg_and_die(bb_msg_memory_exhausted);
2702 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2703 * but we didn't specify it. Paranoia again. */
2704 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2705 }
2706 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2707 char **argv = globdata.gl_pathv;
2708 while (1) {
2709 o_addstr_with_NUL(o, *argv);
2710 n = o_save_ptr_helper(o, n);
2711 argv++;
2712 if (!*argv)
2713 break;
2714 }
2715 }
2716 globfree(&globdata);
2717 }
2718 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002719}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002720/* Performs globbing on last list[],
2721 * saving each result as a new list[].
2722 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002723static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002724{
2725 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002726
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002727 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002728 if (!o->data)
2729 return o_save_ptr_helper(o, n);
2730 pattern = o->data + o_get_last_ptr(o, n);
2731 debug_printf_glob("glob pattern '%s'\n", pattern);
2732 if (!glob_needed(pattern)) {
2733 /* unbackslash last string in o in place, fix length */
2734 o->length = unbackslash(pattern) - o->data;
2735 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2736 return o_save_ptr_helper(o, n);
2737 }
2738
2739 copy = xstrdup(pattern);
2740 /* "forget" pattern in o */
2741 o->length = pattern - o->data;
2742 n = glob_brace(copy, o, n);
2743 free(copy);
2744 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002745 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002746 return n;
2747}
2748
Denys Vlasenko238081f2010-10-03 14:26:26 +02002749#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002750
2751/* Helper */
2752static int glob_needed(const char *s)
2753{
2754 while (*s) {
2755 if (*s == '\\') {
2756 if (!s[1])
2757 return 0;
2758 s += 2;
2759 continue;
2760 }
2761 if (*s == '*' || *s == '[' || *s == '?')
2762 return 1;
2763 s++;
2764 }
2765 return 0;
2766}
2767/* Performs globbing on last list[],
2768 * saving each result as a new list[].
2769 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002770static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002771{
2772 glob_t globdata;
2773 int gr;
2774 char *pattern;
2775
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002776 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002777 if (!o->data)
2778 return o_save_ptr_helper(o, n);
2779 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002780 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002781 if (!glob_needed(pattern)) {
2782 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002783 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002784 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002785 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002786 return o_save_ptr_helper(o, n);
2787 }
2788
2789 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002790 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2791 * If we glob "*.\*" and don't find anything, we need
2792 * to fall back to using literal "*.*", but GLOB_NOCHECK
2793 * will return "*.\*"!
2794 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002795 gr = glob(pattern, 0, NULL, &globdata);
2796 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002797 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002798 if (gr == GLOB_NOMATCH) {
2799 globfree(&globdata);
2800 goto literal;
2801 }
2802 if (gr == GLOB_NOSPACE)
2803 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002804 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2805 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002806 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002807 }
2808 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2809 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002810 /* "forget" pattern in o */
2811 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002812 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002813 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002814 n = o_save_ptr_helper(o, n);
2815 argv++;
2816 if (!*argv)
2817 break;
2818 }
2819 }
2820 globfree(&globdata);
2821 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002822 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002823 return n;
2824}
2825
Denys Vlasenko238081f2010-10-03 14:26:26 +02002826#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002827
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002828/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002829 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002830static int o_save_ptr(o_string *o, int n)
2831{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002832 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002833 /* If o->has_empty_slot, list[n] was already globbed
2834 * (if it was requested back then when it was filled)
2835 * so don't do that again! */
2836 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002837 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002838 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002839 return o_save_ptr_helper(o, n);
2840}
2841
2842/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002843static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002844{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002845 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002846 int string_start;
2847
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002848 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2849 if (DEBUG_EXPAND)
2850 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002851 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002852 list = (char**)o->data;
2853 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2854 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002855 while (n) {
2856 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002857 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002858 }
2859 return list;
2860}
2861
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002862static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002863
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002864/* Returns pi->next - next pipe in the list */
2865static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002866{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002867 struct pipe *next;
2868 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002869
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002870 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002871 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002872 struct command *command;
2873 struct redir_struct *r, *rnext;
2874
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002875 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002876 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002877 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002878 if (DEBUG_CLEAN) {
2879 int a;
2880 char **p;
2881 for (a = 0, p = command->argv; *p; a++, p++) {
2882 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2883 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002884 }
2885 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002886 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002887 }
2888 /* not "else if": on syntax error, we may have both! */
2889 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002890 debug_printf_clean(" begin group (cmd_type:%d)\n",
2891 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002892 free_pipe_list(command->group);
2893 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002894 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002895 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002896 /* else is crucial here.
2897 * If group != NULL, child_func is meaningless */
2898#if ENABLE_HUSH_FUNCTIONS
2899 else if (command->child_func) {
2900 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2901 command->child_func->parent_cmd = NULL;
2902 }
2903#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002904#if !BB_MMU
2905 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002906 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002907#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002908 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002909 debug_printf_clean(" redirect %d%s",
2910 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002911 /* guard against the case >$FOO, where foo is unset or blank */
2912 if (r->rd_filename) {
2913 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2914 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002915 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002916 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002917 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002918 rnext = r->next;
2919 free(r);
2920 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002921 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002922 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002923 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002924 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002925#if ENABLE_HUSH_JOB
2926 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002927 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002928#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002929
2930 next = pi->next;
2931 free(pi);
2932 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002933}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002934
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002935static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002936{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002937 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002938#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002939 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002940#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002941 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002942 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002943 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002944}
2945
2946
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002947/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002948
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002949#ifndef debug_print_tree
2950static void debug_print_tree(struct pipe *pi, int lvl)
2951{
2952 static const char *const PIPE[] = {
2953 [PIPE_SEQ] = "SEQ",
2954 [PIPE_AND] = "AND",
2955 [PIPE_OR ] = "OR" ,
2956 [PIPE_BG ] = "BG" ,
2957 };
2958 static const char *RES[] = {
2959 [RES_NONE ] = "NONE" ,
2960# if ENABLE_HUSH_IF
2961 [RES_IF ] = "IF" ,
2962 [RES_THEN ] = "THEN" ,
2963 [RES_ELIF ] = "ELIF" ,
2964 [RES_ELSE ] = "ELSE" ,
2965 [RES_FI ] = "FI" ,
2966# endif
2967# if ENABLE_HUSH_LOOPS
2968 [RES_FOR ] = "FOR" ,
2969 [RES_WHILE] = "WHILE",
2970 [RES_UNTIL] = "UNTIL",
2971 [RES_DO ] = "DO" ,
2972 [RES_DONE ] = "DONE" ,
2973# endif
2974# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2975 [RES_IN ] = "IN" ,
2976# endif
2977# if ENABLE_HUSH_CASE
2978 [RES_CASE ] = "CASE" ,
2979 [RES_CASE_IN ] = "CASE_IN" ,
2980 [RES_MATCH] = "MATCH",
2981 [RES_CASE_BODY] = "CASE_BODY",
2982 [RES_ESAC ] = "ESAC" ,
2983# endif
2984 [RES_XXXX ] = "XXXX" ,
2985 [RES_SNTX ] = "SNTX" ,
2986 };
2987 static const char *const CMDTYPE[] = {
2988 "{}",
2989 "()",
2990 "[noglob]",
2991# if ENABLE_HUSH_FUNCTIONS
2992 "func()",
2993# endif
2994 };
2995
2996 int pin, prn;
2997
2998 pin = 0;
2999 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003000 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003001 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3002 prn = 0;
3003 while (prn < pi->num_cmds) {
3004 struct command *command = &pi->cmds[prn];
3005 char **argv = command->argv;
3006
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003007 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003008 lvl*2, "", prn,
3009 command->assignment_cnt);
3010 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003011 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003012 CMDTYPE[command->cmd_type],
3013 argv
3014# if !BB_MMU
3015 , " group_as_string:", command->group_as_string
3016# else
3017 , "", ""
3018# endif
3019 );
3020 debug_print_tree(command->group, lvl+1);
3021 prn++;
3022 continue;
3023 }
3024 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003025 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003026 argv++;
3027 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003028 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003029 prn++;
3030 }
3031 pi = pi->next;
3032 pin++;
3033 }
3034}
3035#endif /* debug_print_tree */
3036
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003037static struct pipe *new_pipe(void)
3038{
Eric Andersen25f27032001-04-26 23:22:31 +00003039 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003040 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003041 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003042 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003043 return pi;
3044}
3045
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003046/* Command (member of a pipe) is complete, or we start a new pipe
3047 * if ctx->command is NULL.
3048 * No errors possible here.
3049 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003050static int done_command(struct parse_context *ctx)
3051{
3052 /* The command is really already in the pipe structure, so
3053 * advance the pipe counter and make a new, null command. */
3054 struct pipe *pi = ctx->pipe;
3055 struct command *command = ctx->command;
3056
3057 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003058 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003059 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003060 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003061 }
3062 pi->num_cmds++;
3063 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003064 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003065 } else {
3066 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3067 }
3068
3069 /* Only real trickiness here is that the uncommitted
3070 * command structure is not counted in pi->num_cmds. */
3071 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003072 ctx->command = command = &pi->cmds[pi->num_cmds];
3073 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003074 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003075 return pi->num_cmds; /* used only for 0/nonzero check */
3076}
3077
3078static void done_pipe(struct parse_context *ctx, pipe_style type)
3079{
3080 int not_null;
3081
3082 debug_printf_parse("done_pipe entered, followup %d\n", type);
3083 /* Close previous command */
3084 not_null = done_command(ctx);
3085 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003086#if HAS_KEYWORDS
3087 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3088 ctx->ctx_inverted = 0;
3089 ctx->pipe->res_word = ctx->ctx_res_w;
3090#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003091
3092 /* Without this check, even just <enter> on command line generates
3093 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003094 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003095 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003096#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003097 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003098#endif
3099#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003100 || ctx->ctx_res_w == RES_DONE
3101 || ctx->ctx_res_w == RES_FOR
3102 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003103#endif
3104#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003105 || ctx->ctx_res_w == RES_ESAC
3106#endif
3107 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003108 struct pipe *new_p;
3109 debug_printf_parse("done_pipe: adding new pipe: "
3110 "not_null:%d ctx->ctx_res_w:%d\n",
3111 not_null, ctx->ctx_res_w);
3112 new_p = new_pipe();
3113 ctx->pipe->next = new_p;
3114 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003115 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003116 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003117 * This is used to control execution.
3118 * RES_FOR and RES_IN are NOT sticky (needed to support
3119 * cases where variable or value happens to match a keyword):
3120 */
3121#if ENABLE_HUSH_LOOPS
3122 if (ctx->ctx_res_w == RES_FOR
3123 || ctx->ctx_res_w == RES_IN)
3124 ctx->ctx_res_w = RES_NONE;
3125#endif
3126#if ENABLE_HUSH_CASE
3127 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003128 ctx->ctx_res_w = RES_CASE_BODY;
3129 if (ctx->ctx_res_w == RES_CASE)
3130 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003131#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003132 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003133 /* Create the memory for command, roughly:
3134 * ctx->pipe->cmds = new struct command;
3135 * ctx->command = &ctx->pipe->cmds[0];
3136 */
3137 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003138 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003139 }
3140 debug_printf_parse("done_pipe return\n");
3141}
3142
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003143static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003144{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003145 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003146 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003147 /* Create the memory for command, roughly:
3148 * ctx->pipe->cmds = new struct command;
3149 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003150 */
3151 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003152}
3153
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003154/* If a reserved word is found and processed, parse context is modified
3155 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003156 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003157#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003158struct reserved_combo {
3159 char literal[6];
3160 unsigned char res;
3161 unsigned char assignment_flag;
3162 int flag;
3163};
3164enum {
3165 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003166# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003167 FLAG_IF = (1 << RES_IF ),
3168 FLAG_THEN = (1 << RES_THEN ),
3169 FLAG_ELIF = (1 << RES_ELIF ),
3170 FLAG_ELSE = (1 << RES_ELSE ),
3171 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003172# endif
3173# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003174 FLAG_FOR = (1 << RES_FOR ),
3175 FLAG_WHILE = (1 << RES_WHILE),
3176 FLAG_UNTIL = (1 << RES_UNTIL),
3177 FLAG_DO = (1 << RES_DO ),
3178 FLAG_DONE = (1 << RES_DONE ),
3179 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003180# endif
3181# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003182 FLAG_MATCH = (1 << RES_MATCH),
3183 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003184# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003185 FLAG_START = (1 << RES_XXXX ),
3186};
3187
3188static const struct reserved_combo* match_reserved_word(o_string *word)
3189{
Eric Andersen25f27032001-04-26 23:22:31 +00003190 /* Mostly a list of accepted follow-up reserved words.
3191 * FLAG_END means we are done with the sequence, and are ready
3192 * to turn the compound list into a command.
3193 * FLAG_START means the word must start a new compound list.
3194 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003195 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003196# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003197 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3198 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3199 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3200 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3201 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3202 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003203# endif
3204# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003205 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3206 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3207 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3208 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3209 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3210 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003211# endif
3212# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003213 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3214 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003215# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003216 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003217 const struct reserved_combo *r;
3218
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003219 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003220 if (strcmp(word->data, r->literal) == 0)
3221 return r;
3222 }
3223 return NULL;
3224}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003225/* Return 0: not a keyword, 1: keyword
3226 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003227static int reserved_word(o_string *word, struct parse_context *ctx)
3228{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003229# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003230 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003231 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003232 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003233# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003234 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003235
Denys Vlasenko38292b62010-09-05 14:49:40 +02003236 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003237 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003238 r = match_reserved_word(word);
3239 if (!r)
3240 return 0;
3241
3242 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003243# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003244 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3245 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003246 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003247 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003248# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003249 if (r->flag == 0) { /* '!' */
3250 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003251 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003252 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003253 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003254 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003255 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003256 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003257 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003258 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003259
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003260 old = xmalloc(sizeof(*old));
3261 debug_printf_parse("push stack %p\n", old);
3262 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003263 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003264 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003265 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003266 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003267 ctx->ctx_res_w = RES_SNTX;
3268 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003269 } else {
3270 /* "{...} fi" is ok. "{...} if" is not
3271 * Example:
3272 * if { echo foo; } then { echo bar; } fi */
3273 if (ctx->command->group)
3274 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003275 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003276
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003277 ctx->ctx_res_w = r->res;
3278 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003279 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003280 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003281
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003282 if (ctx->old_flag & FLAG_END) {
3283 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003284
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003285 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003286 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003287 old = ctx->stack;
3288 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003289 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003290# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003291 /* At this point, the compound command's string is in
3292 * ctx->as_string... except for the leading keyword!
3293 * Consider this example: "echo a | if true; then echo a; fi"
3294 * ctx->as_string will contain "true; then echo a; fi",
3295 * with "if " remaining in old->as_string!
3296 */
3297 {
3298 char *str;
3299 int len = old->as_string.length;
3300 /* Concatenate halves */
3301 o_addstr(&old->as_string, ctx->as_string.data);
3302 o_free_unsafe(&ctx->as_string);
3303 /* Find where leading keyword starts in first half */
3304 str = old->as_string.data + len;
3305 if (str > old->as_string.data)
3306 str--; /* skip whitespace after keyword */
3307 while (str > old->as_string.data && isalpha(str[-1]))
3308 str--;
3309 /* Ugh, we're done with this horrid hack */
3310 old->command->group_as_string = xstrdup(str);
3311 debug_printf_parse("pop, remembering as:'%s'\n",
3312 old->command->group_as_string);
3313 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003314# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003315 *ctx = *old; /* physical copy */
3316 free(old);
3317 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003318 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003319}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003320#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003321
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003322/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003323 * Normal return is 0. Syntax errors return 1.
3324 * Note: on return, word is reset, but not o_free'd!
3325 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003326static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003327{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003328 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003329
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003330 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003331 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003332 debug_printf_parse("done_word return 0: true null, ignored\n");
3333 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003334 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003335
Eric Andersen25f27032001-04-26 23:22:31 +00003336 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003337 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3338 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003339 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3340 * "2.7 Redirection
3341 * ...the word that follows the redirection operator
3342 * shall be subjected to tilde expansion, parameter expansion,
3343 * command substitution, arithmetic expansion, and quote
3344 * removal. Pathname expansion shall not be performed
3345 * on the word by a non-interactive shell; an interactive
3346 * shell may perform it, but shall do so only when
3347 * the expansion would result in one word."
3348 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003349 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003350 /* Cater for >\file case:
3351 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3352 * Same with heredocs:
3353 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3354 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003355 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3356 unbackslash(ctx->pending_redirect->rd_filename);
3357 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003358 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003359 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3360 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003361 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003362 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003363 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003364 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003365#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003366# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003367 if (ctx->ctx_dsemicolon
3368 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3369 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003370 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003371 /* ctx->ctx_res_w = RES_MATCH; */
3372 ctx->ctx_dsemicolon = 0;
3373 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003374# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003375 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003376# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003377 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3378 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003379# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003380# if ENABLE_HUSH_CASE
3381 && ctx->ctx_res_w != RES_CASE
3382# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003383 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003384 int reserved = reserved_word(word, ctx);
3385 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3386 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003387 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003388 debug_printf_parse("done_word return %d\n",
3389 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003390 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003391 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003392# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003393 if (strcmp(word->data, "[[") == 0) {
3394 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3395 }
3396 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003397# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003398 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003399#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003400 if (command->group) {
3401 /* "{ echo foo; } echo bar" - bad */
3402 syntax_error_at(word->data);
3403 debug_printf_parse("done_word return 1: syntax error, "
3404 "groups and arglists don't mix\n");
3405 return 1;
3406 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003407
3408 /* If this word wasn't an assignment, next ones definitely
3409 * can't be assignments. Even if they look like ones. */
3410 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3411 && word->o_assignment != WORD_IS_KEYWORD
3412 ) {
3413 word->o_assignment = NOT_ASSIGNMENT;
3414 } else {
3415 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3416 command->assignment_cnt++;
3417 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3418 }
3419 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3420 word->o_assignment = MAYBE_ASSIGNMENT;
3421 }
3422 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3423
Denys Vlasenko38292b62010-09-05 14:49:40 +02003424 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003425 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3426 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003427 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003428 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003429 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003430 char *p = word->data;
3431 while (p[0] == SPECIAL_VAR_SYMBOL
3432 && (p[1] & 0x7f) == '@'
3433 && p[2] == SPECIAL_VAR_SYMBOL
3434 ) {
3435 p += 3;
3436 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003437 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003438 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003439 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003440 }
Eric Andersen25f27032001-04-26 23:22:31 +00003441
Denis Vlasenko06810332007-05-21 23:30:54 +00003442#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003443 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003444 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003445 || !is_well_formed_var_name(command->argv[0], '\0')
3446 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003447 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003448 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003449 return 1;
3450 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003451 /* Force FOR to have just one word (variable name) */
3452 /* NB: basically, this makes hush see "for v in ..."
3453 * syntax as if it is "for v; in ...". FOR and IN become
3454 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003455 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003456 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003457#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003458#if ENABLE_HUSH_CASE
3459 /* Force CASE to have just one word */
3460 if (ctx->ctx_res_w == RES_CASE) {
3461 done_pipe(ctx, PIPE_SEQ);
3462 }
3463#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003464
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003465 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003466
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003467 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003468 return 0;
3469}
3470
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003471
3472/* Peek ahead in the input to find out if we have a "&n" construct,
3473 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003474 * Return:
3475 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3476 * REDIRFD_SYNTAX_ERR if syntax error,
3477 * REDIRFD_TO_FILE if no & was seen,
3478 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003479 */
3480#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003481#define parse_redir_right_fd(as_string, input) \
3482 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003483#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003484static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003485{
3486 int ch, d, ok;
3487
3488 ch = i_peek(input);
3489 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003490 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003491
3492 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003493 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003494 ch = i_peek(input);
3495 if (ch == '-') {
3496 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003497 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003498 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003499 }
3500 d = 0;
3501 ok = 0;
3502 while (ch != EOF && isdigit(ch)) {
3503 d = d*10 + (ch-'0');
3504 ok = 1;
3505 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003506 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003507 ch = i_peek(input);
3508 }
3509 if (ok) return d;
3510
3511//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3512
3513 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003514 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003515}
3516
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003517/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003518 */
3519static int parse_redirect(struct parse_context *ctx,
3520 int fd,
3521 redir_type style,
3522 struct in_str *input)
3523{
3524 struct command *command = ctx->command;
3525 struct redir_struct *redir;
3526 struct redir_struct **redirp;
3527 int dup_num;
3528
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003529 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003530 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003531 /* Check for a '>&1' type redirect */
3532 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3533 if (dup_num == REDIRFD_SYNTAX_ERR)
3534 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003535 } else {
3536 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003537 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003538 if (dup_num) { /* <<-... */
3539 ch = i_getch(input);
3540 nommu_addchr(&ctx->as_string, ch);
3541 ch = i_peek(input);
3542 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003543 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003544
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003545 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003546 int ch = i_peek(input);
3547 if (ch == '|') {
3548 /* >|FILE redirect ("clobbering" >).
3549 * Since we do not support "set -o noclobber" yet,
3550 * >| and > are the same for now. Just eat |.
3551 */
3552 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003553 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003554 }
3555 }
3556
3557 /* Create a new redir_struct and append it to the linked list */
3558 redirp = &command->redirects;
3559 while ((redir = *redirp) != NULL) {
3560 redirp = &(redir->next);
3561 }
3562 *redirp = redir = xzalloc(sizeof(*redir));
3563 /* redir->next = NULL; */
3564 /* redir->rd_filename = NULL; */
3565 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003566 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003567
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003568 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3569 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003570
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003571 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003572 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003573 /* Erik had a check here that the file descriptor in question
3574 * is legit; I postpone that to "run time"
3575 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003576 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3577 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003578 } else {
3579 /* Set ctx->pending_redirect, so we know what to do at the
3580 * end of the next parsed word. */
3581 ctx->pending_redirect = redir;
3582 }
3583 return 0;
3584}
3585
Eric Andersen25f27032001-04-26 23:22:31 +00003586/* If a redirect is immediately preceded by a number, that number is
3587 * supposed to tell which file descriptor to redirect. This routine
3588 * looks for such preceding numbers. In an ideal world this routine
3589 * needs to handle all the following classes of redirects...
3590 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3591 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3592 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3593 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003594 *
3595 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3596 * "2.7 Redirection
3597 * ... If n is quoted, the number shall not be recognized as part of
3598 * the redirection expression. For example:
3599 * echo \2>a
3600 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003601 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003602 *
3603 * A -1 return means no valid number was found,
3604 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003605 */
3606static int redirect_opt_num(o_string *o)
3607{
3608 int num;
3609
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003610 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003611 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003612 num = bb_strtou(o->data, NULL, 10);
3613 if (errno || num < 0)
3614 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003615 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003616 return num;
3617}
3618
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003619#if BB_MMU
3620#define fetch_till_str(as_string, input, word, skip_tabs) \
3621 fetch_till_str(input, word, skip_tabs)
3622#endif
3623static char *fetch_till_str(o_string *as_string,
3624 struct in_str *input,
3625 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003626 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003627{
3628 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003629 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003630 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003631 int ch;
3632
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003633 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003634
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003635 while (1) {
3636 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003637 if (ch != EOF)
3638 nommu_addchr(as_string, ch);
3639 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003640 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3641 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003642 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3643 heredoc.data[past_EOL] = '\0';
3644 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3645 return heredoc.data;
3646 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003647 while (ch == '\n') {
3648 o_addchr(&heredoc, ch);
3649 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003650 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003651 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003652 do {
3653 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003654 if (ch != EOF)
3655 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003656 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003657 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003658 }
3659 if (ch == EOF) {
3660 o_free_unsafe(&heredoc);
3661 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003662 }
3663 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003664 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003665 if (prev == '\\' && ch == '\\')
3666 /* Correctly handle foo\\<eol> (not a line cont.) */
3667 prev = 0; /* not \ */
3668 else
3669 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003670 }
3671}
3672
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003673/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3674 * and load them all. There should be exactly heredoc_cnt of them.
3675 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003676static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3677{
3678 struct pipe *pi = ctx->list_head;
3679
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003680 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003681 int i;
3682 struct command *cmd = pi->cmds;
3683
3684 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3685 pi->num_cmds,
3686 cmd->argv ? cmd->argv[0] : "NONE");
3687 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003688 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003689
3690 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3691 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003692 while (redir) {
3693 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003694 char *p;
3695
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003696 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003697 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003698 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003699 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003700 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003701 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003702 return 1;
3703 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003704 free(redir->rd_filename);
3705 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003706 heredoc_cnt--;
3707 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003708 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003709 }
3710 cmd++;
3711 }
3712 pi = pi->next;
3713 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003714#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003715 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003716 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003717 bb_error_msg_and_die("heredoc BUG 2");
3718#endif
3719 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003720}
3721
3722
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003723static int run_list(struct pipe *pi);
3724#if BB_MMU
3725#define parse_stream(pstring, input, end_trigger) \
3726 parse_stream(input, end_trigger)
3727#endif
3728static struct pipe *parse_stream(char **pstring,
3729 struct in_str *input,
3730 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003731
Eric Andersen25f27032001-04-26 23:22:31 +00003732
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003733#if !ENABLE_HUSH_FUNCTIONS
3734#define parse_group(dest, ctx, input, ch) \
3735 parse_group(ctx, input, ch)
3736#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003737static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003738 struct in_str *input, int ch)
3739{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003740 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003741 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003742 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003743 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003744 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003745 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003746
3747 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003748#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003749 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003750 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003751 if (done_word(dest, ctx))
3752 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003753 if (!command->argv)
3754 goto skip; /* (... */
3755 if (command->argv[1]) { /* word word ... (... */
3756 syntax_error_unexpected_ch('(');
3757 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003758 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003759 /* it is "word(..." or "word (..." */
3760 do
3761 ch = i_getch(input);
3762 while (ch == ' ' || ch == '\t');
3763 if (ch != ')') {
3764 syntax_error_unexpected_ch(ch);
3765 return 1;
3766 }
3767 nommu_addchr(&ctx->as_string, ch);
3768 do
3769 ch = i_getch(input);
3770 while (ch == ' ' || ch == '\t' || ch == '\n');
3771 if (ch != '{') {
3772 syntax_error_unexpected_ch(ch);
3773 return 1;
3774 }
3775 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003776 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003777 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003778 }
3779#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003780
3781#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003782 if (command->argv /* word [word]{... */
3783 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003784 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003785 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003786 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003787 debug_printf_parse("parse_group return 1: "
3788 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003789 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003790 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003791#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003792
3793#if ENABLE_HUSH_FUNCTIONS
3794 skip:
3795#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003796 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003797 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003798 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003799 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003800 } else {
3801 /* bash does not allow "{echo...", requires whitespace */
3802 ch = i_getch(input);
3803 if (ch != ' ' && ch != '\t' && ch != '\n') {
3804 syntax_error_unexpected_ch(ch);
3805 return 1;
3806 }
3807 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003808 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003809
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003810 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003811#if BB_MMU
3812# define as_string NULL
3813#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003814 char *as_string = NULL;
3815#endif
3816 pipe_list = parse_stream(&as_string, input, endch);
3817#if !BB_MMU
3818 if (as_string)
3819 o_addstr(&ctx->as_string, as_string);
3820#endif
3821 /* empty ()/{} or parse error? */
3822 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003823 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003824 if (!BB_MMU)
3825 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003826 debug_printf_parse("parse_group return 1: "
3827 "parse_stream returned %p\n", pipe_list);
3828 return 1;
3829 }
3830 command->group = pipe_list;
3831#if !BB_MMU
3832 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3833 command->group_as_string = as_string;
3834 debug_printf_parse("end of group, remembering as:'%s'\n",
3835 command->group_as_string);
3836#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003837#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003838 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003839 debug_printf_parse("parse_group return 0\n");
3840 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003841 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003842}
3843
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003844#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003845/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003846static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003847/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003848static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003849{
3850 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003851 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003852 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003853 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003854 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003855 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003856 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003857 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003858 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003859 }
3860}
3861/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003862static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003863{
3864 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003865 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003866 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003867 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003868 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003869 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003870 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003871 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003872 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003873 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003874 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003875 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003876 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003877 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003878 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3879 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003880 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003881 continue;
3882 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003883 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003884 }
3885}
3886/* Process `cmd` - copy contents until "`" is seen. Complicated by
3887 * \` quoting.
3888 * "Within the backquoted style of command substitution, backslash
3889 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3890 * The search for the matching backquote shall be satisfied by the first
3891 * backquote found without a preceding backslash; during this search,
3892 * if a non-escaped backquote is encountered within a shell comment,
3893 * a here-document, an embedded command substitution of the $(command)
3894 * form, or a quoted string, undefined results occur. A single-quoted
3895 * or double-quoted string that begins, but does not end, within the
3896 * "`...`" sequence produces undefined results."
3897 * Example Output
3898 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3899 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003900static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003901{
3902 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003903 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003904 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003905 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003906 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003907 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3908 ch = i_getch(input);
3909 if (ch != '`'
3910 && ch != '$'
3911 && ch != '\\'
3912 && (!in_dquote || ch != '"')
3913 ) {
3914 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003915 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003916 }
3917 if (ch == EOF) {
3918 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003919 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003920 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003921 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003922 }
3923}
3924/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3925 * quoting and nested ()s.
3926 * "With the $(command) style of command substitution, all characters
3927 * following the open parenthesis to the matching closing parenthesis
3928 * constitute the command. Any valid shell script can be used for command,
3929 * except a script consisting solely of redirections which produces
3930 * unspecified results."
3931 * Example Output
3932 * echo $(echo '(TEST)' BEST) (TEST) BEST
3933 * echo $(echo 'TEST)' BEST) TEST) BEST
3934 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003935 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003936 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003937 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003938 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3939 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003940 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003941#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003942static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003943{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003944 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003945 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003946# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003947 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003948# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003949 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3950
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003951 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003952 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003953 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003954 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003955 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003956 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003957 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003958 if (!dbl)
3959 break;
3960 /* we look for closing )) of $((EXPR)) */
3961 if (i_peek(input) == end_ch) {
3962 i_getch(input); /* eat second ')' */
3963 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003964 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003965 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003966 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003967 if (ch == '(' || ch == '{') {
3968 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003969 if (!add_till_closing_bracket(dest, input, ch))
3970 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003971 o_addchr(dest, ch);
3972 continue;
3973 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003974 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003975 if (!add_till_single_quote(dest, input))
3976 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003977 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003978 continue;
3979 }
3980 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003981 if (!add_till_double_quote(dest, input))
3982 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003983 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003984 continue;
3985 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003986 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003987 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3988 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003989 o_addchr(dest, ch);
3990 continue;
3991 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003992 if (ch == '\\') {
3993 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003994 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003995 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003996 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003997 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003998 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003999 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004000 continue;
4001 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004002 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004003 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004004}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004005#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004006
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004007/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004008#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004009#define parse_dollar(as_string, dest, input, quote_mask) \
4010 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004011#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004012#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004013static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004014 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004015 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004016{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004017 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004018
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004019 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004020 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004021 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004022 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004023 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004024 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004025 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004026 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004027 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004028 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004029 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004030 if (!isalnum(ch) && ch != '_')
4031 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004032 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004033 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004034 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004035 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004036 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004037 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004038 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004039 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004040 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004041 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004042 o_addchr(dest, ch | quote_mask);
4043 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004044 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004045 case '$': /* pid */
4046 case '!': /* last bg pid */
4047 case '?': /* last exit code */
4048 case '#': /* number of args */
4049 case '*': /* args */
4050 case '@': /* args */
4051 goto make_one_char_var;
4052 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004053 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4054
Denys Vlasenko74369502010-05-21 19:52:01 +02004055 ch = i_getch(input); /* eat '{' */
4056 nommu_addchr(as_string, ch);
4057
4058 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004059 /* It should be ${?}, or ${#var},
4060 * or even ${?+subst} - operator acting on a special variable,
4061 * or the beginning of variable name.
4062 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004063 if (ch == EOF
4064 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4065 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004066 bad_dollar_syntax:
4067 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004068 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4069 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004070 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004071 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004072 ch |= quote_mask;
4073
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004074 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004075 * However, this regresses some of our testsuite cases
4076 * which check invalid constructs like ${%}.
4077 * Oh well... let's check that the var name part is fine... */
4078
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004079 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004080 unsigned pos;
4081
Denys Vlasenko74369502010-05-21 19:52:01 +02004082 o_addchr(dest, ch);
4083 debug_printf_parse(": '%c'\n", ch);
4084
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004085 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004086 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004087 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004088 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004089
Denys Vlasenko74369502010-05-21 19:52:01 +02004090 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004091 unsigned end_ch;
4092 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004093 /* handle parameter expansions
4094 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4095 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004096 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02004097 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004098
4099 /* Eat everything until closing '}' (or ':') */
4100 end_ch = '}';
4101 if (ENABLE_HUSH_BASH_COMPAT
4102 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004103 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004104 ) {
4105 /* It's ${var:N[:M]} thing */
4106 end_ch = '}' * 0x100 + ':';
4107 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004108 if (ENABLE_HUSH_BASH_COMPAT
4109 && ch == '/'
4110 ) {
4111 /* It's ${var/[/]pattern[/repl]} thing */
4112 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4113 i_getch(input);
4114 nommu_addchr(as_string, '/');
4115 ch = '\\';
4116 }
4117 end_ch = '}' * 0x100 + '/';
4118 }
4119 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004120 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004121 if (!BB_MMU)
4122 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004123#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004124 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004125 if (last_ch == 0) /* error? */
4126 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004127#else
4128#error Simple code to only allow ${var} is not implemented
4129#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004130 if (as_string) {
4131 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004132 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004133 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004134
4135 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4136 /* close the first block: */
4137 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004138 /* while parsing N from ${var:N[:M]}
4139 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004140 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004141 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004142 end_ch = '}';
4143 goto again;
4144 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004145 /* got '}' */
4146 if (end_ch == '}' * 0x100 + ':') {
4147 /* it's ${var:N} - emulate :999999999 */
4148 o_addstr(dest, "999999999");
4149 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004150 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004151 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004152 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004153 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004154 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4155 break;
4156 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004157#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004158 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004159 unsigned pos;
4160
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004161 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004162 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004163# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004164 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004165 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004166 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004167 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4168 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004169 if (!BB_MMU)
4170 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004171 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4172 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004173 if (as_string) {
4174 o_addstr(as_string, dest->data + pos);
4175 o_addchr(as_string, ')');
4176 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004177 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004178 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004179 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004180 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004181# endif
4182# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004183 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4184 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004185 if (!BB_MMU)
4186 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004187 if (!add_till_closing_bracket(dest, input, ')'))
4188 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004189 if (as_string) {
4190 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004191 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004192 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004193 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004194# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004195 break;
4196 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004197#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004198 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004199 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004200 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004201 ch = i_peek(input);
4202 if (isalnum(ch)) { /* it's $_name or $_123 */
4203 ch = '_';
4204 goto make_var;
4205 }
4206 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004207 /* TODO: $_ and $-: */
4208 /* $_ Shell or shell script name; or last argument of last command
4209 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4210 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004211 /* $- Option flags set by set builtin or shell options (-i etc) */
4212 default:
4213 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004214 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004215 debug_printf_parse("parse_dollar return 1 (ok)\n");
4216 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004217#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004218}
4219
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004220#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004221# if ENABLE_HUSH_BASH_COMPAT
4222#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4223 encode_string(dest, input, dquote_end, process_bkslash)
4224# else
4225/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4226#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4227 encode_string(dest, input, dquote_end)
4228# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004229#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004230
4231#else /* !MMU */
4232
4233# if ENABLE_HUSH_BASH_COMPAT
4234/* all parameters are needed, no macro tricks */
4235# else
4236#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4237 encode_string(as_string, dest, input, dquote_end)
4238# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004239#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004240static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004241 o_string *dest,
4242 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004243 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004244 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004245{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004246#if !ENABLE_HUSH_BASH_COMPAT
4247 const int process_bkslash = 1;
4248#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004249 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004250 int next;
4251
4252 again:
4253 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004254 if (ch != EOF)
4255 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004256 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004257 debug_printf_parse("encode_string return 1 (ok)\n");
4258 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004259 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004260 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004261 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004262 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004263 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004264 }
4265 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004266 if (ch != '\n') {
4267 next = i_peek(input);
4268 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004269 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004270 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004271 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004272 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004273 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004274 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004275 }
4276 /* bash:
4277 * "The backslash retains its special meaning [in "..."]
4278 * only when followed by one of the following characters:
4279 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004280 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004281 * NB: in (unquoted) heredoc, above does not apply to ",
4282 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004283 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004284 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004285 ch = i_getch(input); /* eat next */
4286 if (ch == '\n')
4287 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004288 } /* else: ch remains == '\\', and we double it below: */
4289 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004290 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004291 goto again;
4292 }
4293 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004294 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4295 debug_printf_parse("encode_string return 0: "
4296 "parse_dollar returned 0 (error)\n");
4297 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004298 }
4299 goto again;
4300 }
4301#if ENABLE_HUSH_TICK
4302 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004303 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004304 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4305 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004306 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4307 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004308 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4309 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004310 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004311 }
4312#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004313 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004314 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004315#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004316}
4317
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004318/*
4319 * Scan input until EOF or end_trigger char.
4320 * Return a list of pipes to execute, or NULL on EOF
4321 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004322 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004323 * reset parsing machinery and start parsing anew,
4324 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004325 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004326static struct pipe *parse_stream(char **pstring,
4327 struct in_str *input,
4328 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004329{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004330 struct parse_context ctx;
4331 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004332 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004333
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004334 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004335 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004336 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004337 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004338 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004339 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004340
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004341 /* If very first arg is "" or '', dest.data may end up NULL.
4342 * Preventing this: */
4343 o_addchr(&dest, '\0');
4344 dest.length = 0;
4345
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004346 /* We used to separate words on $IFS here. This was wrong.
4347 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004348 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004349 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004350
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004351 if (MAYBE_ASSIGNMENT != 0)
4352 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004353 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004354 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004355 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004356 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004357 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004358 int ch;
4359 int next;
4360 int redir_fd;
4361 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004362
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004363 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004364 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004365 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004366 if (ch == EOF) {
4367 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004368
4369 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004370 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004371 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004372 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004373 /* end_trigger == '}' case errors out earlier,
4374 * checking only ')' */
4375 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004376 syntax_error_unterm_ch('(');
4377 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004378 }
4379
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004380 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004381 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004382 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004383 o_free(&dest);
4384 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004385 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004386 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004387 /* (this makes bare "&" cmd a no-op.
4388 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004389 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004390 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004391 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004392 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004393 pi = NULL;
4394 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004395#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004396 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004397 if (pstring)
4398 *pstring = ctx.as_string.data;
4399 else
4400 o_free_unsafe(&ctx.as_string);
4401#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004402 debug_leave();
4403 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004404 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004405 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004406 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004407
4408 next = '\0';
4409 if (ch != '\n')
4410 next = i_peek(input);
4411
4412 is_special = "{}<>;&|()#'" /* special outside of "str" */
4413 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4414 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004415 if (ctx.command->argv /* word [word]{... - non-special */
4416 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004417 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004418 || (next != ';' /* }; - special */
4419 && next != ')' /* }) - special */
4420 && next != '&' /* }& and }&& ... - special */
4421 && next != '|' /* }|| ... - special */
4422 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004423 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004424 ) {
4425 /* They are not special, skip "{}" */
4426 is_special += 2;
4427 }
4428 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004429 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004430
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004431 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004432 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004433 o_addQchr(&dest, ch);
4434 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4435 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004436 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004437 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004438 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004439 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004440 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004441 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004442 continue;
4443 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004444
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004445 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004446 if (done_word(&dest, &ctx)) {
4447 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004448 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004449 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004450 /* Is this a case when newline is simply ignored?
4451 * Some examples:
4452 * "cmd | <newline> cmd ..."
4453 * "case ... in <newline> word) ..."
4454 */
4455 if (IS_NULL_CMD(ctx.command)
4456 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004457 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004458 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004459 * Without check #1, interactive shell
4460 * ignores even bare <newline>,
4461 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004462 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004463 * ps2> _ <=== wrong, should be ps1
4464 * Without check #2, "cmd & <newline>"
4465 * is similarly mistreated.
4466 * (BTW, this makes "cmd & cmd"
4467 * and "cmd && cmd" non-orthogonal.
4468 * Really, ask yourself, why
4469 * "cmd && <newline>" doesn't start
4470 * cmd but waits for more input?
4471 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004472 */
4473 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004474 if (pi->num_cmds != 0 /* check #1 */
4475 && pi->followup != PIPE_BG /* check #2 */
4476 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004477 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004478 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004479 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004480 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004481 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004482 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4483 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004484 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004485 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004486 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004487 heredoc_cnt = 0;
4488 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004489 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004490 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004491 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004492 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004493 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004494 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004495 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004496
4497 /* "cmd}" or "cmd }..." without semicolon or &:
4498 * } is an ordinary char in this case, even inside { cmd; }
4499 * Pathological example: { ""}; } should exec "}" cmd
4500 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004501 if (ch == '}') {
4502 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4503 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004504 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004505 ) {
4506 goto ordinary_char;
4507 }
4508 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4509 goto skip_end_trigger;
4510 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004511 }
4512
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004513 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004514 && (ch != ';' || heredoc_cnt == 0)
4515#if ENABLE_HUSH_CASE
4516 && (ch != ')'
4517 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004518 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004519 )
4520#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004521 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004522 if (heredoc_cnt) {
4523 /* This is technically valid:
4524 * { cat <<HERE; }; echo Ok
4525 * heredoc
4526 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004527 * HERE
4528 * but we don't support this.
4529 * We require heredoc to be in enclosing {}/(),
4530 * if any.
4531 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004532 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004533 goto parse_error;
4534 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004535 if (done_word(&dest, &ctx)) {
4536 goto parse_error;
4537 }
4538 done_pipe(&ctx, PIPE_SEQ);
4539 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004540 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004541 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004542 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004543 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004544 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004545 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004546#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004547 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004548 if (pstring)
4549 *pstring = ctx.as_string.data;
4550 else
4551 o_free_unsafe(&ctx.as_string);
4552#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004553 debug_leave();
4554 debug_printf_parse("parse_stream return %p: "
4555 "end_trigger char found\n",
4556 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004557 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004558 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004559 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004560 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004561 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004562 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004563
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004564 /* Catch <, > before deciding whether this word is
4565 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4566 switch (ch) {
4567 case '>':
4568 redir_fd = redirect_opt_num(&dest);
4569 if (done_word(&dest, &ctx)) {
4570 goto parse_error;
4571 }
4572 redir_style = REDIRECT_OVERWRITE;
4573 if (next == '>') {
4574 redir_style = REDIRECT_APPEND;
4575 ch = i_getch(input);
4576 nommu_addchr(&ctx.as_string, ch);
4577 }
4578#if 0
4579 else if (next == '(') {
4580 syntax_error(">(process) not supported");
4581 goto parse_error;
4582 }
4583#endif
4584 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4585 goto parse_error;
4586 continue; /* back to top of while (1) */
4587 case '<':
4588 redir_fd = redirect_opt_num(&dest);
4589 if (done_word(&dest, &ctx)) {
4590 goto parse_error;
4591 }
4592 redir_style = REDIRECT_INPUT;
4593 if (next == '<') {
4594 redir_style = REDIRECT_HEREDOC;
4595 heredoc_cnt++;
4596 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4597 ch = i_getch(input);
4598 nommu_addchr(&ctx.as_string, ch);
4599 } else if (next == '>') {
4600 redir_style = REDIRECT_IO;
4601 ch = i_getch(input);
4602 nommu_addchr(&ctx.as_string, ch);
4603 }
4604#if 0
4605 else if (next == '(') {
4606 syntax_error("<(process) not supported");
4607 goto parse_error;
4608 }
4609#endif
4610 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4611 goto parse_error;
4612 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004613 case '#':
4614 if (dest.length == 0 && !dest.has_quoted_part) {
4615 /* skip "#comment" */
4616 while (1) {
4617 ch = i_peek(input);
4618 if (ch == EOF || ch == '\n')
4619 break;
4620 i_getch(input);
4621 /* note: we do not add it to &ctx.as_string */
4622 }
4623 nommu_addchr(&ctx.as_string, '\n');
4624 continue; /* back to top of while (1) */
4625 }
4626 break;
4627 case '\\':
4628 if (next == '\n') {
4629 /* It's "\<newline>" */
4630#if !BB_MMU
4631 /* Remove trailing '\' from ctx.as_string */
4632 ctx.as_string.data[--ctx.as_string.length] = '\0';
4633#endif
4634 ch = i_getch(input); /* eat it */
4635 continue; /* back to top of while (1) */
4636 }
4637 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004638 }
4639
4640 if (dest.o_assignment == MAYBE_ASSIGNMENT
4641 /* check that we are not in word in "a=1 2>word b=1": */
4642 && !ctx.pending_redirect
4643 ) {
4644 /* ch is a special char and thus this word
4645 * cannot be an assignment */
4646 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004647 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004648 }
4649
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004650 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4651
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004652 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004653 case '#': /* non-comment #: "echo a#b" etc */
4654 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004655 break;
4656 case '\\':
4657 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004658 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004659 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004660 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004661 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004662 /* note: ch != '\n' (that case does not reach this place) */
4663 o_addchr(&dest, '\\');
4664 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4665 o_addchr(&dest, ch);
4666 nommu_addchr(&ctx.as_string, ch);
4667 /* Example: echo Hello \2>file
4668 * we need to know that word 2 is quoted */
4669 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004670 break;
4671 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004672 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004673 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004674 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004675 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004676 }
Eric Andersen25f27032001-04-26 23:22:31 +00004677 break;
4678 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004679 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004680 if (next == '\'' && !ctx.pending_redirect) {
4681 insert_empty_quoted_str_marker:
4682 nommu_addchr(&ctx.as_string, next);
4683 i_getch(input); /* eat second ' */
4684 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4685 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4686 } else {
4687 while (1) {
4688 ch = i_getch(input);
4689 if (ch == EOF) {
4690 syntax_error_unterm_ch('\'');
4691 goto parse_error;
4692 }
4693 nommu_addchr(&ctx.as_string, ch);
4694 if (ch == '\'')
4695 break;
4696 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004697 }
Eric Andersen25f27032001-04-26 23:22:31 +00004698 }
Eric Andersen25f27032001-04-26 23:22:31 +00004699 break;
4700 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004701 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004702 if (next == '"' && !ctx.pending_redirect)
4703 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004704 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004705 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004706 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004707 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004708 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004709 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004710#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004711 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004712 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004713
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004714 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4715 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004716 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004717 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4718 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004719# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004720 o_addstr(&ctx.as_string, dest.data + pos);
4721 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004722# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004723 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4724 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004725 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004726 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004727#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004728 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004729#if ENABLE_HUSH_CASE
4730 case_semi:
4731#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004732 if (done_word(&dest, &ctx)) {
4733 goto parse_error;
4734 }
4735 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004736#if ENABLE_HUSH_CASE
4737 /* Eat multiple semicolons, detect
4738 * whether it means something special */
4739 while (1) {
4740 ch = i_peek(input);
4741 if (ch != ';')
4742 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004743 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004744 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004745 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004746 ctx.ctx_dsemicolon = 1;
4747 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004748 break;
4749 }
4750 }
4751#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004752 new_cmd:
4753 /* We just finished a cmd. New one may start
4754 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004755 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004756 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004757 break;
4758 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004759 if (done_word(&dest, &ctx)) {
4760 goto parse_error;
4761 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004762 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004763 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004764 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004765 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004766 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004767 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004768 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004769 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004770 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004771 if (done_word(&dest, &ctx)) {
4772 goto parse_error;
4773 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004774#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004775 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004776 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004777#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004778 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004779 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004780 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004781 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004782 } else {
4783 /* we could pick up a file descriptor choice here
4784 * with redirect_opt_num(), but bash doesn't do it.
4785 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004786 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004787 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004788 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004789 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004790#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004791 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004792 if (ctx.ctx_res_w == RES_MATCH
4793 && ctx.command->argv == NULL /* not (word|(... */
4794 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004795 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004796 ) {
4797 continue;
4798 }
4799#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004800 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004801 if (parse_group(&dest, &ctx, input, ch) != 0) {
4802 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004803 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004804 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004805 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004806#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004807 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004808 goto case_semi;
4809#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004810 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004811 /* proper use of this character is caught by end_trigger:
4812 * if we see {, we call parse_group(..., end_trigger='}')
4813 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004814 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004815 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004816 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004817 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004818 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004819 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004820 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004821
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004822 parse_error:
4823 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004824 struct parse_context *pctx;
4825 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004826
4827 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004828 * Sample for finding leaks on syntax error recovery path.
4829 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004830 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004831 * Samples to catch leaks at execution:
4832 * while if (true | {true;}); then echo ok; fi; do break; done
4833 * 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 +00004834 */
4835 pctx = &ctx;
4836 do {
4837 /* Update pipe/command counts,
4838 * otherwise freeing may miss some */
4839 done_pipe(pctx, PIPE_SEQ);
4840 debug_printf_clean("freeing list %p from ctx %p\n",
4841 pctx->list_head, pctx);
4842 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004843 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004844 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004845#if !BB_MMU
4846 o_free_unsafe(&pctx->as_string);
4847#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004848 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004849 if (pctx != &ctx) {
4850 free(pctx);
4851 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004852 IF_HAS_KEYWORDS(pctx = p2;)
4853 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004854
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004855 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004856 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004857#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004858 if (pstring)
4859 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004860#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004861 debug_leave();
4862 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004863 }
Eric Andersen25f27032001-04-26 23:22:31 +00004864}
4865
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004866
4867/*** Execution routines ***/
4868
4869/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004870#if !ENABLE_HUSH_BASH_COMPAT
4871/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4872#define expand_string_to_string(str, do_unbackslash) \
4873 expand_string_to_string(str)
4874#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004875static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004876#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004877static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004878#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004879
4880/* expand_strvec_to_strvec() takes a list of strings, expands
4881 * all variable references within and returns a pointer to
4882 * a list of expanded strings, possibly with larger number
4883 * of strings. (Think VAR="a b"; echo $VAR).
4884 * This new list is allocated as a single malloc block.
4885 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004886 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004887 * Caller can deallocate entire list by single free(list). */
4888
Denys Vlasenko238081f2010-10-03 14:26:26 +02004889/* A horde of its helpers come first: */
4890
4891static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4892{
4893 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004894 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004895
Denys Vlasenko9e800222010-10-03 14:28:04 +02004896#if ENABLE_HUSH_BRACE_EXPANSION
4897 if (c == '{' || c == '}') {
4898 /* { -> \{, } -> \} */
4899 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004900 /* And now we want to add { or } and continue:
4901 * o_addchr(o, c);
4902 * continue;
4903 * luckily, just falling throught achieves this.
4904 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004905 }
4906#endif
4907 o_addchr(o, c);
4908 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004909 /* \z -> \\\z; \<eol> -> \\<eol> */
4910 o_addchr(o, '\\');
4911 if (len) {
4912 len--;
4913 o_addchr(o, '\\');
4914 o_addchr(o, *str++);
4915 }
4916 }
4917 }
4918}
4919
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004920/* Store given string, finalizing the word and starting new one whenever
4921 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004922 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4923 * Return in *ended_with_ifs:
4924 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4925 */
4926static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004927{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004928 int last_is_ifs = 0;
4929
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004930 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004931 int word_len;
4932
4933 if (!*str) /* EOL - do not finalize word */
4934 break;
4935 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004936 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004937 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02004938 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004939 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004940 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004941 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004942 * Example: "v='\*'; echo b$v" prints "b\*"
4943 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004944 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004945 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004946 /*/ Why can't we do it easier? */
4947 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4948 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4949 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004950 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004951 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004952 if (!*str) /* EOL - do not finalize word */
4953 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004954 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004955
4956 /* We know str here points to at least one IFS char */
4957 last_is_ifs = 1;
4958 str += strspn(str, G.ifs); /* skip IFS chars */
4959 if (!*str) /* EOL - do not finalize word */
4960 break;
4961
4962 /* Start new word... but not always! */
4963 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004964 if (output->has_quoted_part
4965 /* Case "v=' a'; echo $v":
4966 * here nothing precedes the space in $v expansion,
4967 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004968 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004969 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004970 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004971 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004972 o_addchr(output, '\0');
4973 debug_print_list("expand_on_ifs", output, n);
4974 n = o_save_ptr(output, n);
4975 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004976 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004977
4978 if (ended_with_ifs)
4979 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004980 debug_print_list("expand_on_ifs[1]", output, n);
4981 return n;
4982}
4983
4984/* Helper to expand $((...)) and heredoc body. These act as if
4985 * they are in double quotes, with the exception that they are not :).
4986 * Just the rules are similar: "expand only $var and `cmd`"
4987 *
4988 * Returns malloced string.
4989 * As an optimization, we return NULL if expansion is not needed.
4990 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004991#if !ENABLE_HUSH_BASH_COMPAT
4992/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4993#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4994 encode_then_expand_string(str)
4995#endif
4996static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004997{
4998 char *exp_str;
4999 struct in_str input;
5000 o_string dest = NULL_O_STRING;
5001
5002 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005003 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005004#if ENABLE_HUSH_TICK
5005 && !strchr(str, '`')
5006#endif
5007 ) {
5008 return NULL;
5009 }
5010
5011 /* We need to expand. Example:
5012 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5013 */
5014 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005015 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005016//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005017 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005018 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005019 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5020 o_free_unsafe(&dest);
5021 return exp_str;
5022}
5023
5024#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02005025static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005026{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005027 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005028 arith_t res;
5029 char *exp_str;
5030
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005031 math_state.lookupvar = get_local_var_value;
5032 math_state.setvar = set_local_var_from_halves;
5033 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005034 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005035 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005036 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005037 if (errmsg_p)
5038 *errmsg_p = math_state.errmsg;
5039 if (math_state.errmsg)
5040 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005041 return res;
5042}
5043#endif
5044
5045#if ENABLE_HUSH_BASH_COMPAT
5046/* ${var/[/]pattern[/repl]} helpers */
5047static char *strstr_pattern(char *val, const char *pattern, int *size)
5048{
5049 while (1) {
5050 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5051 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5052 if (end) {
5053 *size = end - val;
5054 return val;
5055 }
5056 if (*val == '\0')
5057 return NULL;
5058 /* Optimization: if "*pat" did not match the start of "string",
5059 * we know that "tring", "ring" etc will not match too:
5060 */
5061 if (pattern[0] == '*')
5062 return NULL;
5063 val++;
5064 }
5065}
5066static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5067{
5068 char *result = NULL;
5069 unsigned res_len = 0;
5070 unsigned repl_len = strlen(repl);
5071
5072 while (1) {
5073 int size;
5074 char *s = strstr_pattern(val, pattern, &size);
5075 if (!s)
5076 break;
5077
5078 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5079 memcpy(result + res_len, val, s - val);
5080 res_len += s - val;
5081 strcpy(result + res_len, repl);
5082 res_len += repl_len;
5083 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5084
5085 val = s + size;
5086 if (exp_op == '/')
5087 break;
5088 }
5089 if (val[0] && result) {
5090 result = xrealloc(result, res_len + strlen(val) + 1);
5091 strcpy(result + res_len, val);
5092 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5093 }
5094 debug_printf_varexp("result:'%s'\n", result);
5095 return result;
5096}
5097#endif
5098
5099/* Helper:
5100 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5101 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005102static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005103{
5104 const char *val = NULL;
5105 char *to_be_freed = NULL;
5106 char *p = *pp;
5107 char *var;
5108 char first_char;
5109 char exp_op;
5110 char exp_save = exp_save; /* for compiler */
5111 char *exp_saveptr; /* points to expansion operator */
5112 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005113 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005114
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005115 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005116 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005117 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005118 arg0 = arg[0];
5119 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005120 exp_op = 0;
5121
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005122 if (first_char == '#' /* ${#... */
5123 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5124 ) {
5125 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005126 var++;
5127 exp_op = 'L';
5128 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005129 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005130 if (exp_saveptr /* if 2nd char is one of expansion operators */
5131 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5132 ) {
5133 /* ${?:0}, ${#[:]%0} etc */
5134 exp_saveptr = var + 1;
5135 } else {
5136 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5137 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5138 }
5139 exp_op = exp_save = *exp_saveptr;
5140 if (exp_op) {
5141 exp_word = exp_saveptr + 1;
5142 if (exp_op == ':') {
5143 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005144//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005145 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005146 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005147 ) {
5148 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5149 exp_op = ':';
5150 exp_word--;
5151 }
5152 }
5153 *exp_saveptr = '\0';
5154 } /* else: it's not an expansion op, but bare ${var} */
5155 }
5156
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005157 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005158 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005159 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005160 int n = xatoi_positive(var);
5161 if (n < G.global_argc)
5162 val = G.global_argv[n];
5163 /* else val remains NULL: $N with too big N */
5164 } else {
5165 switch (var[0]) {
5166 case '$': /* pid */
5167 val = utoa(G.root_pid);
5168 break;
5169 case '!': /* bg pid */
5170 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5171 break;
5172 case '?': /* exitcode */
5173 val = utoa(G.last_exitcode);
5174 break;
5175 case '#': /* argc */
5176 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5177 break;
5178 default:
5179 val = get_local_var_value(var);
5180 }
5181 }
5182
5183 /* Handle any expansions */
5184 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005185 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005186 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005187 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005188 debug_printf_expand("%s\n", val);
5189 } else if (exp_op) {
5190 if (exp_op == '%' || exp_op == '#') {
5191 /* Standard-mandated substring removal ops:
5192 * ${parameter%word} - remove smallest suffix pattern
5193 * ${parameter%%word} - remove largest suffix pattern
5194 * ${parameter#word} - remove smallest prefix pattern
5195 * ${parameter##word} - remove largest prefix pattern
5196 *
5197 * Word is expanded to produce a glob pattern.
5198 * Then var's value is matched to it and matching part removed.
5199 */
5200 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005201 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005202 char *exp_exp_word;
5203 char *loc;
5204 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005205 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005206 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005207 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005208 if (exp_exp_word)
5209 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005210 /* HACK ALERT. We depend here on the fact that
5211 * G.global_argv and results of utoa and get_local_var_value
5212 * are actually in writable memory:
5213 * scan_and_match momentarily stores NULs there. */
5214 t = (char*)val;
5215 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005216 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005217 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005218 free(exp_exp_word);
5219 if (loc) { /* match was found */
5220 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005221 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005222 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005223 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005224 }
5225 }
5226 }
5227#if ENABLE_HUSH_BASH_COMPAT
5228 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005229 /* It's ${var/[/]pattern[/repl]} thing.
5230 * Note that in encoded form it has TWO parts:
5231 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005232 * and if // is used, it is encoded as \:
5233 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005234 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005235 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005236 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005237 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005238 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005239 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005240 * by the usual expansion rules:
5241 * >az; >bz;
5242 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5243 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5244 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5245 * v='a bz'; echo ${v/a*z/\z} prints "z"
5246 * (note that a*z _pattern_ is never globbed!)
5247 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005248 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005249 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005250 if (!pattern)
5251 pattern = xstrdup(exp_word);
5252 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5253 *p++ = SPECIAL_VAR_SYMBOL;
5254 exp_word = p;
5255 p = strchr(p, SPECIAL_VAR_SYMBOL);
5256 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005257 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005258 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5259 /* HACK ALERT. We depend here on the fact that
5260 * G.global_argv and results of utoa and get_local_var_value
5261 * are actually in writable memory:
5262 * replace_pattern momentarily stores NULs there. */
5263 t = (char*)val;
5264 to_be_freed = replace_pattern(t,
5265 pattern,
5266 (repl ? repl : exp_word),
5267 exp_op);
5268 if (to_be_freed) /* at least one replace happened */
5269 val = to_be_freed;
5270 free(pattern);
5271 free(repl);
5272 }
5273 }
5274#endif
5275 else if (exp_op == ':') {
5276#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5277 /* It's ${var:N[:M]} bashism.
5278 * Note that in encoded form it has TWO parts:
5279 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5280 */
5281 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005282 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005283
Denys Vlasenko063847d2010-09-15 13:33:02 +02005284 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5285 if (errmsg)
5286 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005287 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5288 *p++ = SPECIAL_VAR_SYMBOL;
5289 exp_word = p;
5290 p = strchr(p, SPECIAL_VAR_SYMBOL);
5291 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005292 len = expand_and_evaluate_arith(exp_word, &errmsg);
5293 if (errmsg)
5294 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005295 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005296 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005297 if (beg < 0) /* bash compat */
5298 beg = 0;
5299 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005300 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005301 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005302 val = NULL;
5303 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005304 /* Paranoia. What if user entered 9999999999999
5305 * which fits in arith_t but not int? */
5306 if (len >= INT_MAX)
5307 len = INT_MAX;
5308 val = to_be_freed = xstrndup(val + beg, len);
5309 }
5310 debug_printf_varexp("val:'%s'\n", val);
5311 } else
5312#endif
5313 {
5314 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005315 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005316 }
5317 } else { /* one of "-=+?" */
5318 /* Standard-mandated substitution ops:
5319 * ${var?word} - indicate error if unset
5320 * If var is unset, word (or a message indicating it is unset
5321 * if word is null) is written to standard error
5322 * and the shell exits with a non-zero exit status.
5323 * Otherwise, the value of var is substituted.
5324 * ${var-word} - use default value
5325 * If var is unset, word is substituted.
5326 * ${var=word} - assign and use default value
5327 * If var is unset, word is assigned to var.
5328 * In all cases, final value of var is substituted.
5329 * ${var+word} - use alternative value
5330 * If var is unset, null is substituted.
5331 * Otherwise, word is substituted.
5332 *
5333 * Word is subjected to tilde expansion, parameter expansion,
5334 * command substitution, and arithmetic expansion.
5335 * If word is not needed, it is not expanded.
5336 *
5337 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5338 * but also treat null var as if it is unset.
5339 */
5340 int use_word = (!val || ((exp_save == ':') && !val[0]));
5341 if (exp_op == '+')
5342 use_word = !use_word;
5343 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5344 (exp_save == ':') ? "true" : "false", use_word);
5345 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005346 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005347 if (to_be_freed)
5348 exp_word = to_be_freed;
5349 if (exp_op == '?') {
5350 /* mimic bash message */
5351 die_if_script("%s: %s",
5352 var,
5353 exp_word[0] ? exp_word : "parameter null or not set"
5354 );
5355//TODO: how interactive bash aborts expansion mid-command?
5356 } else {
5357 val = exp_word;
5358 }
5359
5360 if (exp_op == '=') {
5361 /* ${var=[word]} or ${var:=[word]} */
5362 if (isdigit(var[0]) || var[0] == '#') {
5363 /* mimic bash message */
5364 die_if_script("$%s: cannot assign in this way", var);
5365 val = NULL;
5366 } else {
5367 char *new_var = xasprintf("%s=%s", var, val);
5368 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5369 }
5370 }
5371 }
5372 } /* one of "-=+?" */
5373
5374 *exp_saveptr = exp_save;
5375 } /* if (exp_op) */
5376
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005377 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005378
5379 *pp = p;
5380 *to_be_freed_pp = to_be_freed;
5381 return val;
5382}
5383
5384/* Expand all variable references in given string, adding words to list[]
5385 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5386 * to be filled). This routine is extremely tricky: has to deal with
5387 * variables/parameters with whitespace, $* and $@, and constructs like
5388 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005389static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005390{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005391 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005392 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005393 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005394 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005395 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005396 char *p;
5397
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005398 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5399 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005400 debug_print_list("expand_vars_to_list", output, n);
5401 n = o_save_ptr(output, n);
5402 debug_print_list("expand_vars_to_list[0]", output, n);
5403
5404 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5405 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005406 char *to_be_freed = NULL;
5407 const char *val = NULL;
5408#if ENABLE_HUSH_TICK
5409 o_string subst_result = NULL_O_STRING;
5410#endif
5411#if ENABLE_SH_MATH_SUPPORT
5412 char arith_buf[sizeof(arith_t)*3 + 2];
5413#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005414
5415 if (ended_in_ifs) {
5416 o_addchr(output, '\0');
5417 n = o_save_ptr(output, n);
5418 ended_in_ifs = 0;
5419 }
5420
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005421 o_addblock(output, arg, p - arg);
5422 debug_print_list("expand_vars_to_list[1]", output, n);
5423 arg = ++p;
5424 p = strchr(p, SPECIAL_VAR_SYMBOL);
5425
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005426 /* Fetch special var name (if it is indeed one of them)
5427 * and quote bit, force the bit on if singleword expansion -
5428 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005429 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005430
5431 /* Is this variable quoted and thus expansion can't be null?
5432 * "$@" is special. Even if quoted, it can still
5433 * expand to nothing (not even an empty string),
5434 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005435 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005436 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005437
5438 switch (first_ch & 0x7f) {
5439 /* Highest bit in first_ch indicates that var is double-quoted */
5440 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005441 case '@': {
5442 int i;
5443 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005444 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005445 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005446 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005447 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005448 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005449 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005450 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5451 if (G.global_argv[i++][0] && G.global_argv[i]) {
5452 /* this argv[] is not empty and not last:
5453 * put terminating NUL, start new word */
5454 o_addchr(output, '\0');
5455 debug_print_list("expand_vars_to_list[2]", output, n);
5456 n = o_save_ptr(output, n);
5457 debug_print_list("expand_vars_to_list[3]", output, n);
5458 }
5459 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005460 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005461 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005462 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005463 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005464 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005465 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005466 while (1) {
5467 o_addQstr(output, G.global_argv[i]);
5468 if (++i >= G.global_argc)
5469 break;
5470 o_addchr(output, '\0');
5471 debug_print_list("expand_vars_to_list[4]", output, n);
5472 n = o_save_ptr(output, n);
5473 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005474 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005475 while (1) {
5476 o_addQstr(output, G.global_argv[i]);
5477 if (!G.global_argv[++i])
5478 break;
5479 if (G.ifs[0])
5480 o_addchr(output, G.ifs[0]);
5481 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005482 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005483 }
5484 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005485 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005486 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5487 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005488 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005489 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005490 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005491 break;
5492#if ENABLE_HUSH_TICK
5493 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005494 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005495 arg++;
5496 /* Can't just stuff it into output o_string,
5497 * expanded result may need to be globbed
5498 * and $IFS-splitted */
5499 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5500 G.last_exitcode = process_command_subs(&subst_result, arg);
5501 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5502 val = subst_result.data;
5503 goto store_val;
5504#endif
5505#if ENABLE_SH_MATH_SUPPORT
5506 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5507 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005508
5509 arg++; /* skip '+' */
5510 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5511 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005512 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005513 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5514 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005515 val = arith_buf;
5516 break;
5517 }
5518#endif
5519 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005520 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005521 IF_HUSH_TICK(store_val:)
5522 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005523 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5524 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005525 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005526 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005527 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005528 }
5529 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005530 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005531 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5532 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005533 }
5534 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005535 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5536
5537 if (val && val[0]) {
5538 o_addQstr(output, val);
5539 }
5540 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005541
5542 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5543 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005544 if (*p != SPECIAL_VAR_SYMBOL)
5545 *p = SPECIAL_VAR_SYMBOL;
5546
5547#if ENABLE_HUSH_TICK
5548 o_free(&subst_result);
5549#endif
5550 arg = ++p;
5551 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5552
5553 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005554 if (ended_in_ifs) {
5555 o_addchr(output, '\0');
5556 n = o_save_ptr(output, n);
5557 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005558 debug_print_list("expand_vars_to_list[a]", output, n);
5559 /* this part is literal, and it was already pre-quoted
5560 * if needed (much earlier), do not use o_addQstr here! */
5561 o_addstr_with_NUL(output, arg);
5562 debug_print_list("expand_vars_to_list[b]", output, n);
5563 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005564 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005565 ) {
5566 n--;
5567 /* allow to reuse list[n] later without re-growth */
5568 output->has_empty_slot = 1;
5569 } else {
5570 o_addchr(output, '\0');
5571 }
5572
5573 return n;
5574}
5575
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005576static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005577{
5578 int n;
5579 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005580 o_string output = NULL_O_STRING;
5581
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005582 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005583
5584 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005585 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005586 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005587 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005588 }
5589 debug_print_list("expand_variables", &output, n);
5590
5591 /* output.data (malloced in one block) gets returned in "list" */
5592 list = o_finalize_list(&output, n);
5593 debug_print_strings("expand_variables[1]", list);
5594 return list;
5595}
5596
5597static char **expand_strvec_to_strvec(char **argv)
5598{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005599 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005600}
5601
5602#if ENABLE_HUSH_BASH_COMPAT
5603static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5604{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005605 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005606}
5607#endif
5608
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005609/* Used for expansion of right hand of assignments,
5610 * $((...)), heredocs, variable espansion parts.
5611 *
5612 * NB: should NOT do globbing!
5613 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5614 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005615static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005616{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005617#if !ENABLE_HUSH_BASH_COMPAT
5618 const int do_unbackslash = 1;
5619#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005620 char *argv[2], **list;
5621
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005622 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005623 /* This is generally an optimization, but it also
5624 * handles "", which otherwise trips over !list[0] check below.
5625 * (is this ever happens that we actually get str="" here?)
5626 */
5627 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5628 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005629 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005630 return xstrdup(str);
5631 }
5632
5633 argv[0] = (char*)str;
5634 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005635 list = expand_variables(argv, do_unbackslash
5636 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5637 : EXP_FLAG_SINGLEWORD
5638 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005639 if (HUSH_DEBUG)
5640 if (!list[0] || list[1])
5641 bb_error_msg_and_die("BUG in varexp2");
5642 /* actually, just move string 2*sizeof(char*) bytes back */
5643 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005644 if (do_unbackslash)
5645 unbackslash((char*)list);
5646 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005647 return (char*)list;
5648}
5649
5650/* Used for "eval" builtin */
5651static char* expand_strvec_to_string(char **argv)
5652{
5653 char **list;
5654
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005655 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005656 /* Convert all NULs to spaces */
5657 if (list[0]) {
5658 int n = 1;
5659 while (list[n]) {
5660 if (HUSH_DEBUG)
5661 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5662 bb_error_msg_and_die("BUG in varexp3");
5663 /* bash uses ' ' regardless of $IFS contents */
5664 list[n][-1] = ' ';
5665 n++;
5666 }
5667 }
5668 overlapping_strcpy((char*)list, list[0]);
5669 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5670 return (char*)list;
5671}
5672
5673static char **expand_assignments(char **argv, int count)
5674{
5675 int i;
5676 char **p;
5677
5678 G.expanded_assignments = p = NULL;
5679 /* Expand assignments into one string each */
5680 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005681 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005682 }
5683 G.expanded_assignments = NULL;
5684 return p;
5685}
5686
5687
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005688static void switch_off_special_sigs(unsigned mask)
5689{
5690 unsigned sig = 0;
5691 while ((mask >>= 1) != 0) {
5692 sig++;
5693 if (!(mask & 1))
5694 continue;
5695 if (G.traps) {
5696 if (G.traps[sig] && !G.traps[sig][0])
5697 /* trap is '', has to remain SIG_IGN */
5698 continue;
5699 free(G.traps[sig]);
5700 G.traps[sig] = NULL;
5701 }
5702 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005703 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005704 }
5705}
5706
Denys Vlasenkob347df92011-08-09 22:49:15 +02005707#if BB_MMU
5708/* never called */
5709void re_execute_shell(char ***to_free, const char *s,
5710 char *g_argv0, char **g_argv,
5711 char **builtin_argv) NORETURN;
5712
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005713static void reset_traps_to_defaults(void)
5714{
5715 /* This function is always called in a child shell
5716 * after fork (not vfork, NOMMU doesn't use this function).
5717 */
5718 unsigned sig;
5719 unsigned mask;
5720
5721 /* Child shells are not interactive.
5722 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5723 * Testcase: (while :; do :; done) + ^Z should background.
5724 * Same goes for SIGTERM, SIGHUP, SIGINT.
5725 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005726 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5727 if (!G.traps && !mask)
5728 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005729
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005730 /* Switch off special sigs */
5731 switch_off_special_sigs(mask);
5732#if ENABLE_HUSH_JOB
5733 G_fatal_sig_mask = 0;
5734#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005735 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005736 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5737 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005738
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005739 if (!G.traps)
5740 return;
5741
5742 /* Reset all sigs to default except ones with empty traps */
5743 for (sig = 0; sig < NSIG; sig++) {
5744 if (!G.traps[sig])
5745 continue; /* no trap: nothing to do */
5746 if (!G.traps[sig][0])
5747 continue; /* empty trap: has to remain SIG_IGN */
5748 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005749 free(G.traps[sig]);
5750 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005751 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005752 if (sig == 0)
5753 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005754 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005755 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005756}
5757
5758#else /* !BB_MMU */
5759
5760static void re_execute_shell(char ***to_free, const char *s,
5761 char *g_argv0, char **g_argv,
5762 char **builtin_argv) NORETURN;
5763static void re_execute_shell(char ***to_free, const char *s,
5764 char *g_argv0, char **g_argv,
5765 char **builtin_argv)
5766{
5767# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5768 /* delims + 2 * (number of bytes in printed hex numbers) */
5769 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5770 char *heredoc_argv[4];
5771 struct variable *cur;
5772# if ENABLE_HUSH_FUNCTIONS
5773 struct function *funcp;
5774# endif
5775 char **argv, **pp;
5776 unsigned cnt;
5777 unsigned long long empty_trap_mask;
5778
5779 if (!g_argv0) { /* heredoc */
5780 argv = heredoc_argv;
5781 argv[0] = (char *) G.argv0_for_re_execing;
5782 argv[1] = (char *) "-<";
5783 argv[2] = (char *) s;
5784 argv[3] = NULL;
5785 pp = &argv[3]; /* used as pointer to empty environment */
5786 goto do_exec;
5787 }
5788
5789 cnt = 0;
5790 pp = builtin_argv;
5791 if (pp) while (*pp++)
5792 cnt++;
5793
5794 empty_trap_mask = 0;
5795 if (G.traps) {
5796 int sig;
5797 for (sig = 1; sig < NSIG; sig++) {
5798 if (G.traps[sig] && !G.traps[sig][0])
5799 empty_trap_mask |= 1LL << sig;
5800 }
5801 }
5802
5803 sprintf(param_buf, NOMMU_HACK_FMT
5804 , (unsigned) G.root_pid
5805 , (unsigned) G.root_ppid
5806 , (unsigned) G.last_bg_pid
5807 , (unsigned) G.last_exitcode
5808 , cnt
5809 , empty_trap_mask
5810 IF_HUSH_LOOPS(, G.depth_of_loop)
5811 );
5812# undef NOMMU_HACK_FMT
5813 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5814 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5815 */
5816 cnt += 6;
5817 for (cur = G.top_var; cur; cur = cur->next) {
5818 if (!cur->flg_export || cur->flg_read_only)
5819 cnt += 2;
5820 }
5821# if ENABLE_HUSH_FUNCTIONS
5822 for (funcp = G.top_func; funcp; funcp = funcp->next)
5823 cnt += 3;
5824# endif
5825 pp = g_argv;
5826 while (*pp++)
5827 cnt++;
5828 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5829 *pp++ = (char *) G.argv0_for_re_execing;
5830 *pp++ = param_buf;
5831 for (cur = G.top_var; cur; cur = cur->next) {
5832 if (strcmp(cur->varstr, hush_version_str) == 0)
5833 continue;
5834 if (cur->flg_read_only) {
5835 *pp++ = (char *) "-R";
5836 *pp++ = cur->varstr;
5837 } else if (!cur->flg_export) {
5838 *pp++ = (char *) "-V";
5839 *pp++ = cur->varstr;
5840 }
5841 }
5842# if ENABLE_HUSH_FUNCTIONS
5843 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5844 *pp++ = (char *) "-F";
5845 *pp++ = funcp->name;
5846 *pp++ = funcp->body_as_string;
5847 }
5848# endif
5849 /* We can pass activated traps here. Say, -Tnn:trap_string
5850 *
5851 * However, POSIX says that subshells reset signals with traps
5852 * to SIG_DFL.
5853 * I tested bash-3.2 and it not only does that with true subshells
5854 * of the form ( list ), but with any forked children shells.
5855 * I set trap "echo W" WINCH; and then tried:
5856 *
5857 * { echo 1; sleep 20; echo 2; } &
5858 * while true; do echo 1; sleep 20; echo 2; break; done &
5859 * true | { echo 1; sleep 20; echo 2; } | cat
5860 *
5861 * In all these cases sending SIGWINCH to the child shell
5862 * did not run the trap. If I add trap "echo V" WINCH;
5863 * _inside_ group (just before echo 1), it works.
5864 *
5865 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005866 */
5867 *pp++ = (char *) "-c";
5868 *pp++ = (char *) s;
5869 if (builtin_argv) {
5870 while (*++builtin_argv)
5871 *pp++ = *builtin_argv;
5872 *pp++ = (char *) "";
5873 }
5874 *pp++ = g_argv0;
5875 while (*g_argv)
5876 *pp++ = *g_argv++;
5877 /* *pp = NULL; - is already there */
5878 pp = environ;
5879
5880 do_exec:
5881 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02005882 /* Don't propagate SIG_IGN to the child */
5883 if (SPECIAL_JOBSTOP_SIGS != 0)
5884 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005885 execve(bb_busybox_exec_path, argv, pp);
5886 /* Fallback. Useful for init=/bin/hush usage etc */
5887 if (argv[0][0] == '/')
5888 execve(argv[0], argv, pp);
5889 xfunc_error_retval = 127;
5890 bb_error_msg_and_die("can't re-execute the shell");
5891}
5892#endif /* !BB_MMU */
5893
5894
5895static int run_and_free_list(struct pipe *pi);
5896
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005897/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005898 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5899 * end_trigger controls how often we stop parsing
5900 * NUL: parse all, execute, return
5901 * ';': parse till ';' or newline, execute, repeat till EOF
5902 */
5903static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005904{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005905 /* Why we need empty flag?
5906 * An obscure corner case "false; ``; echo $?":
5907 * empty command in `` should still set $? to 0.
5908 * But we can't just set $? to 0 at the start,
5909 * this breaks "false; echo `echo $?`" case.
5910 */
5911 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005912 while (1) {
5913 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005914
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005915#if ENABLE_HUSH_INTERACTIVE
5916 if (end_trigger == ';')
5917 inp->promptmode = 0; /* PS1 */
5918#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005919 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005920 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5921 /* If we are in "big" script
5922 * (not in `cmd` or something similar)...
5923 */
5924 if (pipe_list == ERR_PTR && end_trigger == ';') {
5925 /* Discard cached input (rest of line) */
5926 int ch = inp->last_char;
5927 while (ch != EOF && ch != '\n') {
5928 //bb_error_msg("Discarded:'%c'", ch);
5929 ch = i_getch(inp);
5930 }
5931 /* Force prompt */
5932 inp->p = NULL;
5933 /* This stream isn't empty */
5934 empty = 0;
5935 continue;
5936 }
5937 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01005938 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005939 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005940 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005941 debug_print_tree(pipe_list, 0);
5942 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5943 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005944 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005945#if ENABLE_HUSH_FUNCTIONS
5946 if (G.flag_return_in_progress == 1)
5947 break;
5948#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005949 }
Eric Andersen25f27032001-04-26 23:22:31 +00005950}
5951
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005952static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005953{
5954 struct in_str input;
5955 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005956 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005957}
5958
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005959static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005960{
Eric Andersen25f27032001-04-26 23:22:31 +00005961 struct in_str input;
5962 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005963 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005964}
5965
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005966#if ENABLE_HUSH_TICK
5967static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5968{
5969 pid_t pid;
5970 int channel[2];
5971# if !BB_MMU
5972 char **to_free = NULL;
5973# endif
5974
5975 xpipe(channel);
5976 pid = BB_MMU ? xfork() : xvfork();
5977 if (pid == 0) { /* child */
5978 disable_restore_tty_pgrp_on_exit();
5979 /* Process substitution is not considered to be usual
5980 * 'command execution'.
5981 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5982 */
5983 bb_signals(0
5984 + (1 << SIGTSTP)
5985 + (1 << SIGTTIN)
5986 + (1 << SIGTTOU)
5987 , SIG_IGN);
5988 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5989 close(channel[0]); /* NB: close _first_, then move fd! */
5990 xmove_fd(channel[1], 1);
5991 /* Prevent it from trying to handle ctrl-z etc */
5992 IF_HUSH_JOB(G.run_list_level = 1;)
5993 /* Awful hack for `trap` or $(trap).
5994 *
5995 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5996 * contains an example where "trap" is executed in a subshell:
5997 *
5998 * save_traps=$(trap)
5999 * ...
6000 * eval "$save_traps"
6001 *
6002 * Standard does not say that "trap" in subshell shall print
6003 * parent shell's traps. It only says that its output
6004 * must have suitable form, but then, in the above example
6005 * (which is not supposed to be normative), it implies that.
6006 *
6007 * bash (and probably other shell) does implement it
6008 * (traps are reset to defaults, but "trap" still shows them),
6009 * but as a result, "trap" logic is hopelessly messed up:
6010 *
6011 * # trap
6012 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6013 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6014 * # true | trap <--- trap is in subshell - no output (ditto)
6015 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6016 * trap -- 'echo Ho' SIGWINCH
6017 * # echo `(trap)` <--- in subshell in subshell - output
6018 * trap -- 'echo Ho' SIGWINCH
6019 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6020 * trap -- 'echo Ho' SIGWINCH
6021 *
6022 * The rules when to forget and when to not forget traps
6023 * get really complex and nonsensical.
6024 *
6025 * Our solution: ONLY bare $(trap) or `trap` is special.
6026 */
6027 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006028 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006029 && skip_whitespace(s + 4)[0] == '\0'
6030 ) {
6031 static const char *const argv[] = { NULL, NULL };
6032 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006033 fflush_all(); /* important */
6034 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006035 }
6036# if BB_MMU
6037 reset_traps_to_defaults();
6038 parse_and_run_string(s);
6039 _exit(G.last_exitcode);
6040# else
6041 /* We re-execute after vfork on NOMMU. This makes this script safe:
6042 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6043 * huge=`cat BIG` # was blocking here forever
6044 * echo OK
6045 */
6046 re_execute_shell(&to_free,
6047 s,
6048 G.global_argv[0],
6049 G.global_argv + 1,
6050 NULL);
6051# endif
6052 }
6053
6054 /* parent */
6055 *pid_p = pid;
6056# if ENABLE_HUSH_FAST
6057 G.count_SIGCHLD++;
6058//bb_error_msg("[%d] fork in generate_stream_from_string:"
6059// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6060// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6061# endif
6062 enable_restore_tty_pgrp_on_exit();
6063# if !BB_MMU
6064 free(to_free);
6065# endif
6066 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006067 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006068}
6069
6070/* Return code is exit status of the process that is run. */
6071static int process_command_subs(o_string *dest, const char *s)
6072{
6073 FILE *fp;
6074 struct in_str pipe_str;
6075 pid_t pid;
6076 int status, ch, eol_cnt;
6077
6078 fp = generate_stream_from_string(s, &pid);
6079
6080 /* Now send results of command back into original context */
6081 setup_file_in_str(&pipe_str, fp);
6082 eol_cnt = 0;
6083 while ((ch = i_getch(&pipe_str)) != EOF) {
6084 if (ch == '\n') {
6085 eol_cnt++;
6086 continue;
6087 }
6088 while (eol_cnt) {
6089 o_addchr(dest, '\n');
6090 eol_cnt--;
6091 }
6092 o_addQchr(dest, ch);
6093 }
6094
6095 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006096 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006097 /* We need to extract exitcode. Test case
6098 * "true; echo `sleep 1; false` $?"
6099 * should print 1 */
6100 safe_waitpid(pid, &status, 0);
6101 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6102 return WEXITSTATUS(status);
6103}
6104#endif /* ENABLE_HUSH_TICK */
6105
6106
6107static void setup_heredoc(struct redir_struct *redir)
6108{
6109 struct fd_pair pair;
6110 pid_t pid;
6111 int len, written;
6112 /* the _body_ of heredoc (misleading field name) */
6113 const char *heredoc = redir->rd_filename;
6114 char *expanded;
6115#if !BB_MMU
6116 char **to_free;
6117#endif
6118
6119 expanded = NULL;
6120 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006121 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006122 if (expanded)
6123 heredoc = expanded;
6124 }
6125 len = strlen(heredoc);
6126
6127 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6128 xpiped_pair(pair);
6129 xmove_fd(pair.rd, redir->rd_fd);
6130
6131 /* Try writing without forking. Newer kernels have
6132 * dynamically growing pipes. Must use non-blocking write! */
6133 ndelay_on(pair.wr);
6134 while (1) {
6135 written = write(pair.wr, heredoc, len);
6136 if (written <= 0)
6137 break;
6138 len -= written;
6139 if (len == 0) {
6140 close(pair.wr);
6141 free(expanded);
6142 return;
6143 }
6144 heredoc += written;
6145 }
6146 ndelay_off(pair.wr);
6147
6148 /* Okay, pipe buffer was not big enough */
6149 /* Note: we must not create a stray child (bastard? :)
6150 * for the unsuspecting parent process. Child creates a grandchild
6151 * and exits before parent execs the process which consumes heredoc
6152 * (that exec happens after we return from this function) */
6153#if !BB_MMU
6154 to_free = NULL;
6155#endif
6156 pid = xvfork();
6157 if (pid == 0) {
6158 /* child */
6159 disable_restore_tty_pgrp_on_exit();
6160 pid = BB_MMU ? xfork() : xvfork();
6161 if (pid != 0)
6162 _exit(0);
6163 /* grandchild */
6164 close(redir->rd_fd); /* read side of the pipe */
6165#if BB_MMU
6166 full_write(pair.wr, heredoc, len); /* may loop or block */
6167 _exit(0);
6168#else
6169 /* Delegate blocking writes to another process */
6170 xmove_fd(pair.wr, STDOUT_FILENO);
6171 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6172#endif
6173 }
6174 /* parent */
6175#if ENABLE_HUSH_FAST
6176 G.count_SIGCHLD++;
6177//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6178#endif
6179 enable_restore_tty_pgrp_on_exit();
6180#if !BB_MMU
6181 free(to_free);
6182#endif
6183 close(pair.wr);
6184 free(expanded);
6185 wait(NULL); /* wait till child has died */
6186}
6187
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006188/* fd: redirect wants this fd to be used (e.g. 3>file).
6189 * Move all conflicting internally used fds,
6190 * and remember them so that we can restore them later.
6191 */
6192static int save_fds_on_redirect(int fd, int squirrel[3])
6193{
6194 if (squirrel) {
6195 /* Handle redirects of fds 0,1,2 */
6196
6197 /* If we collide with an already moved stdio fd... */
6198 if (fd == squirrel[0]) {
6199 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6200 return 1;
6201 }
6202 if (fd == squirrel[1]) {
6203 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6204 return 1;
6205 }
6206 if (fd == squirrel[2]) {
6207 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6208 return 1;
6209 }
6210 /* If we are about to redirect stdio fd, and did not yet move it... */
6211 if (fd <= 2 && squirrel[fd] < 0) {
6212 /* We avoid taking stdio fds */
6213 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6214 if (squirrel[fd] < 0 && errno != EBADF)
6215 xfunc_die();
6216 return 0; /* "we did not close fd" */
6217 }
6218 }
6219
6220#if ENABLE_HUSH_INTERACTIVE
6221 if (fd != 0 && fd == G.interactive_fd) {
6222 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6223 return 1;
6224 }
6225#endif
6226
6227 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6228 * (1) Redirect in a forked child. No need to save FILEs' fds,
6229 * we aren't going to use them anymore, ok to trash.
6230 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6231 * but how are we doing to use them?
6232 * "fileno(fd) = new_fd" can't be done.
6233 */
6234 if (!squirrel)
6235 return 0;
6236
6237 return save_FILEs_on_redirect(fd);
6238}
6239
6240static void restore_redirects(int squirrel[3])
6241{
6242 int i, fd;
6243 for (i = 0; i <= 2; i++) {
6244 fd = squirrel[i];
6245 if (fd != -1) {
6246 /* We simply die on error */
6247 xmove_fd(fd, i);
6248 }
6249 }
6250
6251 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6252
6253 restore_redirected_FILEs();
6254}
6255
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006256/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6257 * and stderr if they are redirected. */
6258static int setup_redirects(struct command *prog, int squirrel[])
6259{
6260 int openfd, mode;
6261 struct redir_struct *redir;
6262
6263 for (redir = prog->redirects; redir; redir = redir->next) {
6264 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006265 /* "rd_fd<<HERE" case */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006266 save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006267 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6268 * of the heredoc */
6269 debug_printf_parse("set heredoc '%s'\n",
6270 redir->rd_filename);
6271 setup_heredoc(redir);
6272 continue;
6273 }
6274
6275 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006276 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006277 char *p;
6278 if (redir->rd_filename == NULL) {
6279 /* Something went wrong in the parse.
6280 * Pretend it didn't happen */
6281 bb_error_msg("bug in redirect parse");
6282 continue;
6283 }
6284 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006285 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006286 openfd = open_or_warn(p, mode);
6287 free(p);
6288 if (openfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006289 /* Error message from open_or_warn can be lost
6290 * if stderr has been redirected, but bash
6291 * and ash both lose it as well
6292 * (though zsh doesn't!)
6293 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006294 return 1;
6295 }
6296 } else {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006297 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006298 openfd = redir->rd_dup;
6299 }
6300
6301 if (openfd != redir->rd_fd) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006302 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006303 if (openfd == REDIRFD_CLOSE) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006304 /* "rd_fd >&-" means "close me" */
6305 if (!closed) {
6306 /* ^^^ optimization: saving may already
6307 * have closed it. If not... */
6308 close(redir->rd_fd);
6309 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006310 } else {
6311 xdup2(openfd, redir->rd_fd);
6312 if (redir->rd_dup == REDIRFD_TO_FILE)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006313 /* "rd_fd > FILE" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006314 close(openfd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006315 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006316 }
6317 }
6318 }
6319 return 0;
6320}
6321
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006322static char *find_in_path(const char *arg)
6323{
6324 char *ret = NULL;
6325 const char *PATH = get_local_var_value("PATH");
6326
6327 if (!PATH)
6328 return NULL;
6329
6330 while (1) {
6331 const char *end = strchrnul(PATH, ':');
6332 int sz = end - PATH; /* must be int! */
6333
6334 free(ret);
6335 if (sz != 0) {
6336 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6337 } else {
6338 /* We have xxx::yyyy in $PATH,
6339 * it means "use current dir" */
6340 ret = xstrdup(arg);
6341 }
6342 if (access(ret, F_OK) == 0)
6343 break;
6344
6345 if (*end == '\0') {
6346 free(ret);
6347 return NULL;
6348 }
6349 PATH = end + 1;
6350 }
6351
6352 return ret;
6353}
6354
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006355static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006356 const struct built_in_command *x,
6357 const struct built_in_command *end)
6358{
6359 while (x != end) {
6360 if (strcmp(name, x->b_cmd) != 0) {
6361 x++;
6362 continue;
6363 }
6364 debug_printf_exec("found builtin '%s'\n", name);
6365 return x;
6366 }
6367 return NULL;
6368}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006369static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006370{
6371 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6372}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006373static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006374{
6375 const struct built_in_command *x = find_builtin1(name);
6376 if (x)
6377 return x;
6378 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6379}
6380
6381#if ENABLE_HUSH_FUNCTIONS
6382static struct function **find_function_slot(const char *name)
6383{
6384 struct function **funcpp = &G.top_func;
6385 while (*funcpp) {
6386 if (strcmp(name, (*funcpp)->name) == 0) {
6387 break;
6388 }
6389 funcpp = &(*funcpp)->next;
6390 }
6391 return funcpp;
6392}
6393
6394static const struct function *find_function(const char *name)
6395{
6396 const struct function *funcp = *find_function_slot(name);
6397 if (funcp)
6398 debug_printf_exec("found function '%s'\n", name);
6399 return funcp;
6400}
6401
6402/* Note: takes ownership on name ptr */
6403static struct function *new_function(char *name)
6404{
6405 struct function **funcpp = find_function_slot(name);
6406 struct function *funcp = *funcpp;
6407
6408 if (funcp != NULL) {
6409 struct command *cmd = funcp->parent_cmd;
6410 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6411 if (!cmd) {
6412 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6413 free(funcp->name);
6414 /* Note: if !funcp->body, do not free body_as_string!
6415 * This is a special case of "-F name body" function:
6416 * body_as_string was not malloced! */
6417 if (funcp->body) {
6418 free_pipe_list(funcp->body);
6419# if !BB_MMU
6420 free(funcp->body_as_string);
6421# endif
6422 }
6423 } else {
6424 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6425 cmd->argv[0] = funcp->name;
6426 cmd->group = funcp->body;
6427# if !BB_MMU
6428 cmd->group_as_string = funcp->body_as_string;
6429# endif
6430 }
6431 } else {
6432 debug_printf_exec("remembering new function '%s'\n", name);
6433 funcp = *funcpp = xzalloc(sizeof(*funcp));
6434 /*funcp->next = NULL;*/
6435 }
6436
6437 funcp->name = name;
6438 return funcp;
6439}
6440
6441static void unset_func(const char *name)
6442{
6443 struct function **funcpp = find_function_slot(name);
6444 struct function *funcp = *funcpp;
6445
6446 if (funcp != NULL) {
6447 debug_printf_exec("freeing function '%s'\n", funcp->name);
6448 *funcpp = funcp->next;
6449 /* funcp is unlinked now, deleting it.
6450 * Note: if !funcp->body, the function was created by
6451 * "-F name body", do not free ->body_as_string
6452 * and ->name as they were not malloced. */
6453 if (funcp->body) {
6454 free_pipe_list(funcp->body);
6455 free(funcp->name);
6456# if !BB_MMU
6457 free(funcp->body_as_string);
6458# endif
6459 }
6460 free(funcp);
6461 }
6462}
6463
6464# if BB_MMU
6465#define exec_function(to_free, funcp, argv) \
6466 exec_function(funcp, argv)
6467# endif
6468static void exec_function(char ***to_free,
6469 const struct function *funcp,
6470 char **argv) NORETURN;
6471static void exec_function(char ***to_free,
6472 const struct function *funcp,
6473 char **argv)
6474{
6475# if BB_MMU
6476 int n = 1;
6477
6478 argv[0] = G.global_argv[0];
6479 G.global_argv = argv;
6480 while (*++argv)
6481 n++;
6482 G.global_argc = n;
6483 /* On MMU, funcp->body is always non-NULL */
6484 n = run_list(funcp->body);
6485 fflush_all();
6486 _exit(n);
6487# else
6488 re_execute_shell(to_free,
6489 funcp->body_as_string,
6490 G.global_argv[0],
6491 argv + 1,
6492 NULL);
6493# endif
6494}
6495
6496static int run_function(const struct function *funcp, char **argv)
6497{
6498 int rc;
6499 save_arg_t sv;
6500 smallint sv_flg;
6501
6502 save_and_replace_G_args(&sv, argv);
6503
6504 /* "we are in function, ok to use return" */
6505 sv_flg = G.flag_return_in_progress;
6506 G.flag_return_in_progress = -1;
6507# if ENABLE_HUSH_LOCAL
6508 G.func_nest_level++;
6509# endif
6510
6511 /* On MMU, funcp->body is always non-NULL */
6512# if !BB_MMU
6513 if (!funcp->body) {
6514 /* Function defined by -F */
6515 parse_and_run_string(funcp->body_as_string);
6516 rc = G.last_exitcode;
6517 } else
6518# endif
6519 {
6520 rc = run_list(funcp->body);
6521 }
6522
6523# if ENABLE_HUSH_LOCAL
6524 {
6525 struct variable *var;
6526 struct variable **var_pp;
6527
6528 var_pp = &G.top_var;
6529 while ((var = *var_pp) != NULL) {
6530 if (var->func_nest_level < G.func_nest_level) {
6531 var_pp = &var->next;
6532 continue;
6533 }
6534 /* Unexport */
6535 if (var->flg_export)
6536 bb_unsetenv(var->varstr);
6537 /* Remove from global list */
6538 *var_pp = var->next;
6539 /* Free */
6540 if (!var->max_len)
6541 free(var->varstr);
6542 free(var);
6543 }
6544 G.func_nest_level--;
6545 }
6546# endif
6547 G.flag_return_in_progress = sv_flg;
6548
6549 restore_G_args(&sv, argv);
6550
6551 return rc;
6552}
6553#endif /* ENABLE_HUSH_FUNCTIONS */
6554
6555
6556#if BB_MMU
6557#define exec_builtin(to_free, x, argv) \
6558 exec_builtin(x, argv)
6559#else
6560#define exec_builtin(to_free, x, argv) \
6561 exec_builtin(to_free, argv)
6562#endif
6563static void exec_builtin(char ***to_free,
6564 const struct built_in_command *x,
6565 char **argv) NORETURN;
6566static void exec_builtin(char ***to_free,
6567 const struct built_in_command *x,
6568 char **argv)
6569{
6570#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006571 int rcode;
6572 fflush_all();
6573 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006574 fflush_all();
6575 _exit(rcode);
6576#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006577 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006578 /* On NOMMU, we must never block!
6579 * Example: { sleep 99 | read line; } & echo Ok
6580 */
6581 re_execute_shell(to_free,
6582 argv[0],
6583 G.global_argv[0],
6584 G.global_argv + 1,
6585 argv);
6586#endif
6587}
6588
6589
6590static void execvp_or_die(char **argv) NORETURN;
6591static void execvp_or_die(char **argv)
6592{
6593 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006594 /* Don't propagate SIG_IGN to the child */
6595 if (SPECIAL_JOBSTOP_SIGS != 0)
6596 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006597 execvp(argv[0], argv);
6598 bb_perror_msg("can't execute '%s'", argv[0]);
6599 _exit(127); /* bash compat */
6600}
6601
6602#if ENABLE_HUSH_MODE_X
6603static void dump_cmd_in_x_mode(char **argv)
6604{
6605 if (G_x_mode && argv) {
6606 /* We want to output the line in one write op */
6607 char *buf, *p;
6608 int len;
6609 int n;
6610
6611 len = 3;
6612 n = 0;
6613 while (argv[n])
6614 len += strlen(argv[n++]) + 1;
6615 buf = xmalloc(len);
6616 buf[0] = '+';
6617 p = buf + 1;
6618 n = 0;
6619 while (argv[n])
6620 p += sprintf(p, " %s", argv[n++]);
6621 *p++ = '\n';
6622 *p = '\0';
6623 fputs(buf, stderr);
6624 free(buf);
6625 }
6626}
6627#else
6628# define dump_cmd_in_x_mode(argv) ((void)0)
6629#endif
6630
6631#if BB_MMU
6632#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6633 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6634#define pseudo_exec(nommu_save, command, argv_expanded) \
6635 pseudo_exec(command, argv_expanded)
6636#endif
6637
6638/* Called after [v]fork() in run_pipe, or from builtin_exec.
6639 * Never returns.
6640 * Don't exit() here. If you don't exec, use _exit instead.
6641 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006642 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006643 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006644static void pseudo_exec_argv(nommu_save_t *nommu_save,
6645 char **argv, int assignment_cnt,
6646 char **argv_expanded) NORETURN;
6647static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6648 char **argv, int assignment_cnt,
6649 char **argv_expanded)
6650{
6651 char **new_env;
6652
6653 new_env = expand_assignments(argv, assignment_cnt);
6654 dump_cmd_in_x_mode(new_env);
6655
6656 if (!argv[assignment_cnt]) {
6657 /* Case when we are here: ... | var=val | ...
6658 * (note that we do not exit early, i.e., do not optimize out
6659 * expand_assignments(): think about ... | var=`sleep 1` | ...
6660 */
6661 free_strings(new_env);
6662 _exit(EXIT_SUCCESS);
6663 }
6664
6665#if BB_MMU
6666 set_vars_and_save_old(new_env);
6667 free(new_env); /* optional */
6668 /* we can also destroy set_vars_and_save_old's return value,
6669 * to save memory */
6670#else
6671 nommu_save->new_env = new_env;
6672 nommu_save->old_vars = set_vars_and_save_old(new_env);
6673#endif
6674
6675 if (argv_expanded) {
6676 argv = argv_expanded;
6677 } else {
6678 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6679#if !BB_MMU
6680 nommu_save->argv = argv;
6681#endif
6682 }
6683 dump_cmd_in_x_mode(argv);
6684
6685#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6686 if (strchr(argv[0], '/') != NULL)
6687 goto skip;
6688#endif
6689
6690 /* Check if the command matches any of the builtins.
6691 * Depending on context, this might be redundant. But it's
6692 * easier to waste a few CPU cycles than it is to figure out
6693 * if this is one of those cases.
6694 */
6695 {
6696 /* On NOMMU, it is more expensive to re-execute shell
6697 * just in order to run echo or test builtin.
6698 * It's better to skip it here and run corresponding
6699 * non-builtin later. */
6700 const struct built_in_command *x;
6701 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6702 if (x) {
6703 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6704 }
6705 }
6706#if ENABLE_HUSH_FUNCTIONS
6707 /* Check if the command matches any functions */
6708 {
6709 const struct function *funcp = find_function(argv[0]);
6710 if (funcp) {
6711 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6712 }
6713 }
6714#endif
6715
6716#if ENABLE_FEATURE_SH_STANDALONE
6717 /* Check if the command matches any busybox applets */
6718 {
6719 int a = find_applet_by_name(argv[0]);
6720 if (a >= 0) {
6721# if BB_MMU /* see above why on NOMMU it is not allowed */
6722 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006723 /* Do not leak open fds from opened script files etc */
6724 close_all_FILE_list();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006725 debug_printf_exec("running applet '%s'\n", argv[0]);
6726 run_applet_no_and_exit(a, argv);
6727 }
6728# endif
6729 /* Re-exec ourselves */
6730 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006731 /* Don't propagate SIG_IGN to the child */
6732 if (SPECIAL_JOBSTOP_SIGS != 0)
6733 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006734 execv(bb_busybox_exec_path, argv);
6735 /* If they called chroot or otherwise made the binary no longer
6736 * executable, fall through */
6737 }
6738 }
6739#endif
6740
6741#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6742 skip:
6743#endif
6744 execvp_or_die(argv);
6745}
6746
6747/* Called after [v]fork() in run_pipe
6748 */
6749static void pseudo_exec(nommu_save_t *nommu_save,
6750 struct command *command,
6751 char **argv_expanded) NORETURN;
6752static void pseudo_exec(nommu_save_t *nommu_save,
6753 struct command *command,
6754 char **argv_expanded)
6755{
6756 if (command->argv) {
6757 pseudo_exec_argv(nommu_save, command->argv,
6758 command->assignment_cnt, argv_expanded);
6759 }
6760
6761 if (command->group) {
6762 /* Cases when we are here:
6763 * ( list )
6764 * { list } &
6765 * ... | ( list ) | ...
6766 * ... | { list } | ...
6767 */
6768#if BB_MMU
6769 int rcode;
6770 debug_printf_exec("pseudo_exec: run_list\n");
6771 reset_traps_to_defaults();
6772 rcode = run_list(command->group);
6773 /* OK to leak memory by not calling free_pipe_list,
6774 * since this process is about to exit */
6775 _exit(rcode);
6776#else
6777 re_execute_shell(&nommu_save->argv_from_re_execing,
6778 command->group_as_string,
6779 G.global_argv[0],
6780 G.global_argv + 1,
6781 NULL);
6782#endif
6783 }
6784
6785 /* Case when we are here: ... | >file */
6786 debug_printf_exec("pseudo_exec'ed null command\n");
6787 _exit(EXIT_SUCCESS);
6788}
6789
6790#if ENABLE_HUSH_JOB
6791static const char *get_cmdtext(struct pipe *pi)
6792{
6793 char **argv;
6794 char *p;
6795 int len;
6796
6797 /* This is subtle. ->cmdtext is created only on first backgrounding.
6798 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6799 * On subsequent bg argv is trashed, but we won't use it */
6800 if (pi->cmdtext)
6801 return pi->cmdtext;
6802 argv = pi->cmds[0].argv;
6803 if (!argv || !argv[0]) {
6804 pi->cmdtext = xzalloc(1);
6805 return pi->cmdtext;
6806 }
6807
6808 len = 0;
6809 do {
6810 len += strlen(*argv) + 1;
6811 } while (*++argv);
6812 p = xmalloc(len);
6813 pi->cmdtext = p;
6814 argv = pi->cmds[0].argv;
6815 do {
6816 len = strlen(*argv);
6817 memcpy(p, *argv, len);
6818 p += len;
6819 *p++ = ' ';
6820 } while (*++argv);
6821 p[-1] = '\0';
6822 return pi->cmdtext;
6823}
6824
6825static void insert_bg_job(struct pipe *pi)
6826{
6827 struct pipe *job, **jobp;
6828 int i;
6829
6830 /* Linear search for the ID of the job to use */
6831 pi->jobid = 1;
6832 for (job = G.job_list; job; job = job->next)
6833 if (job->jobid >= pi->jobid)
6834 pi->jobid = job->jobid + 1;
6835
6836 /* Add job to the list of running jobs */
6837 jobp = &G.job_list;
6838 while ((job = *jobp) != NULL)
6839 jobp = &job->next;
6840 job = *jobp = xmalloc(sizeof(*job));
6841
6842 *job = *pi; /* physical copy */
6843 job->next = NULL;
6844 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6845 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6846 for (i = 0; i < pi->num_cmds; i++) {
6847 job->cmds[i].pid = pi->cmds[i].pid;
6848 /* all other fields are not used and stay zero */
6849 }
6850 job->cmdtext = xstrdup(get_cmdtext(pi));
6851
6852 if (G_interactive_fd)
6853 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6854 G.last_jobid = job->jobid;
6855}
6856
6857static void remove_bg_job(struct pipe *pi)
6858{
6859 struct pipe *prev_pipe;
6860
6861 if (pi == G.job_list) {
6862 G.job_list = pi->next;
6863 } else {
6864 prev_pipe = G.job_list;
6865 while (prev_pipe->next != pi)
6866 prev_pipe = prev_pipe->next;
6867 prev_pipe->next = pi->next;
6868 }
6869 if (G.job_list)
6870 G.last_jobid = G.job_list->jobid;
6871 else
6872 G.last_jobid = 0;
6873}
6874
6875/* Remove a backgrounded job */
6876static void delete_finished_bg_job(struct pipe *pi)
6877{
6878 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006879 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006880}
6881#endif /* JOB */
6882
6883/* Check to see if any processes have exited -- if they
6884 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006885static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006886{
6887 int attributes;
6888 int status;
6889#if ENABLE_HUSH_JOB
6890 struct pipe *pi;
6891#endif
6892 pid_t childpid;
6893 int rcode = 0;
6894
6895 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6896
6897 attributes = WUNTRACED;
6898 if (fg_pipe == NULL)
6899 attributes |= WNOHANG;
6900
6901 errno = 0;
6902#if ENABLE_HUSH_FAST
6903 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6904//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6905//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6906 /* There was neither fork nor SIGCHLD since last waitpid */
6907 /* Avoid doing waitpid syscall if possible */
6908 if (!G.we_have_children) {
6909 errno = ECHILD;
6910 return -1;
6911 }
6912 if (fg_pipe == NULL) { /* is WNOHANG set? */
6913 /* We have children, but they did not exit
6914 * or stop yet (we saw no SIGCHLD) */
6915 return 0;
6916 }
6917 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6918 }
6919#endif
6920
6921/* Do we do this right?
6922 * bash-3.00# sleep 20 | false
6923 * <ctrl-Z pressed>
6924 * [3]+ Stopped sleep 20 | false
6925 * bash-3.00# echo $?
6926 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6927 * [hush 1.14.0: yes we do it right]
6928 */
6929 wait_more:
6930 while (1) {
6931 int i;
6932 int dead;
6933
6934#if ENABLE_HUSH_FAST
6935 i = G.count_SIGCHLD;
6936#endif
6937 childpid = waitpid(-1, &status, attributes);
6938 if (childpid <= 0) {
6939 if (childpid && errno != ECHILD)
6940 bb_perror_msg("waitpid");
6941#if ENABLE_HUSH_FAST
6942 else { /* Until next SIGCHLD, waitpid's are useless */
6943 G.we_have_children = (childpid == 0);
6944 G.handled_SIGCHLD = i;
6945//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6946 }
6947#endif
6948 break;
6949 }
6950 dead = WIFEXITED(status) || WIFSIGNALED(status);
6951
6952#if DEBUG_JOBS
6953 if (WIFSTOPPED(status))
6954 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6955 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6956 if (WIFSIGNALED(status))
6957 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6958 childpid, WTERMSIG(status), WEXITSTATUS(status));
6959 if (WIFEXITED(status))
6960 debug_printf_jobs("pid %d exited, exitcode %d\n",
6961 childpid, WEXITSTATUS(status));
6962#endif
6963 /* Were we asked to wait for fg pipe? */
6964 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006965 i = fg_pipe->num_cmds;
6966 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006967 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6968 if (fg_pipe->cmds[i].pid != childpid)
6969 continue;
6970 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006971 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006972 fg_pipe->cmds[i].pid = 0;
6973 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006974 ex = WEXITSTATUS(status);
6975 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006976 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006977 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6978 */
6979 if (WIFSIGNALED(status)) {
6980 int sig = WTERMSIG(status);
6981 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006982 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
Denys Vlasenkod60752f2015-10-07 22:42:45 +02006983 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006984 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006985 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6986 * Maybe we need to use sig | 128? */
6987 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006988 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006989 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006990 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006991 fg_pipe->stopped_cmds++;
6992 }
6993 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6994 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006995 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006996 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006997 i = fg_pipe->num_cmds;
6998 while (--i >= 0) {
6999 rcode = fg_pipe->cmds[i].cmd_exitcode;
7000 /* usually last process gives overall exitstatus,
7001 * but with "set -o pipefail", last *failed* process does */
7002 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7003 break;
7004 }
7005 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007006/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7007 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7008 * and "killall -STOP cat" */
7009 if (G_interactive_fd) {
7010#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01007011 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007012 insert_bg_job(fg_pipe);
7013#endif
7014 return rcode;
7015 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01007016 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007017 return rcode;
7018 }
7019 /* There are still running processes in the fg pipe */
7020 goto wait_more; /* do waitpid again */
7021 }
7022 /* it wasnt fg_pipe, look for process in bg pipes */
7023 }
7024
7025#if ENABLE_HUSH_JOB
7026 /* We asked to wait for bg or orphaned children */
7027 /* No need to remember exitcode in this case */
7028 for (pi = G.job_list; pi; pi = pi->next) {
7029 for (i = 0; i < pi->num_cmds; i++) {
7030 if (pi->cmds[i].pid == childpid)
7031 goto found_pi_and_prognum;
7032 }
7033 }
7034 /* Happens when shell is used as init process (init=/bin/sh) */
7035 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7036 continue; /* do waitpid again */
7037
7038 found_pi_and_prognum:
7039 if (dead) {
7040 /* child exited */
7041 pi->cmds[i].pid = 0;
7042 pi->alive_cmds--;
7043 if (!pi->alive_cmds) {
7044 if (G_interactive_fd)
7045 printf(JOB_STATUS_FORMAT, pi->jobid,
7046 "Done", pi->cmdtext);
7047 delete_finished_bg_job(pi);
7048 }
7049 } else {
7050 /* child stopped */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007051 pi->stopped_cmds++;
7052 }
7053#endif
7054 } /* while (waitpid succeeds)... */
7055
7056 return rcode;
7057}
7058
7059#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007060static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007061{
7062 pid_t p;
7063 int rcode = checkjobs(fg_pipe);
7064 if (G_saved_tty_pgrp) {
7065 /* Job finished, move the shell to the foreground */
7066 p = getpgrp(); /* our process group id */
7067 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7068 tcsetpgrp(G_interactive_fd, p);
7069 }
7070 return rcode;
7071}
7072#endif
7073
7074/* Start all the jobs, but don't wait for anything to finish.
7075 * See checkjobs().
7076 *
7077 * Return code is normally -1, when the caller has to wait for children
7078 * to finish to determine the exit status of the pipe. If the pipe
7079 * is a simple builtin command, however, the action is done by the
7080 * time run_pipe returns, and the exit code is provided as the
7081 * return value.
7082 *
7083 * Returns -1 only if started some children. IOW: we have to
7084 * mask out retvals of builtins etc with 0xff!
7085 *
7086 * The only case when we do not need to [v]fork is when the pipe
7087 * is single, non-backgrounded, non-subshell command. Examples:
7088 * cmd ; ... { list } ; ...
7089 * cmd && ... { list } && ...
7090 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007091 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007092 * or (if SH_STANDALONE) an applet, and we can run the { list }
7093 * with run_list. If it isn't one of these, we fork and exec cmd.
7094 *
7095 * Cases when we must fork:
7096 * non-single: cmd | cmd
7097 * backgrounded: cmd & { list } &
7098 * subshell: ( list ) [&]
7099 */
7100#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01007101#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007102 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7103#endif
7104static int redirect_and_varexp_helper(char ***new_env_p,
7105 struct variable **old_vars_p,
7106 struct command *command,
7107 int squirrel[3],
7108 char **argv_expanded)
7109{
7110 /* setup_redirects acts on file descriptors, not FILEs.
7111 * This is perfect for work that comes after exec().
7112 * Is it really safe for inline use? Experimentally,
7113 * things seem to work. */
7114 int rcode = setup_redirects(command, squirrel);
7115 if (rcode == 0) {
7116 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7117 *new_env_p = new_env;
7118 dump_cmd_in_x_mode(new_env);
7119 dump_cmd_in_x_mode(argv_expanded);
7120 if (old_vars_p)
7121 *old_vars_p = set_vars_and_save_old(new_env);
7122 }
7123 return rcode;
7124}
7125static NOINLINE int run_pipe(struct pipe *pi)
7126{
7127 static const char *const null_ptr = NULL;
7128
7129 int cmd_no;
7130 int next_infd;
7131 struct command *command;
7132 char **argv_expanded;
7133 char **argv;
7134 /* it is not always needed, but we aim to smaller code */
7135 int squirrel[] = { -1, -1, -1 };
7136 int rcode;
7137
7138 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7139 debug_enter();
7140
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007141 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7142 * Result should be 3 lines: q w e, qwe, q w e
7143 */
7144 G.ifs = get_local_var_value("IFS");
7145 if (!G.ifs)
7146 G.ifs = defifs;
7147
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007148 IF_HUSH_JOB(pi->pgrp = -1;)
7149 pi->stopped_cmds = 0;
7150 command = &pi->cmds[0];
7151 argv_expanded = NULL;
7152
7153 if (pi->num_cmds != 1
7154 || pi->followup == PIPE_BG
7155 || command->cmd_type == CMD_SUBSHELL
7156 ) {
7157 goto must_fork;
7158 }
7159
7160 pi->alive_cmds = 1;
7161
7162 debug_printf_exec(": group:%p argv:'%s'\n",
7163 command->group, command->argv ? command->argv[0] : "NONE");
7164
7165 if (command->group) {
7166#if ENABLE_HUSH_FUNCTIONS
7167 if (command->cmd_type == CMD_FUNCDEF) {
7168 /* "executing" func () { list } */
7169 struct function *funcp;
7170
7171 funcp = new_function(command->argv[0]);
7172 /* funcp->name is already set to argv[0] */
7173 funcp->body = command->group;
7174# if !BB_MMU
7175 funcp->body_as_string = command->group_as_string;
7176 command->group_as_string = NULL;
7177# endif
7178 command->group = NULL;
7179 command->argv[0] = NULL;
7180 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7181 funcp->parent_cmd = command;
7182 command->child_func = funcp;
7183
7184 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7185 debug_leave();
7186 return EXIT_SUCCESS;
7187 }
7188#endif
7189 /* { list } */
7190 debug_printf("non-subshell group\n");
7191 rcode = 1; /* exitcode if redir failed */
7192 if (setup_redirects(command, squirrel) == 0) {
7193 debug_printf_exec(": run_list\n");
7194 rcode = run_list(command->group) & 0xff;
7195 }
7196 restore_redirects(squirrel);
7197 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7198 debug_leave();
7199 debug_printf_exec("run_pipe: return %d\n", rcode);
7200 return rcode;
7201 }
7202
7203 argv = command->argv ? command->argv : (char **) &null_ptr;
7204 {
7205 const struct built_in_command *x;
7206#if ENABLE_HUSH_FUNCTIONS
7207 const struct function *funcp;
7208#else
7209 enum { funcp = 0 };
7210#endif
7211 char **new_env = NULL;
7212 struct variable *old_vars = NULL;
7213
7214 if (argv[command->assignment_cnt] == NULL) {
7215 /* Assignments, but no command */
7216 /* Ensure redirects take effect (that is, create files).
7217 * Try "a=t >file" */
7218#if 0 /* A few cases in testsuite fail with this code. FIXME */
7219 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7220 /* Set shell variables */
7221 if (new_env) {
7222 argv = new_env;
7223 while (*argv) {
7224 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7225 /* Do we need to flag set_local_var() errors?
7226 * "assignment to readonly var" and "putenv error"
7227 */
7228 argv++;
7229 }
7230 }
7231 /* Redirect error sets $? to 1. Otherwise,
7232 * if evaluating assignment value set $?, retain it.
7233 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7234 if (rcode == 0)
7235 rcode = G.last_exitcode;
7236 /* Exit, _skipping_ variable restoring code: */
7237 goto clean_up_and_ret0;
7238
7239#else /* Older, bigger, but more correct code */
7240
7241 rcode = setup_redirects(command, squirrel);
7242 restore_redirects(squirrel);
7243 /* Set shell variables */
7244 if (G_x_mode)
7245 bb_putchar_stderr('+');
7246 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007247 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007248 if (G_x_mode)
7249 fprintf(stderr, " %s", p);
7250 debug_printf_exec("set shell var:'%s'->'%s'\n",
7251 *argv, p);
7252 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7253 /* Do we need to flag set_local_var() errors?
7254 * "assignment to readonly var" and "putenv error"
7255 */
7256 argv++;
7257 }
7258 if (G_x_mode)
7259 bb_putchar_stderr('\n');
7260 /* Redirect error sets $? to 1. Otherwise,
7261 * if evaluating assignment value set $?, retain it.
7262 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7263 if (rcode == 0)
7264 rcode = G.last_exitcode;
7265 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7266 debug_leave();
7267 debug_printf_exec("run_pipe: return %d\n", rcode);
7268 return rcode;
7269#endif
7270 }
7271
7272 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007273#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007274 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007275 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007276 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007277#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007278 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007279 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7280 }
7281
7282 /* if someone gives us an empty string: `cmd with empty output` */
7283 if (!argv_expanded[0]) {
7284 free(argv_expanded);
7285 debug_leave();
7286 return G.last_exitcode;
7287 }
7288
7289 x = find_builtin(argv_expanded[0]);
7290#if ENABLE_HUSH_FUNCTIONS
7291 funcp = NULL;
7292 if (!x)
7293 funcp = find_function(argv_expanded[0]);
7294#endif
7295 if (x || funcp) {
7296 if (!funcp) {
7297 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7298 debug_printf("exec with redirects only\n");
7299 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007300 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007301 goto clean_up_and_ret1;
7302 }
7303 }
7304 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7305 if (rcode == 0) {
7306 if (!funcp) {
7307 debug_printf_exec(": builtin '%s' '%s'...\n",
7308 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007309 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007310 rcode = x->b_function(argv_expanded) & 0xff;
7311 fflush_all();
7312 }
7313#if ENABLE_HUSH_FUNCTIONS
7314 else {
7315# if ENABLE_HUSH_LOCAL
7316 struct variable **sv;
7317 sv = G.shadowed_vars_pp;
7318 G.shadowed_vars_pp = &old_vars;
7319# endif
7320 debug_printf_exec(": function '%s' '%s'...\n",
7321 funcp->name, argv_expanded[1]);
7322 rcode = run_function(funcp, argv_expanded) & 0xff;
7323# if ENABLE_HUSH_LOCAL
7324 G.shadowed_vars_pp = sv;
7325# endif
7326 }
7327#endif
7328 }
7329 clean_up_and_ret:
7330 unset_vars(new_env);
7331 add_vars(old_vars);
7332/* clean_up_and_ret0: */
7333 restore_redirects(squirrel);
7334 clean_up_and_ret1:
7335 free(argv_expanded);
7336 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7337 debug_leave();
7338 debug_printf_exec("run_pipe return %d\n", rcode);
7339 return rcode;
7340 }
7341
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007342 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007343 int n = find_applet_by_name(argv_expanded[0]);
7344 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7345 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7346 if (rcode == 0) {
7347 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7348 argv_expanded[0], argv_expanded[1]);
7349 rcode = run_nofork_applet(n, argv_expanded);
7350 }
7351 goto clean_up_and_ret;
7352 }
7353 }
7354 /* It is neither builtin nor applet. We must fork. */
7355 }
7356
7357 must_fork:
7358 /* NB: argv_expanded may already be created, and that
7359 * might include `cmd` runs! Do not rerun it! We *must*
7360 * use argv_expanded if it's non-NULL */
7361
7362 /* Going to fork a child per each pipe member */
7363 pi->alive_cmds = 0;
7364 next_infd = 0;
7365
7366 cmd_no = 0;
7367 while (cmd_no < pi->num_cmds) {
7368 struct fd_pair pipefds;
7369#if !BB_MMU
7370 volatile nommu_save_t nommu_save;
7371 nommu_save.new_env = NULL;
7372 nommu_save.old_vars = NULL;
7373 nommu_save.argv = NULL;
7374 nommu_save.argv_from_re_execing = NULL;
7375#endif
7376 command = &pi->cmds[cmd_no];
7377 cmd_no++;
7378 if (command->argv) {
7379 debug_printf_exec(": pipe member '%s' '%s'...\n",
7380 command->argv[0], command->argv[1]);
7381 } else {
7382 debug_printf_exec(": pipe member with no argv\n");
7383 }
7384
7385 /* pipes are inserted between pairs of commands */
7386 pipefds.rd = 0;
7387 pipefds.wr = 1;
7388 if (cmd_no < pi->num_cmds)
7389 xpiped_pair(pipefds);
7390
7391 command->pid = BB_MMU ? fork() : vfork();
7392 if (!command->pid) { /* child */
7393#if ENABLE_HUSH_JOB
7394 disable_restore_tty_pgrp_on_exit();
7395 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7396
7397 /* Every child adds itself to new process group
7398 * with pgid == pid_of_first_child_in_pipe */
7399 if (G.run_list_level == 1 && G_interactive_fd) {
7400 pid_t pgrp;
7401 pgrp = pi->pgrp;
7402 if (pgrp < 0) /* true for 1st process only */
7403 pgrp = getpid();
7404 if (setpgid(0, pgrp) == 0
7405 && pi->followup != PIPE_BG
7406 && G_saved_tty_pgrp /* we have ctty */
7407 ) {
7408 /* We do it in *every* child, not just first,
7409 * to avoid races */
7410 tcsetpgrp(G_interactive_fd, pgrp);
7411 }
7412 }
7413#endif
7414 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7415 /* 1st cmd in backgrounded pipe
7416 * should have its stdin /dev/null'ed */
7417 close(0);
7418 if (open(bb_dev_null, O_RDONLY))
7419 xopen("/", O_RDONLY);
7420 } else {
7421 xmove_fd(next_infd, 0);
7422 }
7423 xmove_fd(pipefds.wr, 1);
7424 if (pipefds.rd > 1)
7425 close(pipefds.rd);
7426 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02007427 * and the pipe fd (fd#1) is available for dup'ing:
7428 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7429 * of cmd1 goes into pipe.
7430 */
7431 if (setup_redirects(command, NULL)) {
7432 /* Happens when redir file can't be opened:
7433 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7434 * FOO
7435 * hush: can't open '/qwe/rty': No such file or directory
7436 * BAZ
7437 * (echo BAR is not executed, it hits _exit(1) below)
7438 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007439 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007440 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007441
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007442 /* Stores to nommu_save list of env vars putenv'ed
7443 * (NOMMU, on MMU we don't need that) */
7444 /* cast away volatility... */
7445 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7446 /* pseudo_exec() does not return */
7447 }
7448
7449 /* parent or error */
7450#if ENABLE_HUSH_FAST
7451 G.count_SIGCHLD++;
7452//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7453#endif
7454 enable_restore_tty_pgrp_on_exit();
7455#if !BB_MMU
7456 /* Clean up after vforked child */
7457 free(nommu_save.argv);
7458 free(nommu_save.argv_from_re_execing);
7459 unset_vars(nommu_save.new_env);
7460 add_vars(nommu_save.old_vars);
7461#endif
7462 free(argv_expanded);
7463 argv_expanded = NULL;
7464 if (command->pid < 0) { /* [v]fork failed */
7465 /* Clearly indicate, was it fork or vfork */
7466 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7467 } else {
7468 pi->alive_cmds++;
7469#if ENABLE_HUSH_JOB
7470 /* Second and next children need to know pid of first one */
7471 if (pi->pgrp < 0)
7472 pi->pgrp = command->pid;
7473#endif
7474 }
7475
7476 if (cmd_no > 1)
7477 close(next_infd);
7478 if (cmd_no < pi->num_cmds)
7479 close(pipefds.wr);
7480 /* Pass read (output) pipe end to next iteration */
7481 next_infd = pipefds.rd;
7482 }
7483
7484 if (!pi->alive_cmds) {
7485 debug_leave();
7486 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7487 return 1;
7488 }
7489
7490 debug_leave();
7491 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7492 return -1;
7493}
7494
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007495/* NB: called by pseudo_exec, and therefore must not modify any
7496 * global data until exec/_exit (we can be a child after vfork!) */
7497static int run_list(struct pipe *pi)
7498{
7499#if ENABLE_HUSH_CASE
7500 char *case_word = NULL;
7501#endif
7502#if ENABLE_HUSH_LOOPS
7503 struct pipe *loop_top = NULL;
7504 char **for_lcur = NULL;
7505 char **for_list = NULL;
7506#endif
7507 smallint last_followup;
7508 smalluint rcode;
7509#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7510 smalluint cond_code = 0;
7511#else
7512 enum { cond_code = 0 };
7513#endif
7514#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007515 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007516 smallint last_rword; /* ditto */
7517#endif
7518
7519 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7520 debug_enter();
7521
7522#if ENABLE_HUSH_LOOPS
7523 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007524 {
7525 struct pipe *cpipe;
7526 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7527 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7528 continue;
7529 /* current word is FOR or IN (BOLD in comments below) */
7530 if (cpipe->next == NULL) {
7531 syntax_error("malformed for");
7532 debug_leave();
7533 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7534 return 1;
7535 }
7536 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7537 if (cpipe->next->res_word == RES_DO)
7538 continue;
7539 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7540 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7541 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7542 ) {
7543 syntax_error("malformed for");
7544 debug_leave();
7545 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7546 return 1;
7547 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007548 }
7549 }
7550#endif
7551
7552 /* Past this point, all code paths should jump to ret: label
7553 * in order to return, no direct "return" statements please.
7554 * This helps to ensure that no memory is leaked. */
7555
7556#if ENABLE_HUSH_JOB
7557 G.run_list_level++;
7558#endif
7559
7560#if HAS_KEYWORDS
7561 rword = RES_NONE;
7562 last_rword = RES_XXXX;
7563#endif
7564 last_followup = PIPE_SEQ;
7565 rcode = G.last_exitcode;
7566
7567 /* Go through list of pipes, (maybe) executing them. */
7568 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7569 if (G.flag_SIGINT)
7570 break;
7571
7572 IF_HAS_KEYWORDS(rword = pi->res_word;)
7573 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7574 rword, cond_code, last_rword);
7575#if ENABLE_HUSH_LOOPS
7576 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7577 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7578 ) {
7579 /* start of a loop: remember where loop starts */
7580 loop_top = pi;
7581 G.depth_of_loop++;
7582 }
7583#endif
7584 /* Still in the same "if...", "then..." or "do..." branch? */
7585 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7586 if ((rcode == 0 && last_followup == PIPE_OR)
7587 || (rcode != 0 && last_followup == PIPE_AND)
7588 ) {
7589 /* It is "<true> || CMD" or "<false> && CMD"
7590 * and we should not execute CMD */
7591 debug_printf_exec("skipped cmd because of || or &&\n");
7592 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02007593 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007594 }
7595 }
7596 last_followup = pi->followup;
7597 IF_HAS_KEYWORDS(last_rword = rword;)
7598#if ENABLE_HUSH_IF
7599 if (cond_code) {
7600 if (rword == RES_THEN) {
7601 /* if false; then ... fi has exitcode 0! */
7602 G.last_exitcode = rcode = EXIT_SUCCESS;
7603 /* "if <false> THEN cmd": skip cmd */
7604 continue;
7605 }
7606 } else {
7607 if (rword == RES_ELSE || rword == RES_ELIF) {
7608 /* "if <true> then ... ELSE/ELIF cmd":
7609 * skip cmd and all following ones */
7610 break;
7611 }
7612 }
7613#endif
7614#if ENABLE_HUSH_LOOPS
7615 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7616 if (!for_lcur) {
7617 /* first loop through for */
7618
7619 static const char encoded_dollar_at[] ALIGN1 = {
7620 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7621 }; /* encoded representation of "$@" */
7622 static const char *const encoded_dollar_at_argv[] = {
7623 encoded_dollar_at, NULL
7624 }; /* argv list with one element: "$@" */
7625 char **vals;
7626
7627 vals = (char**)encoded_dollar_at_argv;
7628 if (pi->next->res_word == RES_IN) {
7629 /* if no variable values after "in" we skip "for" */
7630 if (!pi->next->cmds[0].argv) {
7631 G.last_exitcode = rcode = EXIT_SUCCESS;
7632 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7633 break;
7634 }
7635 vals = pi->next->cmds[0].argv;
7636 } /* else: "for var; do..." -> assume "$@" list */
7637 /* create list of variable values */
7638 debug_print_strings("for_list made from", vals);
7639 for_list = expand_strvec_to_strvec(vals);
7640 for_lcur = for_list;
7641 debug_print_strings("for_list", for_list);
7642 }
7643 if (!*for_lcur) {
7644 /* "for" loop is over, clean up */
7645 free(for_list);
7646 for_list = NULL;
7647 for_lcur = NULL;
7648 break;
7649 }
7650 /* Insert next value from for_lcur */
7651 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7652 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7653 continue;
7654 }
7655 if (rword == RES_IN) {
7656 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7657 }
7658 if (rword == RES_DONE) {
7659 continue; /* "done" has no cmds too */
7660 }
7661#endif
7662#if ENABLE_HUSH_CASE
7663 if (rword == RES_CASE) {
7664 case_word = expand_strvec_to_string(pi->cmds->argv);
7665 continue;
7666 }
7667 if (rword == RES_MATCH) {
7668 char **argv;
7669
7670 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7671 break;
7672 /* all prev words didn't match, does this one match? */
7673 argv = pi->cmds->argv;
7674 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007675 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007676 /* TODO: which FNM_xxx flags to use? */
7677 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7678 free(pattern);
7679 if (cond_code == 0) { /* match! we will execute this branch */
7680 free(case_word); /* make future "word)" stop */
7681 case_word = NULL;
7682 break;
7683 }
7684 argv++;
7685 }
7686 continue;
7687 }
7688 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7689 if (cond_code != 0)
7690 continue; /* not matched yet, skip this pipe */
7691 }
7692#endif
7693 /* Just pressing <enter> in shell should check for jobs.
7694 * OTOH, in non-interactive shell this is useless
7695 * and only leads to extra job checks */
7696 if (pi->num_cmds == 0) {
7697 if (G_interactive_fd)
7698 goto check_jobs_and_continue;
7699 continue;
7700 }
7701
7702 /* After analyzing all keywords and conditions, we decided
7703 * to execute this pipe. NB: have to do checkjobs(NULL)
7704 * after run_pipe to collect any background children,
7705 * even if list execution is to be stopped. */
7706 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7707 {
7708 int r;
7709#if ENABLE_HUSH_LOOPS
7710 G.flag_break_continue = 0;
7711#endif
7712 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7713 if (r != -1) {
7714 /* We ran a builtin, function, or group.
7715 * rcode is already known
7716 * and we don't need to wait for anything. */
7717 G.last_exitcode = rcode;
7718 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007719 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007720#if ENABLE_HUSH_LOOPS
7721 /* Was it "break" or "continue"? */
7722 if (G.flag_break_continue) {
7723 smallint fbc = G.flag_break_continue;
7724 /* We might fall into outer *loop*,
7725 * don't want to break it too */
7726 if (loop_top) {
7727 G.depth_break_continue--;
7728 if (G.depth_break_continue == 0)
7729 G.flag_break_continue = 0;
7730 /* else: e.g. "continue 2" should *break* once, *then* continue */
7731 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denys Vlasenko3beab832013-04-07 18:16:58 +02007732 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7733 checkjobs(NULL);
7734 break;
7735 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007736 /* "continue": simulate end of loop */
7737 rword = RES_DONE;
7738 continue;
7739 }
7740#endif
7741#if ENABLE_HUSH_FUNCTIONS
7742 if (G.flag_return_in_progress == 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007743 checkjobs(NULL);
7744 break;
7745 }
7746#endif
7747 } else if (pi->followup == PIPE_BG) {
7748 /* What does bash do with attempts to background builtins? */
7749 /* even bash 3.2 doesn't do that well with nested bg:
7750 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7751 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007752 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007753#if ENABLE_HUSH_JOB
7754 if (G.run_list_level == 1)
7755 insert_bg_job(pi);
7756#endif
7757 /* Last command's pid goes to $! */
7758 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7759 G.last_exitcode = rcode = EXIT_SUCCESS;
7760 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7761 } else {
7762#if ENABLE_HUSH_JOB
7763 if (G.run_list_level == 1 && G_interactive_fd) {
7764 /* Waits for completion, then fg's main shell */
7765 rcode = checkjobs_and_fg_shell(pi);
7766 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007767 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007768 } else
7769#endif
7770 { /* This one just waits for completion */
7771 rcode = checkjobs(pi);
7772 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007773 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007774 }
7775 G.last_exitcode = rcode;
7776 }
7777 }
7778
7779 /* Analyze how result affects subsequent commands */
7780#if ENABLE_HUSH_IF
7781 if (rword == RES_IF || rword == RES_ELIF)
7782 cond_code = rcode;
7783#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02007784 check_jobs_and_continue:
7785 checkjobs(NULL);
7786 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007787#if ENABLE_HUSH_LOOPS
7788 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007789 if (pi->next
7790 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02007791 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007792 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007793 if (rword == RES_WHILE) {
7794 if (rcode) {
7795 /* "while false; do...done" - exitcode 0 */
7796 G.last_exitcode = rcode = EXIT_SUCCESS;
7797 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02007798 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007799 }
7800 }
7801 if (rword == RES_UNTIL) {
7802 if (!rcode) {
7803 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007804 break;
7805 }
7806 }
7807 }
7808#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007809 } /* for (pi) */
7810
7811#if ENABLE_HUSH_JOB
7812 G.run_list_level--;
7813#endif
7814#if ENABLE_HUSH_LOOPS
7815 if (loop_top)
7816 G.depth_of_loop--;
7817 free(for_list);
7818#endif
7819#if ENABLE_HUSH_CASE
7820 free(case_word);
7821#endif
7822 debug_leave();
7823 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7824 return rcode;
7825}
7826
7827/* Select which version we will use */
7828static int run_and_free_list(struct pipe *pi)
7829{
7830 int rcode = 0;
7831 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007832 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007833 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7834 rcode = run_list(pi);
7835 }
7836 /* free_pipe_list has the side effect of clearing memory.
7837 * In the long run that function can be merged with run_list,
7838 * but doing that now would hobble the debugging effort. */
7839 free_pipe_list(pi);
7840 debug_printf_exec("run_and_free_list return %d\n", rcode);
7841 return rcode;
7842}
7843
7844
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007845static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007846{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007847 sighandler_t old_handler;
7848 unsigned sig = 0;
7849 while ((mask >>= 1) != 0) {
7850 sig++;
7851 if (!(mask & 1))
7852 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007853 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007854 /* POSIX allows shell to re-enable SIGCHLD
7855 * even if it was SIG_IGN on entry.
7856 * Therefore we skip IGN check for it:
7857 */
7858 if (sig == SIGCHLD)
7859 continue;
7860 if (old_handler == SIG_IGN) {
7861 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007862 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007863 if (!G.traps)
7864 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7865 free(G.traps[sig]);
7866 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7867 }
7868 }
7869}
7870
7871/* Called a few times only (or even once if "sh -c") */
7872static void install_special_sighandlers(void)
7873{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007874 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007875
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007876 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007877 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007878 if (G_interactive_fd) {
7879 mask |= SPECIAL_INTERACTIVE_SIGS;
7880 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007881 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007882 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007883 /* Careful, do not re-install handlers we already installed */
7884 if (G.special_sig_mask != mask) {
7885 unsigned diff = mask & ~G.special_sig_mask;
7886 G.special_sig_mask = mask;
7887 install_sighandlers(diff);
7888 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007889}
7890
7891#if ENABLE_HUSH_JOB
7892/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007893/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007894static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007895{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007896 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007897
7898 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007899 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007900 + (1 << SIGILL ) * HUSH_DEBUG
7901 + (1 << SIGFPE ) * HUSH_DEBUG
7902 + (1 << SIGBUS ) * HUSH_DEBUG
7903 + (1 << SIGSEGV) * HUSH_DEBUG
7904 + (1 << SIGTRAP) * HUSH_DEBUG
7905 + (1 << SIGABRT)
7906 /* bash 3.2 seems to handle these just like 'fatal' ones */
7907 + (1 << SIGPIPE)
7908 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007909 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007910 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007911 * we never want to restore pgrp on exit, and this fn is not called
7912 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007913 /*+ (1 << SIGHUP )*/
7914 /*+ (1 << SIGTERM)*/
7915 /*+ (1 << SIGINT )*/
7916 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007917 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007918
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007919 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007920}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007921#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007922
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007923static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007924{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007925 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007926 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007927 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007928 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007929 break;
7930 case 'x':
7931 IF_HUSH_MODE_X(G_x_mode = state;)
7932 break;
7933 case 'o':
7934 if (!o_opt) {
7935 /* "set -+o" without parameter.
7936 * in bash, set -o produces this output:
7937 * pipefail off
7938 * and set +o:
7939 * set +o pipefail
7940 * We always use the second form.
7941 */
7942 const char *p = o_opt_strings;
7943 idx = 0;
7944 while (*p) {
7945 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7946 idx++;
7947 p += strlen(p) + 1;
7948 }
7949 break;
7950 }
7951 idx = index_in_strings(o_opt_strings, o_opt);
7952 if (idx >= 0) {
7953 G.o_opt[idx] = state;
7954 break;
7955 }
7956 default:
7957 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007958 }
7959 return EXIT_SUCCESS;
7960}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007961
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007962int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007963int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007964{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007965 enum {
7966 OPT_login = (1 << 0),
7967 };
7968 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00007969 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007970 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007971 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007972 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007973 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007974
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007975 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02007976 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007977 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02007978
Denys Vlasenko10c01312011-05-11 11:49:21 +02007979#if ENABLE_HUSH_FAST
7980 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7981#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007982#if !BB_MMU
7983 G.argv0_for_re_execing = argv[0];
7984#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007985 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007986 shell_ver = xzalloc(sizeof(*shell_ver));
7987 shell_ver->flg_export = 1;
7988 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007989 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007990 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007991 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007992 /* Create shell local variables from the values
7993 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007994 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007995 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007996 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007997 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007998 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007999 if (e) while (*e) {
8000 char *value = strchr(*e, '=');
8001 if (value) { /* paranoia */
8002 cur_var->next = xzalloc(sizeof(*cur_var));
8003 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00008004 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008005 cur_var->max_len = strlen(*e);
8006 cur_var->flg_export = 1;
8007 }
8008 e++;
8009 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02008010 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008011 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8012 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02008013
8014 /* Export PWD */
8015 set_pwd_var(/*exp:*/ 1);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008016
8017#if ENABLE_HUSH_BASH_COMPAT
8018 /* Set (but not export) HOSTNAME unless already set */
8019 if (!get_local_var_value("HOSTNAME")) {
8020 struct utsname uts;
8021 uname(&uts);
8022 set_local_var_from_halves("HOSTNAME", uts.nodename);
8023 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008024 /* bash also exports SHLVL and _,
8025 * and sets (but doesn't export) the following variables:
8026 * BASH=/bin/bash
8027 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8028 * BASH_VERSION='3.2.0(1)-release'
8029 * HOSTTYPE=i386
8030 * MACHTYPE=i386-pc-linux-gnu
8031 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02008032 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02008033 * EUID=<NNNNN>
8034 * UID=<NNNNN>
8035 * GROUPS=()
8036 * LINES=<NNN>
8037 * COLUMNS=<NNN>
8038 * BASH_ARGC=()
8039 * BASH_ARGV=()
8040 * BASH_LINENO=()
8041 * BASH_SOURCE=()
8042 * DIRSTACK=()
8043 * PIPESTATUS=([0]="0")
8044 * HISTFILE=/<xxx>/.bash_history
8045 * HISTFILESIZE=500
8046 * HISTSIZE=500
8047 * MAILCHECK=60
8048 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8049 * SHELL=/bin/bash
8050 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8051 * TERM=dumb
8052 * OPTERR=1
8053 * OPTIND=1
8054 * IFS=$' \t\n'
8055 * PS1='\s-\v\$ '
8056 * PS2='> '
8057 * PS4='+ '
8058 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008059#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02008060
Denis Vlasenko38f63192007-01-22 09:03:07 +00008061#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02008062 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008063#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02008064
Eric Andersen94ac2442001-05-22 19:05:18 +00008065 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00008066 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00008067
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008068 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00008069
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008070 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008071 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008072 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008073 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008074 * in order to intercept (more) signals.
8075 */
8076
8077 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008078 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008079 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008080 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008081 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008082 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008083#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00008084 "<:$:R:V:"
8085# if ENABLE_HUSH_FUNCTIONS
8086 "F:"
8087# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008088#endif
8089 );
8090 if (opt <= 0)
8091 break;
Eric Andersen25f27032001-04-26 23:22:31 +00008092 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008093 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008094 /* Possibilities:
8095 * sh ... -c 'script'
8096 * sh ... -c 'script' ARG0 [ARG1...]
8097 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01008098 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008099 * "" needs to be replaced with NULL
8100 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01008101 * Note: the form without ARG0 never happens:
8102 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008103 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02008104 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008105 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008106 G.root_ppid = getppid();
8107 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008108 G.global_argv = argv + optind;
8109 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008110 if (builtin_argc) {
8111 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8112 const struct built_in_command *x;
8113
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008114 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008115 x = find_builtin(optarg);
8116 if (x) { /* paranoia */
8117 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8118 G.global_argv += builtin_argc;
8119 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008120 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01008121 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008122 }
8123 goto final_return;
8124 }
8125 if (!G.global_argv[0]) {
8126 /* -c 'script' (no params): prevent empty $0 */
8127 G.global_argv--; /* points to argv[i] of 'script' */
8128 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02008129 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008130 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008131 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008132 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008133 goto final_return;
8134 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00008135 /* Well, we cannot just declare interactiveness,
8136 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008137 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008138 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008139 case 's':
8140 /* "-s" means "read from stdin", but this is how we always
8141 * operate, so simply do nothing here. */
8142 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008143 case 'l':
8144 flags |= OPT_login;
8145 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008146#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008147 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02008148 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008149 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008150 case '$': {
8151 unsigned long long empty_trap_mask;
8152
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008153 G.root_pid = bb_strtou(optarg, &optarg, 16);
8154 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02008155 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8156 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008157 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8158 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008159 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008160 optarg++;
8161 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008162 optarg++;
8163 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8164 if (empty_trap_mask != 0) {
8165 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008166 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008167 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8168 for (sig = 1; sig < NSIG; sig++) {
8169 if (empty_trap_mask & (1LL << sig)) {
8170 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008171 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008172 }
8173 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008174 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008175# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008176 optarg++;
8177 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008178# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008179 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008180 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008181 case 'R':
8182 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02008183 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008184 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00008185# if ENABLE_HUSH_FUNCTIONS
8186 case 'F': {
8187 struct function *funcp = new_function(optarg);
8188 /* funcp->name is already set to optarg */
8189 /* funcp->body is set to NULL. It's a special case. */
8190 funcp->body_as_string = argv[optind];
8191 optind++;
8192 break;
8193 }
8194# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008195#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008196 case 'n':
8197 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008198 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008199 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008200 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008201#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008202 fprintf(stderr, "Usage: sh [FILE]...\n"
8203 " or: sh -c command [args]...\n\n");
8204 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008205#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008206 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008207#endif
Eric Andersen25f27032001-04-26 23:22:31 +00008208 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008209 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008210
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008211 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8212 G.global_argc = argc - (optind - 1);
8213 G.global_argv = argv + (optind - 1);
8214 G.global_argv[0] = argv[0];
8215
Denys Vlasenkodea47882009-10-09 15:40:49 +02008216 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008217 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008218 G.root_ppid = getppid();
8219 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008220
8221 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008222 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008223 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008224 debug_printf("sourcing /etc/profile\n");
8225 input = fopen_for_read("/etc/profile");
8226 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008227 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008228 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008229 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008230 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008231 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008232 /* bash: after sourcing /etc/profile,
8233 * tries to source (in the given order):
8234 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008235 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008236 * bash also sources ~/.bash_logout on exit.
8237 * If called as sh, skips .bash_XXX files.
8238 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008239 }
8240
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008241 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008242 FILE *input;
8243 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008244 * "bash <script>" (which is never interactive (unless -i?))
8245 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008246 * If called as sh, does the same but with $ENV.
8247 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008248 G.global_argc--;
8249 G.global_argv++;
8250 debug_printf("running script '%s'\n", G.global_argv[0]);
8251 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008252 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008253 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008254 parse_and_run_file(input);
8255#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008256 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008257#endif
8258 goto final_return;
8259 }
8260
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008261 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008262 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008263 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008264
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008265 /* A shell is interactive if the '-i' flag was given,
8266 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008267 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008268 * no arguments remaining or the -s flag given
8269 * standard input is a terminal
8270 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008271 * Refer to Posix.2, the description of the 'sh' utility.
8272 */
8273#if ENABLE_HUSH_JOB
8274 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008275 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8276 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8277 if (G_saved_tty_pgrp < 0)
8278 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008279
8280 /* try to dup stdin to high fd#, >= 255 */
8281 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8282 if (G_interactive_fd < 0) {
8283 /* try to dup to any fd */
8284 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008285 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008286 /* give up */
8287 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008288 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008289 }
8290 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008291// TODO: track & disallow any attempts of user
8292// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008293 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008294 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008295 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008296 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008297
Mike Frysinger38478a62009-05-20 04:48:06 -04008298 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008299 /* If we were run as 'hush &', sleep until we are
8300 * in the foreground (tty pgrp == our pgrp).
8301 * If we get started under a job aware app (like bash),
8302 * make sure we are now in charge so we don't fight over
8303 * who gets the foreground */
8304 while (1) {
8305 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008306 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8307 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008308 break;
8309 /* send TTIN to ourself (should stop us) */
8310 kill(- shell_pgrp, SIGTTIN);
8311 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008312 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008313
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008314 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008315 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008316
Mike Frysinger38478a62009-05-20 04:48:06 -04008317 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008318 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008319 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008320 /* Put ourselves in our own process group
8321 * (bash, too, does this only if ctty is available) */
8322 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8323 /* Grab control of the terminal */
8324 tcsetpgrp(G_interactive_fd, getpid());
8325 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02008326 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008327
8328# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8329 {
8330 const char *hp = get_local_var_value("HISTFILE");
8331 if (!hp) {
8332 hp = get_local_var_value("HOME");
8333 if (hp)
8334 hp = concat_path_file(hp, ".hush_history");
8335 } else {
8336 hp = xstrdup(hp);
8337 }
8338 if (hp) {
8339 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008340 //set_local_var(xasprintf("HISTFILE=%s", ...));
8341 }
8342# if ENABLE_FEATURE_SH_HISTFILESIZE
8343 hp = get_local_var_value("HISTFILESIZE");
8344 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8345# endif
8346 }
8347# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008348 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008349 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008350 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008351#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008352 /* No job control compiled in, only prompt/line editing */
8353 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008354 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8355 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008356 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008357 G_interactive_fd = dup(STDIN_FILENO);
8358 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008359 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008360 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008361 }
8362 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008363 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008364 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008365 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008366 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008367#else
8368 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008369 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008370#endif
8371 /* bash:
8372 * if interactive but not a login shell, sources ~/.bashrc
8373 * (--norc turns this off, --rcfile <file> overrides)
8374 */
8375
8376 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008377 /* note: ash and hush share this string */
8378 printf("\n\n%s %s\n"
8379 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8380 "\n",
8381 bb_banner,
8382 "hush - the humble shell"
8383 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008384 }
8385
Denis Vlasenkof9375282009-04-05 19:13:39 +00008386 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008387
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008388 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008389 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008390}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008391
8392
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008393#if ENABLE_MSH
8394int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8395int msh_main(int argc, char **argv)
8396{
8397 //bb_error_msg("msh is deprecated, please use hush instead");
8398 return hush_main(argc, argv);
8399}
8400#endif
8401
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008402
8403/*
8404 * Built-ins
8405 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008406static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008407{
8408 return 0;
8409}
8410
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008411static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008412{
8413 int argc = 0;
8414 while (*argv) {
8415 argc++;
8416 argv++;
8417 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008418 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008419}
8420
8421static int FAST_FUNC builtin_test(char **argv)
8422{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008423 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008424}
8425
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008426static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008427{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008428 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008429}
8430
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008431#if ENABLE_PRINTF
8432static int FAST_FUNC builtin_printf(char **argv)
8433{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008434 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008435}
8436#endif
8437
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008438static char **skip_dash_dash(char **argv)
8439{
8440 argv++;
8441 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8442 argv++;
8443 return argv;
8444}
8445
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008446static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008447{
8448 int rcode = EXIT_SUCCESS;
8449
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008450 argv = skip_dash_dash(argv);
8451 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008452 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008453 /* bash:
8454 * eval "echo Hi; done" ("done" is syntax error):
8455 * "echo Hi" will not execute too.
8456 */
8457 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008458 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008459 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008460 }
8461 return rcode;
8462}
8463
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008464static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008465{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008466 const char *newdir;
8467
8468 argv = skip_dash_dash(argv);
8469 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008470 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008471 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008472 * bash says "bash: cd: HOME not set" and does nothing
8473 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008474 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008475 const char *home = get_local_var_value("HOME");
8476 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008477 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008478 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008479 /* Mimic bash message exactly */
8480 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008481 return EXIT_FAILURE;
8482 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008483 /* Read current dir (get_cwd(1) is inside) and set PWD.
8484 * Note: do not enforce exporting. If PWD was unset or unexported,
8485 * set it again, but do not export. bash does the same.
8486 */
8487 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008488 return EXIT_SUCCESS;
8489}
8490
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008491static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008492{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008493 argv = skip_dash_dash(argv);
8494 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008495 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008496
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008497 /* Careful: we can end up here after [v]fork. Do not restore
8498 * tty pgrp then, only top-level shell process does that */
8499 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8500 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8501
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008502 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008503 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008504 * and tcsetpgrp, and this is inherently racy.
8505 */
8506 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008507}
8508
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008509static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008510{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008511 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008512
8513 /* interactive bash:
8514 * # trap "echo EEE" EXIT
8515 * # exit
8516 * exit
8517 * There are stopped jobs.
8518 * (if there are _stopped_ jobs, running ones don't count)
8519 * # exit
8520 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01008521 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00008522 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008523 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008524 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008525
8526 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008527 argv = skip_dash_dash(argv);
8528 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008529 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008530 /* mimic bash: exit 123abc == exit 255 + error msg */
8531 xfunc_error_retval = 255;
8532 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008533 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008534}
8535
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008536static void print_escaped(const char *s)
8537{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008538 if (*s == '\'')
8539 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008540 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008541 const char *p = strchrnul(s, '\'');
8542 /* print 'xxxx', possibly just '' */
8543 printf("'%.*s'", (int)(p - s), s);
8544 if (*p == '\0')
8545 break;
8546 s = p;
8547 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008548 /* s points to '; print "'''...'''" */
8549 putchar('"');
8550 do putchar('\''); while (*++s == '\'');
8551 putchar('"');
8552 } while (*s);
8553}
8554
Denys Vlasenko295fef82009-06-03 12:47:26 +02008555#if !ENABLE_HUSH_LOCAL
8556#define helper_export_local(argv, exp, lvl) \
8557 helper_export_local(argv, exp)
8558#endif
8559static void helper_export_local(char **argv, int exp, int lvl)
8560{
8561 do {
8562 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008563 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008564
8565 /* So far we do not check that name is valid (TODO?) */
8566
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008567 if (*name_end == '\0') {
8568 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008569
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008570 vpp = get_ptr_to_local_var(name, name_end - name);
8571 var = vpp ? *vpp : NULL;
8572
Denys Vlasenko295fef82009-06-03 12:47:26 +02008573 if (exp == -1) { /* unexporting? */
8574 /* export -n NAME (without =VALUE) */
8575 if (var) {
8576 var->flg_export = 0;
8577 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8578 unsetenv(name);
8579 } /* else: export -n NOT_EXISTING_VAR: no-op */
8580 continue;
8581 }
8582 if (exp == 1) { /* exporting? */
8583 /* export NAME (without =VALUE) */
8584 if (var) {
8585 var->flg_export = 1;
8586 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8587 putenv(var->varstr);
8588 continue;
8589 }
8590 }
8591 /* Exporting non-existing variable.
8592 * bash does not put it in environment,
8593 * but remembers that it is exported,
8594 * and does put it in env when it is set later.
8595 * We just set it to "" and export. */
8596 /* Or, it's "local NAME" (without =VALUE).
8597 * bash sets the value to "". */
8598 name = xasprintf("%s=", name);
8599 } else {
8600 /* (Un)exporting/making local NAME=VALUE */
8601 name = xstrdup(name);
8602 }
8603 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8604 } while (*++argv);
8605}
8606
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008607static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008608{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008609 unsigned opt_unexport;
8610
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008611#if ENABLE_HUSH_EXPORT_N
8612 /* "!": do not abort on errors */
8613 opt_unexport = getopt32(argv, "!n");
8614 if (opt_unexport == (uint32_t)-1)
8615 return EXIT_FAILURE;
8616 argv += optind;
8617#else
8618 opt_unexport = 0;
8619 argv++;
8620#endif
8621
8622 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008623 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008624 if (e) {
8625 while (*e) {
8626#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008627 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008628#else
8629 /* ash emits: export VAR='VAL'
8630 * bash: declare -x VAR="VAL"
8631 * we follow ash example */
8632 const char *s = *e++;
8633 const char *p = strchr(s, '=');
8634
8635 if (!p) /* wtf? take next variable */
8636 continue;
8637 /* export var= */
8638 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008639 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008640 putchar('\n');
8641#endif
8642 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008643 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008644 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008645 return EXIT_SUCCESS;
8646 }
8647
Denys Vlasenko295fef82009-06-03 12:47:26 +02008648 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008649
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008650 return EXIT_SUCCESS;
8651}
8652
Denys Vlasenko295fef82009-06-03 12:47:26 +02008653#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008654static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008655{
8656 if (G.func_nest_level == 0) {
8657 bb_error_msg("%s: not in a function", argv[0]);
8658 return EXIT_FAILURE; /* bash compat */
8659 }
8660 helper_export_local(argv, 0, G.func_nest_level);
8661 return EXIT_SUCCESS;
8662}
8663#endif
8664
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008665static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008666{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008667 int sig;
8668 char *new_cmd;
8669
8670 if (!G.traps)
8671 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8672
8673 argv++;
8674 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008675 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008676 /* No args: print all trapped */
8677 for (i = 0; i < NSIG; ++i) {
8678 if (G.traps[i]) {
8679 printf("trap -- ");
8680 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008681 /* note: bash adds "SIG", but only if invoked
8682 * as "bash". If called as "sh", or if set -o posix,
8683 * then it prints short signal names.
8684 * We are printing short names: */
8685 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008686 }
8687 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008688 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008689 return EXIT_SUCCESS;
8690 }
8691
8692 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008693 /* If first arg is a number: reset all specified signals */
8694 sig = bb_strtou(*argv, NULL, 10);
8695 if (errno == 0) {
8696 int ret;
8697 process_sig_list:
8698 ret = EXIT_SUCCESS;
8699 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008700 sighandler_t handler;
8701
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008702 sig = get_signum(*argv++);
8703 if (sig < 0 || sig >= NSIG) {
8704 ret = EXIT_FAILURE;
8705 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008706 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008707 continue;
8708 }
8709
8710 free(G.traps[sig]);
8711 G.traps[sig] = xstrdup(new_cmd);
8712
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008713 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008714 get_signame(sig), sig, G.traps[sig]);
8715
8716 /* There is no signal for 0 (EXIT) */
8717 if (sig == 0)
8718 continue;
8719
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008720 if (new_cmd)
8721 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8722 else
8723 /* We are removing trap handler */
8724 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02008725 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008726 }
8727 return ret;
8728 }
8729
8730 if (!argv[1]) { /* no second arg */
8731 bb_error_msg("trap: invalid arguments");
8732 return EXIT_FAILURE;
8733 }
8734
8735 /* First arg is "-": reset all specified to default */
8736 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8737 /* Everything else: set arg as signal handler
8738 * (includes "" case, which ignores signal) */
8739 if (argv[0][0] == '-') {
8740 if (argv[0][1] == '\0') { /* "-" */
8741 /* new_cmd remains NULL: "reset these sigs" */
8742 goto reset_traps;
8743 }
8744 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8745 argv++;
8746 }
8747 /* else: "-something", no special meaning */
8748 }
8749 new_cmd = *argv;
8750 reset_traps:
8751 argv++;
8752 goto process_sig_list;
8753}
8754
Mike Frysinger93cadc22009-05-27 17:06:25 -04008755/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008756static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008757{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008758 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008759
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008760 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008761 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008762 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008763
8764 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008765 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008766 type = "an alias";*/
8767#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008768 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008769 type = "a function";
8770#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008771 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008772 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008773 else if ((path = find_in_path(*argv)) != NULL)
8774 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008775 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008776 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008777 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008778 continue;
8779 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008780
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008781 printf("%s is %s\n", *argv, type);
8782 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008783 }
8784
8785 return ret;
8786}
8787
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008788#if ENABLE_HUSH_JOB
8789/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008790static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008791{
8792 int i, jobnum;
8793 struct pipe *pi;
8794
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008795 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008796 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008797
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008798 /* If they gave us no args, assume they want the last backgrounded task */
8799 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008800 for (pi = G.job_list; pi; pi = pi->next) {
8801 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008802 goto found;
8803 }
8804 }
8805 bb_error_msg("%s: no current job", argv[0]);
8806 return EXIT_FAILURE;
8807 }
8808 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8809 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8810 return EXIT_FAILURE;
8811 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008812 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008813 if (pi->jobid == jobnum) {
8814 goto found;
8815 }
8816 }
8817 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8818 return EXIT_FAILURE;
8819 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008820 /* TODO: bash prints a string representation
8821 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008822 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008823 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008824 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008825 }
8826
8827 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008828 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8829 for (i = 0; i < pi->num_cmds; i++) {
8830 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008831 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008832 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008833
8834 i = kill(- pi->pgrp, SIGCONT);
8835 if (i < 0) {
8836 if (errno == ESRCH) {
8837 delete_finished_bg_job(pi);
8838 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008839 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008840 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008841 }
8842
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008843 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008844 remove_bg_job(pi);
8845 return checkjobs_and_fg_shell(pi);
8846 }
8847 return EXIT_SUCCESS;
8848}
8849#endif
8850
8851#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008852static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008853{
8854 const struct built_in_command *x;
8855
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008856 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008857 "Built-in commands:\n"
8858 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008859 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008860 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008861 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008862 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008863 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008864 return EXIT_SUCCESS;
8865}
8866#endif
8867
Denys Vlasenkoff463a82013-05-12 02:45:23 +02008868#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02008869static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
8870{
8871 show_history(G.line_input_state);
8872 return EXIT_SUCCESS;
8873}
8874#endif
8875
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008876#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008877static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008878{
8879 struct pipe *job;
8880 const char *status_string;
8881
Denis Vlasenko87a86552008-07-29 19:43:10 +00008882 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008883 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008884 status_string = "Stopped";
8885 else
8886 status_string = "Running";
8887
8888 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8889 }
8890 return EXIT_SUCCESS;
8891}
8892#endif
8893
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008894#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008895static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008896{
8897 void *p;
8898 unsigned long l;
8899
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008900# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008901 /* Optional. Reduces probability of false positives */
8902 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008903# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008904 /* Crude attempt to find where "free memory" starts,
8905 * sans fragmentation. */
8906 p = malloc(240);
8907 l = (unsigned long)p;
8908 free(p);
8909 p = malloc(3400);
8910 if (l < (unsigned long)p) l = (unsigned long)p;
8911 free(p);
8912
8913 if (!G.memleak_value)
8914 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008915
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008916 l -= G.memleak_value;
8917 if ((long)l < 0)
8918 l = 0;
8919 l /= 1024;
8920 if (l > 127)
8921 l = 127;
8922
8923 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8924 return l;
8925}
8926#endif
8927
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008928static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008929{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008930 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008931 return EXIT_SUCCESS;
8932}
8933
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008934/* Interruptibility of read builtin in bash
8935 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8936 *
8937 * Empty trap makes read ignore corresponding signal, for any signal.
8938 *
8939 * SIGINT:
8940 * - terminates non-interactive shell;
8941 * - interrupts read in interactive shell;
8942 * if it has non-empty trap:
8943 * - executes trap and returns to command prompt in interactive shell;
8944 * - executes trap and returns to read in non-interactive shell;
8945 * SIGTERM:
8946 * - is ignored (does not interrupt) read in interactive shell;
8947 * - terminates non-interactive shell;
8948 * if it has non-empty trap:
8949 * - executes trap and returns to read;
8950 * SIGHUP:
8951 * - terminates shell (regardless of interactivity);
8952 * if it has non-empty trap:
8953 * - executes trap and returns to read;
8954 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008955static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008956{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008957 const char *r;
8958 char *opt_n = NULL;
8959 char *opt_p = NULL;
8960 char *opt_t = NULL;
8961 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008962 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01008963 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008964
Denys Vlasenko03dad222010-01-12 23:29:57 +01008965 /* "!": do not abort on errors.
8966 * Option string must start with "sr" to match BUILTIN_READ_xxx
8967 */
8968 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8969 if (read_flags == (uint32_t)-1)
8970 return EXIT_FAILURE;
8971 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008972 ifs = get_local_var_value("IFS"); /* can be NULL */
8973
8974 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01008975 r = shell_builtin_read(set_local_var_from_halves,
8976 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008977 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01008978 read_flags,
8979 opt_n,
8980 opt_p,
8981 opt_t,
8982 opt_u
8983 );
8984
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008985 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008986 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008987 if (sig && sig != SIGINT)
8988 goto again;
8989 }
8990
Denys Vlasenko03dad222010-01-12 23:29:57 +01008991 if ((uintptr_t)r > 1) {
8992 bb_error_msg("%s", r);
8993 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008994 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008995
Denys Vlasenko03dad222010-01-12 23:29:57 +01008996 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008997}
8998
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008999/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9000 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009001 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009002 * set [-abCefhmnuvx] [-o option] [argument...]
9003 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009004 * set -- [argument...]
9005 * set -o
9006 * set +o
9007 * Implementations shall support the options in both their hyphen and
9008 * plus-sign forms. These options can also be specified as options to sh.
9009 * Examples:
9010 * Write out all variables and their values: set
9011 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9012 * Turn on the -x and -v options: set -xv
9013 * Unset all positional parameters: set --
9014 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9015 * Set the positional parameters to the expansion of x, even if x expands
9016 * with a leading '-' or '+': set -- $x
9017 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009018 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009019 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009020static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009021{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009022 int n;
9023 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009024 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009025
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009026 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009027 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009028 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009029 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009030 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00009031 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009032
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009033 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009034 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009035 ++argv;
9036 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009037 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00009038 if (arg[0] != '+' && arg[0] != '-')
9039 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009040 for (n = 1; arg[n]; ++n) {
9041 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00009042 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01009043 if (arg[n] == 'o' && argv[1])
9044 argv++;
9045 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009046 } while ((arg = *++argv) != NULL);
9047 /* Now argv[0] is 1st argument */
9048
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009049 if (arg == NULL)
9050 return EXIT_SUCCESS;
9051 set_argv:
9052
Denis Vlasenko424f79b2009-03-22 14:23:34 +00009053 /* NB: G.global_argv[0] ($0) is never freed/changed */
9054 g_argv = G.global_argv;
9055 if (G.global_args_malloced) {
9056 pp = g_argv;
9057 while (*++pp)
9058 free(*pp);
9059 g_argv[1] = NULL;
9060 } else {
9061 G.global_args_malloced = 1;
9062 pp = xzalloc(sizeof(pp[0]) * 2);
9063 pp[0] = g_argv[0]; /* retain $0 */
9064 g_argv = pp;
9065 }
9066 /* This realloc's G.global_argv */
9067 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9068
9069 n = 1;
9070 while (*++pp)
9071 n++;
9072 G.global_argc = n;
9073
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009074 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00009075
9076 /* Nothing known, so abort */
9077 error:
9078 bb_error_msg("set: %s: invalid option", arg);
9079 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009080}
9081
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009082static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009083{
9084 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009085 argv = skip_dash_dash(argv);
9086 if (argv[0]) {
9087 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009088 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009089 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00009090 if (G.global_args_malloced) {
9091 int m = 1;
9092 while (m <= n)
9093 free(G.global_argv[m++]);
9094 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009095 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00009096 memmove(&G.global_argv[1], &G.global_argv[n+1],
9097 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009098 return EXIT_SUCCESS;
9099 }
9100 return EXIT_FAILURE;
9101}
9102
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009103static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009104{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009105 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009106 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009107 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009108#if ENABLE_HUSH_FUNCTIONS
9109 smallint sv_flg;
9110#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009111
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009112 argv = skip_dash_dash(argv);
9113 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009114 if (!filename) {
9115 /* bash says: "bash: .: filename argument required" */
9116 return 2; /* bash compat */
9117 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009118 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009119 if (!strchr(filename, '/')) {
9120 arg_path = find_in_path(filename);
9121 if (arg_path)
9122 filename = arg_path;
9123 }
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009124 input = remember_FILE(fopen_or_warn(filename, "r"));
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009125 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009126 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009127 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009128 /* POSIX: non-interactive shell should abort here,
9129 * not merely fail. So far no one complained :)
9130 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009131 return EXIT_FAILURE;
9132 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009133
Mike Frysinger885b6f22009-04-18 21:04:25 +00009134#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009135 sv_flg = G.flag_return_in_progress;
9136 /* "we are inside sourced file, ok to use return" */
9137 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009138#endif
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009139 if (argv[1])
9140 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009141
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009142 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009143 fclose_and_forget(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009144
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009145 if (argv[1])
9146 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00009147#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009148 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009149#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009150
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009151 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009152}
9153
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009154static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009155{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009156 int rc;
9157 mode_t mask;
9158
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009159 rc = 1;
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009160 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009161 argv = skip_dash_dash(argv);
9162 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009163 mode_t old_mask = mask;
9164
Denys Vlasenko6283f982015-10-07 16:56:20 +02009165 /* numeric umasks are taken as-is */
9166 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9167 if (!isdigit(argv[0][0]))
9168 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009169 mask = bb_parse_mode(argv[0], mask);
Denys Vlasenko6283f982015-10-07 16:56:20 +02009170 if (!isdigit(argv[0][0]))
9171 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009172 if ((unsigned)mask > 0777) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009173 mask = old_mask;
9174 /* bash messages:
9175 * bash: umask: 'q': invalid symbolic mode operator
9176 * bash: umask: 999: octal number out of range
9177 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02009178 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009179 rc = 0;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009180 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009181 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009182 /* Mimic bash */
9183 printf("%04o\n", (unsigned) mask);
9184 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009185 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009186 umask(mask);
9187
9188 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009189}
9190
Mike Frysingerd690f682009-03-30 06:50:54 +00009191/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009192static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009193{
Mike Frysingerd690f682009-03-30 06:50:54 +00009194 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00009195 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00009196
Denis Vlasenko28e67962009-04-26 23:22:40 +00009197 /* "!": do not abort on errors */
9198 /* "+": stop at 1st non-option */
9199 opts = getopt32(argv, "!+vf");
9200 if (opts == (unsigned)-1)
9201 return EXIT_FAILURE;
9202 if (opts == 3) {
9203 bb_error_msg("unset: -v and -f are exclusive");
9204 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00009205 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00009206 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00009207
9208 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009209 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00009210 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009211 if (unset_local_var(*argv)) {
9212 /* unset <nonexistent_var> doesn't fail.
9213 * Error is when one tries to unset RO var.
9214 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00009215 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009216 }
Mike Frysingerd690f682009-03-30 06:50:54 +00009217 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00009218#if ENABLE_HUSH_FUNCTIONS
9219 else {
9220 unset_func(*argv);
9221 }
9222#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009223 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00009224 }
9225 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009226}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009227
Mike Frysinger56bdea12009-03-28 20:01:58 +00009228/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009229static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00009230{
9231 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009232 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009233
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009234 argv = skip_dash_dash(argv);
9235 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009236 /* Don't care about wait results */
9237 /* Note 1: must wait until there are no more children */
9238 /* Note 2: must be interruptible */
9239 /* Examples:
9240 * $ sleep 3 & sleep 6 & wait
9241 * [1] 30934 sleep 3
9242 * [2] 30935 sleep 6
9243 * [1] Done sleep 3
9244 * [2] Done sleep 6
9245 * $ sleep 3 & sleep 6 & wait
9246 * [1] 30936 sleep 3
9247 * [2] 30937 sleep 6
9248 * [1] Done sleep 3
9249 * ^C <-- after ~4 sec from keyboard
9250 * $
9251 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009252 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009253 int sig;
9254 sigset_t oldset, allsigs;
9255
9256 /* waitpid is not interruptible by SA_RESTARTed
9257 * signals which we use. Thus, this ugly dance:
9258 */
9259
9260 /* Make sure possible SIGCHLD is stored in kernel's
9261 * pending signal mask before we call waitpid.
9262 * Or else we may race with SIGCHLD, lose it,
9263 * and get stuck in sigwaitinfo...
9264 */
9265 sigfillset(&allsigs);
9266 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9267
9268 if (!sigisemptyset(&G.pending_set)) {
9269 /* Crap! we raced with some signal! */
9270 // sig = 0;
9271 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009272 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009273
9274 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9275 if (errno == ECHILD) {
9276 sigprocmask(SIG_SETMASK, &oldset, NULL);
9277 break;
9278 }
9279
9280 /* Wait for SIGCHLD or any other signal */
9281 //sig = sigwaitinfo(&allsigs, NULL);
9282 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9283 /* Note: sigsuspend invokes signal handler */
9284 sigsuspend(&oldset);
9285 restore:
9286 sigprocmask(SIG_SETMASK, &oldset, NULL);
9287
9288 /* So, did we get a signal? */
9289 //if (sig > 0)
9290 // raise(sig); /* run handler */
9291 sig = check_and_run_traps();
9292 if (sig /*&& sig != SIGCHLD - always true */) {
9293 /* see note 2 */
9294 ret = 128 + sig;
9295 break;
9296 }
9297 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009298 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009299 return ret;
9300 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009301
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009302 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009303 while (*argv) {
9304 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00009305 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009306 /* mimic bash message */
9307 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009308 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009309 }
9310 if (waitpid(pid, &status, 0) == pid) {
Denys Vlasenko85378cd2015-10-11 21:47:11 +02009311 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009312 if (WIFSIGNALED(status))
9313 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009314 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009315 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009316 ret = 127;
9317 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00009318 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009319 }
9320
9321 return ret;
9322}
9323
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009324#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9325static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9326{
9327 if (argv[1]) {
9328 def = bb_strtou(argv[1], NULL, 10);
9329 if (errno || def < def_min || argv[2]) {
9330 bb_error_msg("%s: bad arguments", argv[0]);
9331 def = UINT_MAX;
9332 }
9333 }
9334 return def;
9335}
9336#endif
9337
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009338#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009339static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009340{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009341 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009342 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009343 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +02009344 /* if we came from builtin_continue(), need to undo "= 1" */
9345 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009346 return EXIT_SUCCESS; /* bash compat */
9347 }
Denys Vlasenko49117b42016-07-21 14:40:08 +02009348 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009349
9350 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9351 if (depth == UINT_MAX)
9352 G.flag_break_continue = BC_BREAK;
9353 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009354 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009355
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009356 return EXIT_SUCCESS;
9357}
9358
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009359static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009360{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009361 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9362 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009363}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009364#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009365
9366#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009367static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009368{
9369 int rc;
9370
9371 if (G.flag_return_in_progress != -1) {
9372 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9373 return EXIT_FAILURE; /* bash compat */
9374 }
9375
9376 G.flag_return_in_progress = 1;
9377
9378 /* bash:
9379 * out of range: wraps around at 256, does not error out
9380 * non-numeric param:
9381 * f() { false; return qwe; }; f; echo $?
9382 * bash: return: qwe: numeric argument required <== we do this
9383 * 255 <== we also do this
9384 */
9385 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9386 return rc;
9387}
9388#endif