blob: b2c3a752e75f9a6e94bcc549c2bcfece3fa3f147 [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 Vlasenko03dad222010-01-12 23:29:57 +010094
Denys Vlasenko20704f02011-03-23 17:59:27 +010095#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
96#include "unicode.h"
Denys Vlasenko03dad222010-01-12 23:29:57 +010097#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000098#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000099#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +0200100#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200101# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +0200102#else
103# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200104#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000105#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200106# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000107#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000108
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200109/* Not every libc has sighandler_t. Fix it */
110typedef void (*hush_sighandler_t)(int);
111#define sighandler_t hush_sighandler_t
112
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 Vlasenko6b6af532011-03-08 10:24:17 +0100263//usage: "[-nx] [-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
Denis Vlasenko8412d792007-10-01 09:59:47 +0000327#endif
328
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000329/* Do we support ANY keywords? */
330#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000331# define HAS_KEYWORDS 1
332# define IF_HAS_KEYWORDS(...) __VA_ARGS__
333# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000334#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000335# define HAS_KEYWORDS 0
336# define IF_HAS_KEYWORDS(...)
337# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000338#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000339
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000340/* If you comment out one of these below, it will be #defined later
341 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000342#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000343/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000344#define debug_printf_parse(...) do {} while (0)
345#define debug_print_tree(a, b) do {} while (0)
346#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000347#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000348#define debug_printf_jobs(...) do {} while (0)
349#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200350#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000351#define debug_printf_glob(...) do {} while (0)
352#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000353#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000354#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000355
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000356#define ERR_PTR ((void*)(long)1)
357
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200358#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000359
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200360#define _SPECIAL_VARS_STR "_*@$!?#"
361#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
362#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200363#if ENABLE_HUSH_BASH_COMPAT
364/* Support / and // replace ops */
365/* Note that // is stored as \ in "encoded" string representation */
366# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
367# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
368# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
369#else
370# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
371# define VAR_SUBST_OPS "%#:-=+?"
372# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
373#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200374
375#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000376
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200377struct variable;
378
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000379static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
380
381/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000382 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000383 */
384#if !BB_MMU
385typedef struct nommu_save_t {
386 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200387 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000388 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000389 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000390} nommu_save_t;
391#endif
392
Denys Vlasenko9b782552010-09-08 13:33:26 +0200393enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000394 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000395#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000396 RES_IF ,
397 RES_THEN ,
398 RES_ELIF ,
399 RES_ELSE ,
400 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000401#endif
402#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000403 RES_FOR ,
404 RES_WHILE ,
405 RES_UNTIL ,
406 RES_DO ,
407 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000408#endif
409#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000410 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000411#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000412#if ENABLE_HUSH_CASE
413 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200414 /* three pseudo-keywords support contrived "case" syntax: */
415 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
416 RES_MATCH , /* "word)" */
417 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000418 RES_ESAC ,
419#endif
420 RES_XXXX ,
421 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200422};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000423
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000424typedef struct o_string {
425 char *data;
426 int length; /* position where data is appended */
427 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200428 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000429 /* At least some part of the string was inside '' or "",
430 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200431 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000432 smallint has_empty_slot;
433 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
434} o_string;
435enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200436 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
437 EXP_FLAG_GLOB = 0x2,
438 /* Protect newly added chars against globbing
439 * by prepending \ to *, ?, [, \ */
440 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
441};
442enum {
443 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000444 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200445 NOT_ASSIGNMENT = 2,
446 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
447 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000448};
449/* Used for initialization: o_string foo = NULL_O_STRING; */
450#define NULL_O_STRING { NULL }
451
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000452typedef struct in_str {
453 const char *p;
454 /* eof_flag=1: last char in ->p is really an EOF */
455 char eof_flag; /* meaningless if ->p == NULL */
456 char peek_buf[2];
457#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000458 smallint promptmode; /* 0: PS1, 1: PS2 */
459#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200460 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000461 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200462 int (*get) (struct in_str *) FAST_FUNC;
463 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000464} in_str;
465#define i_getch(input) ((input)->get(input))
466#define i_peek(input) ((input)->peek(input))
467
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200468/* The descrip member of this structure is only used to make
469 * debugging output pretty */
470static const struct {
471 int mode;
472 signed char default_fd;
473 char descrip[3];
474} redir_table[] = {
475 { O_RDONLY, 0, "<" },
476 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
477 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
478 { O_CREAT|O_RDWR, 1, "<>" },
479 { O_RDONLY, 0, "<<" },
480/* Should not be needed. Bogus default_fd helps in debugging */
481/* { O_RDONLY, 77, "<<" }, */
482};
483
Eric Andersen25f27032001-04-26 23:22:31 +0000484struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000485 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000486 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000487 int rd_fd; /* fd to redirect */
488 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
489 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000490 smallint rd_type; /* (enum redir_type) */
491 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000492 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200493 * bit 0: do we need to trim leading tabs?
494 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000495 */
Eric Andersen25f27032001-04-26 23:22:31 +0000496};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000497typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200498 REDIRECT_INPUT = 0,
499 REDIRECT_OVERWRITE = 1,
500 REDIRECT_APPEND = 2,
501 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000502 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200503 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000504
505 REDIRFD_CLOSE = -3,
506 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000507 REDIRFD_TO_FILE = -1,
508 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000509
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000510 HEREDOC_SKIPTABS = 1,
511 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000512} redir_type;
513
Eric Andersen25f27032001-04-26 23:22:31 +0000514
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000515struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000516 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000517 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000518 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200519 smallint cmd_type; /* CMD_xxx */
520#define CMD_NORMAL 0
521#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200522#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200523/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200524# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000525#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200526#if ENABLE_HUSH_FUNCTIONS
527# define CMD_FUNCDEF 3
528#endif
529
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100530 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200531 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
532 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000533#if !BB_MMU
534 char *group_as_string;
535#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000536#if ENABLE_HUSH_FUNCTIONS
537 struct function *child_func;
538/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200539 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000540 * When we execute "f1() {a;}" cmd, we create new function and clear
541 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200542 * When we execute "f1() {b;}", we notice that f1 exists,
543 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000544 * we put those fields back into cmd->xxx
545 * (struct function has ->parent_cmd ptr to facilitate that).
546 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
547 * Without this trick, loop would execute a;b;b;b;...
548 * instead of correct sequence a;b;a;b;...
549 * When command is freed, it severs the link
550 * (sets ->child_func->parent_cmd to NULL).
551 */
552#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000553 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000554/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
555 * and on execution these are substituted with their values.
556 * Substitution can make _several_ words out of one argv[n]!
557 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000558 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000559 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000560 struct redir_struct *redirects; /* I/O redirections */
561};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000562/* Is there anything in this command at all? */
563#define IS_NULL_CMD(cmd) \
564 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
565
Eric Andersen25f27032001-04-26 23:22:31 +0000566struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000567 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000568 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000569 int alive_cmds; /* number of commands running (not exited) */
570 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000571#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000572 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000573 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000574 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000575#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000576 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000577 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000578 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
579 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000580};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000581typedef enum pipe_style {
582 PIPE_SEQ = 1,
583 PIPE_AND = 2,
584 PIPE_OR = 3,
585 PIPE_BG = 4,
586} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000587/* Is there anything in this pipe at all? */
588#define IS_NULL_PIPE(pi) \
589 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000590
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000591/* This holds pointers to the various results of parsing */
592struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000593 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000594 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000595 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000596 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000597 /* last command in pipe (being constructed right now) */
598 struct command *command;
599 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000600 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000601#if !BB_MMU
602 o_string as_string;
603#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000604#if HAS_KEYWORDS
605 smallint ctx_res_w;
606 smallint ctx_inverted; /* "! cmd | cmd" */
607#if ENABLE_HUSH_CASE
608 smallint ctx_dsemicolon; /* ";;" seen */
609#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000610 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
611 int old_flag;
612 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000613 * example: "if pipe1; pipe2; then pipe3; fi"
614 * when we see "if" or "then", we malloc and copy current context,
615 * and make ->stack point to it. then we parse pipeN.
616 * when closing "then" / fi" / whatever is found,
617 * we move list_head into ->stack->command->group,
618 * copy ->stack into current context, and delete ->stack.
619 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000620 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000621 struct parse_context *stack;
622#endif
623};
624
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000625/* On program start, environ points to initial environment.
626 * putenv adds new pointers into it, unsetenv removes them.
627 * Neither of these (de)allocates the strings.
628 * setenv allocates new strings in malloc space and does putenv,
629 * and thus setenv is unusable (leaky) for shell's purposes */
630#define setenv(...) setenv_is_leaky_dont_use()
631struct variable {
632 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000633 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200634#if ENABLE_HUSH_LOCAL
635 unsigned func_nest_level;
636#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000637 int max_len; /* if > 0, name is part of initial env; else name is malloced */
638 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000639 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000640};
641
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000642enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000643 BC_BREAK = 1,
644 BC_CONTINUE = 2,
645};
646
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000647#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000648struct function {
649 struct function *next;
650 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000651 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000652 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200653# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000654 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200655# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000656};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000657#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000658
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000659
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100660/* set -/+o OPT support. (TODO: make it optional)
661 * bash supports the following opts:
662 * allexport off
663 * braceexpand on
664 * emacs on
665 * errexit off
666 * errtrace off
667 * functrace off
668 * hashall on
669 * histexpand off
670 * history on
671 * ignoreeof off
672 * interactive-comments on
673 * keyword off
674 * monitor on
675 * noclobber off
676 * noexec off
677 * noglob off
678 * nolog off
679 * notify off
680 * nounset off
681 * onecmd off
682 * physical off
683 * pipefail off
684 * posix off
685 * privileged off
686 * verbose off
687 * vi off
688 * xtrace off
689 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800690static const char o_opt_strings[] ALIGN1 =
691 "pipefail\0"
692 "noexec\0"
693#if ENABLE_HUSH_MODE_X
694 "xtrace\0"
695#endif
696 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100697enum {
698 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800699 OPT_O_NOEXEC,
700#if ENABLE_HUSH_MODE_X
701 OPT_O_XTRACE,
702#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100703 NUM_OPT_O
704};
705
706
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000707/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000708/* Sorted roughly by size (smaller offsets == smaller code) */
709struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000710 /* interactive_fd != 0 means we are an interactive shell.
711 * If we are, then saved_tty_pgrp can also be != 0, meaning
712 * that controlling tty is available. With saved_tty_pgrp == 0,
713 * job control still works, but terminal signals
714 * (^C, ^Z, ^Y, ^\) won't work at all, and background
715 * process groups can only be created with "cmd &".
716 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
717 * to give tty to the foreground process group,
718 * and will take it back when the group is stopped (^Z)
719 * or killed (^C).
720 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000721#if ENABLE_HUSH_INTERACTIVE
722 /* 'interactive_fd' is a fd# open to ctty, if we have one
723 * _AND_ if we decided to act interactively */
724 int interactive_fd;
725 const char *PS1;
726 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000727# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000728#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000729# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000730#endif
731#if ENABLE_FEATURE_EDITING
732 line_input_t *line_input_state;
733#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000734 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200735 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000736 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200737#if ENABLE_HUSH_RANDOM_SUPPORT
738 random_t random_gen;
739#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000740#if ENABLE_HUSH_JOB
741 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000742 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000743 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000744 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400745# define G_saved_tty_pgrp (G.saved_tty_pgrp)
746#else
747# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000748#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100749 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100750#if ENABLE_HUSH_MODE_X
751# define G_x_mode (G.o_opt[OPT_O_XTRACE])
752#else
753# define G_x_mode 0
754#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000755 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000756#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000757 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000758#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000759#if ENABLE_HUSH_FUNCTIONS
760 /* 0: outside of a function (or sourced file)
761 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000762 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000763 */
764 smallint flag_return_in_progress;
765#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000766 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000767 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000768 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000769 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000770 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000771 /* how many non-NULL argv's we have. NB: $# + 1 */
772 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000773 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000774#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000775 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000776#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000777#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000778 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000779 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000780#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000781 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000782 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200783 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200784 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000785#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000786 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200787# if ENABLE_HUSH_LOCAL
788 struct variable **shadowed_vars_pp;
789 unsigned func_nest_level;
790# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000791#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000792 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200793#if ENABLE_HUSH_FAST
794 unsigned count_SIGCHLD;
795 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200796 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200797#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +0200798 /* Which signals have non-DFL handler (even with no traps set)?
799 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200800 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200801 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200802 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200803 * Other than these two times, never modified.
804 */
805 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200806#if ENABLE_HUSH_JOB
807 unsigned fatal_sig_mask;
808#define G_fatal_sig_mask G.fatal_sig_mask
809#else
810#define G_fatal_sig_mask 0
811#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000812 char **traps; /* char *traps[NSIG] */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200813 sigset_t pending_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000814#if HUSH_DEBUG
815 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000816 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000817#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200818 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000819};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000820#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000821/* Not #defining name to G.name - this quickly gets unwieldy
822 * (too many defines). Also, I actually prefer to see when a variable
823 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000824#define INIT_G() do { \
825 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
826} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000827
828
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000829/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200830static int builtin_cd(char **argv) FAST_FUNC;
831static int builtin_echo(char **argv) FAST_FUNC;
832static int builtin_eval(char **argv) FAST_FUNC;
833static int builtin_exec(char **argv) FAST_FUNC;
834static int builtin_exit(char **argv) FAST_FUNC;
835static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000836#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200837static int builtin_fg_bg(char **argv) FAST_FUNC;
838static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000839#endif
840#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200841static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000842#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200843#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200844static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200845#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000846#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200847static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000848#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400849#if ENABLE_PRINTF
850static int builtin_printf(char **argv) FAST_FUNC;
851#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200852static int builtin_pwd(char **argv) FAST_FUNC;
853static int builtin_read(char **argv) FAST_FUNC;
854static int builtin_set(char **argv) FAST_FUNC;
855static int builtin_shift(char **argv) FAST_FUNC;
856static int builtin_source(char **argv) FAST_FUNC;
857static int builtin_test(char **argv) FAST_FUNC;
858static int builtin_trap(char **argv) FAST_FUNC;
859static int builtin_type(char **argv) FAST_FUNC;
860static int builtin_true(char **argv) FAST_FUNC;
861static int builtin_umask(char **argv) FAST_FUNC;
862static int builtin_unset(char **argv) FAST_FUNC;
863static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000864#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200865static int builtin_break(char **argv) FAST_FUNC;
866static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000867#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000868#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200869static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000870#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000871
872/* Table of built-in functions. They can be forked or not, depending on
873 * context: within pipes, they fork. As simple commands, they do not.
874 * When used in non-forking context, they can change global variables
875 * in the parent shell process. If forked, of course they cannot.
876 * For example, 'unset foo | whatever' will parse and run, but foo will
877 * still be set at the end. */
878struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100879 const char *b_cmd;
880 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000881#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100882 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200883# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000884#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200885# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000886#endif
887};
888
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200889static const struct built_in_command bltins1[] = {
890 BLTIN("." , builtin_source , "Run commands in a file"),
891 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000892#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200893 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000894#endif
895#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200896 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000897#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200898 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000899#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200900 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000901#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200902 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
903 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
904 BLTIN("exit" , builtin_exit , "Exit"),
905 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000906#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200907 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000908#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000909#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200910 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000911#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000912#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200913 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000914#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200915#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200916 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200917#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000918#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200919 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000920#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200921 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000922#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200923 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000924#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200925 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
926 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200927#if ENABLE_HUSH_BASH_COMPAT
928 BLTIN("source" , builtin_source , "Run commands in a file"),
929#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200930 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100931 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100932 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200933 BLTIN("umask" , builtin_umask , "Set file creation mask"),
934 BLTIN("unset" , builtin_unset , "Unset variables"),
935 BLTIN("wait" , builtin_wait , "Wait for process"),
936};
937/* For now, echo and test are unconditionally enabled.
938 * Maybe make it configurable? */
939static const struct built_in_command bltins2[] = {
940 BLTIN("[" , builtin_test , NULL),
941 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400942#if ENABLE_PRINTF
943 BLTIN("printf" , builtin_printf , NULL),
944#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200945 BLTIN("pwd" , builtin_pwd , NULL),
946 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000947};
948
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000949
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000950/* Debug printouts.
951 */
952#if HUSH_DEBUG
953/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100954# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000955# define debug_enter() (G.debug_indent++)
956# define debug_leave() (G.debug_indent--)
957#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200958# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000959# define debug_enter() ((void)0)
960# define debug_leave() ((void)0)
961#endif
962
963#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100964# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000965#endif
966
967#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100968# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000969#endif
970
971#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100972#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000973#endif
974
975#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100976# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000977#endif
978
979#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100980# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000981# define DEBUG_JOBS 1
982#else
983# define DEBUG_JOBS 0
984#endif
985
986#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100987# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000988# define DEBUG_EXPAND 1
989#else
990# define DEBUG_EXPAND 0
991#endif
992
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200993#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100994# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200995#endif
996
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000997#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100998# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000999# define DEBUG_GLOB 1
1000#else
1001# define DEBUG_GLOB 0
1002#endif
1003
1004#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001005# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001006#endif
1007
1008#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001009# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001010#endif
1011
1012#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001013# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001014# define DEBUG_CLEAN 1
1015#else
1016# define DEBUG_CLEAN 0
1017#endif
1018
1019#if DEBUG_EXPAND
1020static void debug_print_strings(const char *prefix, char **vv)
1021{
1022 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001023 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001024 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001025 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001026}
1027#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001028# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001029#endif
1030
1031
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001032/* Leak hunting. Use hush_leaktool.sh for post-processing.
1033 */
1034#if LEAK_HUNTING
1035static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001036{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001037 void *ptr = xmalloc((size + 0xff) & ~0xff);
1038 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1039 return ptr;
1040}
1041static void *xxrealloc(int lineno, void *ptr, size_t size)
1042{
1043 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1044 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1045 return ptr;
1046}
1047static char *xxstrdup(int lineno, const char *str)
1048{
1049 char *ptr = xstrdup(str);
1050 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1051 return ptr;
1052}
1053static void xxfree(void *ptr)
1054{
1055 fdprintf(2, "free %p\n", ptr);
1056 free(ptr);
1057}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001058# define xmalloc(s) xxmalloc(__LINE__, s)
1059# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1060# define xstrdup(s) xxstrdup(__LINE__, s)
1061# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001062#endif
1063
1064
1065/* Syntax and runtime errors. They always abort scripts.
1066 * In interactive use they usually discard unparsed and/or unexecuted commands
1067 * and return to the prompt.
1068 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1069 */
1070#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001071# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001072# define syntax_error(lineno, msg) syntax_error(msg)
1073# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1074# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1075# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1076# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001077#endif
1078
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001079static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001080{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001081 va_list p;
1082
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001083#if HUSH_DEBUG >= 2
1084 bb_error_msg("hush.c:%u", lineno);
1085#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001086 va_start(p, fmt);
1087 bb_verror_msg(fmt, p, NULL);
1088 va_end(p);
1089 if (!G_interactive_fd)
1090 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001091}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001092
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001093static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001094{
1095 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001096 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001097 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001098 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001099}
1100
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001101static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001102{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001103 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001104}
1105
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001106static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001107{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001108 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001109}
1110
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001111static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001112{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001113 char msg[2] = { ch, '\0' };
1114 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001115}
1116
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001117static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001118{
1119 char msg[2];
1120 msg[0] = ch;
1121 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001122 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001123}
1124
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001125#if HUSH_DEBUG < 2
1126# undef die_if_script
1127# undef syntax_error
1128# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001129# undef syntax_error_unterm_ch
1130# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001131# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001132#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001133# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001134# define syntax_error(msg) syntax_error(__LINE__, msg)
1135# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1136# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1137# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1138# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001139#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001140
Denis Vlasenko552433b2009-04-04 19:29:21 +00001141
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001142#if ENABLE_HUSH_INTERACTIVE
1143static void cmdedit_update_prompt(void);
1144#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001145# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001146#endif
1147
1148
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001149/* Utility functions
1150 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001151/* Replace each \x with x in place, return ptr past NUL. */
1152static char *unbackslash(char *src)
1153{
Denys Vlasenko71885402009-09-24 01:44:13 +02001154 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001155 while (1) {
1156 if (*src == '\\')
1157 src++;
1158 if ((*dst++ = *src++) == '\0')
1159 break;
1160 }
1161 return dst;
1162}
1163
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001164static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001165{
1166 int i;
1167 unsigned count1;
1168 unsigned count2;
1169 char **v;
1170
1171 v = strings;
1172 count1 = 0;
1173 if (v) {
1174 while (*v) {
1175 count1++;
1176 v++;
1177 }
1178 }
1179 count2 = 0;
1180 v = add;
1181 while (*v) {
1182 count2++;
1183 v++;
1184 }
1185 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1186 v[count1 + count2] = NULL;
1187 i = count2;
1188 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001189 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001190 return v;
1191}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001192#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001193static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1194{
1195 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1196 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1197 return ptr;
1198}
1199#define add_strings_to_strings(strings, add, need_to_dup) \
1200 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1201#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001202
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001203/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001204static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001205{
1206 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001207 v[0] = add;
1208 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001209 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001210}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001211#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001212static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1213{
1214 char **ptr = add_string_to_strings(strings, add);
1215 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1216 return ptr;
1217}
1218#define add_string_to_strings(strings, add) \
1219 xx_add_string_to_strings(__LINE__, strings, add)
1220#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001221
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001222static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001223{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001224 char **v;
1225
1226 if (!strings)
1227 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001228 v = strings;
1229 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001230 free(*v);
1231 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001232 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001233 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001234}
1235
Denis Vlasenko76d50412008-06-10 16:19:39 +00001236
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001237/* Helpers for setting new $n and restoring them back
1238 */
1239typedef struct save_arg_t {
1240 char *sv_argv0;
1241 char **sv_g_argv;
1242 int sv_g_argc;
1243 smallint sv_g_malloced;
1244} save_arg_t;
1245
1246static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1247{
1248 int n;
1249
1250 sv->sv_argv0 = argv[0];
1251 sv->sv_g_argv = G.global_argv;
1252 sv->sv_g_argc = G.global_argc;
1253 sv->sv_g_malloced = G.global_args_malloced;
1254
1255 argv[0] = G.global_argv[0]; /* retain $0 */
1256 G.global_argv = argv;
1257 G.global_args_malloced = 0;
1258
1259 n = 1;
1260 while (*++argv)
1261 n++;
1262 G.global_argc = n;
1263}
1264
1265static void restore_G_args(save_arg_t *sv, char **argv)
1266{
1267 char **pp;
1268
1269 if (G.global_args_malloced) {
1270 /* someone ran "set -- arg1 arg2 ...", undo */
1271 pp = G.global_argv;
1272 while (*++pp) /* note: does not free $0 */
1273 free(*pp);
1274 free(G.global_argv);
1275 }
1276 argv[0] = sv->sv_argv0;
1277 G.global_argv = sv->sv_g_argv;
1278 G.global_argc = sv->sv_g_argc;
1279 G.global_args_malloced = sv->sv_g_malloced;
1280}
1281
1282
Denis Vlasenkod5762932009-03-31 11:22:57 +00001283/* Basic theory of signal handling in shell
1284 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001285 * This does not describe what hush does, rather, it is current understanding
1286 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001287 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1288 *
1289 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1290 * is finished or backgrounded. It is the same in interactive and
1291 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001292 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001293 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001294 * backgrounds (i.e. stops) or kills all members of currently running
1295 * pipe.
1296 *
1297 * Wait builtin in interruptible by signals for which user trap is set
1298 * or by SIGINT in interactive shell.
1299 *
1300 * Trap handlers will execute even within trap handlers. (right?)
1301 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001302 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1303 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001304 *
1305 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001306 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001307 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001308 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001309 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001310 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001311 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001312 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001313 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001314 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001315 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001316 *
1317 * SIGQUIT: ignore
1318 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001319 * SIGHUP (interactive):
1320 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001321 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001322 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1323 * that all pipe members are stopped. Try this in bash:
1324 * while :; do :; done - ^Z does not background it
1325 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001326 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001327 * of the command line, show prompt. NB: ^C does not send SIGINT
1328 * to interactive shell while shell is waiting for a pipe,
1329 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001330 * Example 1: this waits 5 sec, but does not execute ls:
1331 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1332 * Example 2: this does not wait and does not execute ls:
1333 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1334 * Example 3: this does not wait 5 sec, but executes ls:
1335 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001336 * Example 4: this does not wait and does not execute ls:
1337 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001338 *
1339 * (What happens to signals which are IGN on shell start?)
1340 * (What happens with signal mask on shell start?)
1341 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001342 * Old implementation
1343 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001344 * We use in-kernel pending signal mask to determine which signals were sent.
1345 * We block all signals which we don't want to take action immediately,
1346 * i.e. we block all signals which need to have special handling as described
1347 * above, and all signals which have traps set.
1348 * After each pipe execution, we extract any pending signals via sigtimedwait()
1349 * and act on them.
1350 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001351 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001352 * sigset_t blocked_set: current blocked signal set
1353 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001354 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001355 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001356 * "trap 'cmd' SIGxxx":
1357 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001358 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001359 * unblock signals with special interactive handling
1360 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001361 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001362 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001363 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001364 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001365 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001366 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001367 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001368 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001369 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001370 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001371 * Standard says "When a subshell is entered, traps that are not being ignored
1372 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001373 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001374 *
1375 * Problem: the above approach makes it unwieldy to catch signals while
1376 * we are in read builtin, of while we read commands from stdin:
1377 * masked signals are not visible!
1378 *
1379 * New implementation
1380 * ==================
1381 * We record each signal we are interested in by installing signal handler
1382 * for them - a bit like emulating kernel pending signal mask in userspace.
1383 * We are interested in: signals which need to have special handling
1384 * as described above, and all signals which have traps set.
1385 * Signals are rocorded in pending_set.
1386 * After each pipe execution, we extract any pending signals
1387 * and act on them.
1388 *
1389 * unsigned special_sig_mask: a mask of shell-special signals.
1390 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1391 * char *traps[sig] if trap for sig is set (even if it's '').
1392 * sigset_t pending_set: set of sigs we received.
1393 *
1394 * "trap - SIGxxx":
1395 * if sig is in special_sig_mask, set handler back to:
1396 * record_pending_signo, or to IGN if it's a tty stop signal
1397 * if sig is in fatal_sig_mask, set handler back to sigexit.
1398 * else: set handler back to SIG_DFL
1399 * "trap 'cmd' SIGxxx":
1400 * set handler to record_pending_signo.
1401 * "trap '' SIGxxx":
1402 * set handler to SIG_IGN.
1403 * after [v]fork, if we plan to be a shell:
1404 * set signals with special interactive handling to SIG_DFL
1405 * (because child shell is not interactive),
1406 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1407 * after [v]fork, if we plan to exec:
1408 * POSIX says fork clears pending signal mask in child - no need to clear it.
1409 *
1410 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1411 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1412 *
1413 * Note (compat):
1414 * Standard says "When a subshell is entered, traps that are not being ignored
1415 * are set to the default actions". bash interprets it so that traps which
1416 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001417 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001418enum {
1419 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001420 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001421 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001422 | (1 << SIGHUP)
1423 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001424 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001425#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001426 | (1 << SIGTTIN)
1427 | (1 << SIGTTOU)
1428 | (1 << SIGTSTP)
1429#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001430 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001431};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001432
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001433static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001434{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001435 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001436#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001437 if (sig == SIGCHLD) {
1438 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001439//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 +02001440 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001441#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001442}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001443
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001444#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001445
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001446/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001447# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001448/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001449# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001450
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001451/* Restores tty foreground process group, and exits.
1452 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001453 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001454 * or called directly with -EXITCODE.
1455 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001456static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001457static void sigexit(int sig)
1458{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001459 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001460 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001461
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001462 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001463 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001464 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1465 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001466
1467 /* Not a signal, just exit */
1468 if (sig <= 0)
1469 _exit(- sig);
1470
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001471 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001472}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001473#else
1474
Denys Vlasenko8391c482010-05-22 17:50:43 +02001475# define disable_restore_tty_pgrp_on_exit() ((void)0)
1476# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001477
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001478#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001479
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001480static sighandler_t pick_sighandler(unsigned sig)
1481{
1482 sighandler_t handler = SIG_DFL;
1483 if (sig < sizeof(unsigned)*8) {
1484 unsigned sigmask = (1 << sig);
1485
1486#if ENABLE_HUSH_JOB
1487 /* sig is fatal? */
1488 if (G_fatal_sig_mask & sigmask)
1489 handler = sigexit;
1490#endif
1491 /* sig has special handling? */
1492 else if (G.special_sig_mask & sigmask)
1493 handler = record_pending_signo;
1494 /* TTIN/TTOU/TSTS can't be set to record_pending_signo
1495 * in order to ignore them: they will be raised
1496 * in an endless loop then when we try to do some
1497 * terminal ioctls! We do nave to _ignore_ these.
1498 */
1499 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1500 handler = SIG_IGN;
1501 }
1502 return handler;
1503}
1504
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001505/* Restores tty foreground process group, and exits. */
1506static void hush_exit(int exitcode) NORETURN;
1507static void hush_exit(int exitcode)
1508{
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001509 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001510 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1511 /* Prevent recursion:
1512 * trap "echo Hi; exit" EXIT; exit
1513 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001514 char *argv[3];
1515 /* argv[0] is unused */
1516 argv[1] = G.traps[0];
1517 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001518 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001519 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001520 * "trap" will still show it, if executed
1521 * in the handler */
1522 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001523 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001524
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001525#if ENABLE_FEATURE_CLEAN_UP
1526 {
1527 struct variable *cur_var;
1528 if (G.cwd != bb_msg_unknown)
1529 free((char*)G.cwd);
1530 cur_var = G.top_var;
1531 while (cur_var) {
1532 struct variable *tmp = cur_var;
1533 if (!cur_var->max_len)
1534 free(cur_var->varstr);
1535 cur_var = cur_var->next;
1536 free(tmp);
1537 }
1538 }
1539#endif
1540
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001541#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001542 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001543 sigexit(- (exitcode & 0xff));
1544#else
1545 exit(exitcode);
1546#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001547}
1548
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001549
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001550//TODO: return a mask of ALL handled sigs?
1551static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001552{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001553 int last_sig = 0;
1554
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001555 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001556 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001557
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001558 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001559 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001560 sig = 0;
1561 do {
1562 sig++;
1563 if (sigismember(&G.pending_set, sig)) {
1564 sigdelset(&G.pending_set, sig);
1565 goto got_sig;
1566 }
1567 } while (sig < NSIG);
1568 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001569 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001570 if (G.traps && G.traps[sig]) {
1571 if (G.traps[sig][0]) {
1572 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001573 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001574 char *argv[3];
1575 /* argv[0] is unused */
1576 argv[1] = G.traps[sig];
1577 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001578 save_rcode = G.last_exitcode;
1579 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001580 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001581 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001582 } /* else: "" trap, ignoring signal */
1583 continue;
1584 }
1585 /* not a trap: special action */
1586 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001587 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001588 /* Builtin was ^C'ed, make it look prettier: */
1589 bb_putchar('\n');
1590 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001591 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001592 break;
1593#if ENABLE_HUSH_JOB
1594 case SIGHUP: {
1595 struct pipe *job;
1596 /* bash is observed to signal whole process groups,
1597 * not individual processes */
1598 for (job = G.job_list; job; job = job->next) {
1599 if (job->pgrp <= 0)
1600 continue;
1601 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1602 if (kill(- job->pgrp, SIGHUP) == 0)
1603 kill(- job->pgrp, SIGCONT);
1604 }
1605 sigexit(SIGHUP);
1606 }
1607#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001608#if ENABLE_HUSH_FAST
1609 case SIGCHLD:
1610 G.count_SIGCHLD++;
1611//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1612 /* Note:
1613 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1614 * This simplifies wait builtin a bit.
1615 */
1616 break;
1617#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001618 default: /* ignored: */
1619 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001620 /* Note:
1621 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1622 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001623 * in interactive shell, because TERM is ignored.
1624 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001625 break;
1626 }
1627 }
1628 return last_sig;
1629}
1630
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001631
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001632static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001633{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001634 if (force || G.cwd == NULL) {
1635 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1636 * we must not try to free(bb_msg_unknown) */
1637 if (G.cwd == bb_msg_unknown)
1638 G.cwd = NULL;
1639 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1640 if (!G.cwd)
1641 G.cwd = bb_msg_unknown;
1642 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001643 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001644}
1645
Denis Vlasenko83506862007-11-23 13:11:42 +00001646
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001647/*
1648 * Shell and environment variable support
1649 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001650static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001651{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001652 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001653 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001654
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001655 pp = &G.top_var;
1656 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001657 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001658 return pp;
1659 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001660 }
1661 return NULL;
1662}
1663
Denys Vlasenko03dad222010-01-12 23:29:57 +01001664static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001665{
Denys Vlasenko29082232010-07-16 13:52:32 +02001666 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001667 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001668
1669 if (G.expanded_assignments) {
1670 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001671 while (*cpp) {
1672 char *cp = *cpp;
1673 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1674 return cp + len + 1;
1675 cpp++;
1676 }
1677 }
1678
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001679 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001680 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001681 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001682
Denys Vlasenkodea47882009-10-09 15:40:49 +02001683 if (strcmp(name, "PPID") == 0)
1684 return utoa(G.root_ppid);
1685 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001686#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001687 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001688 return utoa(next_random(&G.random_gen));
1689#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001690 return NULL;
1691}
1692
1693/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001694 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001695 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001696 * 0: do not change export flag
1697 * (if creating new variable, flag will be 0)
1698 * 1: set export flag and putenv the variable
1699 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001700 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001701 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001702#if !BB_MMU && ENABLE_HUSH_LOCAL
1703/* all params are used */
1704#elif BB_MMU && ENABLE_HUSH_LOCAL
1705#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1706 set_local_var(str, flg_export, local_lvl)
1707#elif BB_MMU && !ENABLE_HUSH_LOCAL
1708#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001709 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001710#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1711#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1712 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001713#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001714static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001715{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001716 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001717 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001718 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001719 int name_len;
1720
Denis Vlasenko950bd722009-04-21 11:23:56 +00001721 eq_sign = strchr(str, '=');
1722 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001723 free(str);
1724 return -1;
1725 }
1726
Denis Vlasenko950bd722009-04-21 11:23:56 +00001727 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001728 var_pp = &G.top_var;
1729 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001730 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001731 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001732 continue;
1733 }
1734 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001735 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001736#if !BB_MMU
1737 if (!flg_read_only)
1738#endif
1739 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001740 free(str);
1741 return -1;
1742 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001743 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001744 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1745 *eq_sign = '\0';
1746 unsetenv(str);
1747 *eq_sign = '=';
1748 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001749#if ENABLE_HUSH_LOCAL
1750 if (cur->func_nest_level < local_lvl) {
1751 /* New variable is declared as local,
1752 * and existing one is global, or local
1753 * from enclosing function.
1754 * Remove and save old one: */
1755 *var_pp = cur->next;
1756 cur->next = *G.shadowed_vars_pp;
1757 *G.shadowed_vars_pp = cur;
1758 /* bash 3.2.33(1) and exported vars:
1759 * # export z=z
1760 * # f() { local z=a; env | grep ^z; }
1761 * # f
1762 * z=a
1763 * # env | grep ^z
1764 * z=z
1765 */
1766 if (cur->flg_export)
1767 flg_export = 1;
1768 break;
1769 }
1770#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001771 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001772 free_and_exp:
1773 free(str);
1774 goto exp;
1775 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001776 if (cur->max_len != 0) {
1777 if (cur->max_len >= strlen(str)) {
1778 /* This one is from startup env, reuse space */
1779 strcpy(cur->varstr, str);
1780 goto free_and_exp;
1781 }
1782 } else {
1783 /* max_len == 0 signifies "malloced" var, which we can
1784 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001785 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001786 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001787 cur->max_len = 0;
1788 goto set_str_and_exp;
1789 }
1790
Denys Vlasenko295fef82009-06-03 12:47:26 +02001791 /* Not found - create new variable struct */
1792 cur = xzalloc(sizeof(*cur));
1793#if ENABLE_HUSH_LOCAL
1794 cur->func_nest_level = local_lvl;
1795#endif
1796 cur->next = *var_pp;
1797 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001798
1799 set_str_and_exp:
1800 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001801#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001802 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001803#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001804 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001805 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001806 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001807 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1808 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001809 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001810 if (flg_export == -1) {
1811 cur->flg_export = 0;
1812 /* unsetenv was already done */
1813 } else {
1814 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1815 return putenv(cur->varstr);
1816 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001817 }
1818 return 0;
1819}
1820
Denys Vlasenko6db47842009-09-05 20:15:17 +02001821/* Used at startup and after each cd */
1822static void set_pwd_var(int exp)
1823{
1824 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1825 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1826}
1827
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001828static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001829{
1830 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001831 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001832
1833 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001834 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001835 var_pp = &G.top_var;
1836 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001837 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1838 if (cur->flg_read_only) {
1839 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001840 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001841 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001842 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001843 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1844 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001845 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1846 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001847 if (!cur->max_len)
1848 free(cur->varstr);
1849 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001850 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001851 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001852 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001853 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001854 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001855}
1856
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001857static int unset_local_var(const char *name)
1858{
1859 return unset_local_var_len(name, strlen(name));
1860}
1861
1862static void unset_vars(char **strings)
1863{
1864 char **v;
1865
1866 if (!strings)
1867 return;
1868 v = strings;
1869 while (*v) {
1870 const char *eq = strchrnul(*v, '=');
1871 unset_local_var_len(*v, (int)(eq - *v));
1872 v++;
1873 }
1874 free(strings);
1875}
1876
Denys Vlasenko03dad222010-01-12 23:29:57 +01001877static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001878{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001879 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001880 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001881}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001882
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001883
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001884/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001885 * Helpers for "var1=val1 var2=val2 cmd" feature
1886 */
1887static void add_vars(struct variable *var)
1888{
1889 struct variable *next;
1890
1891 while (var) {
1892 next = var->next;
1893 var->next = G.top_var;
1894 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001895 if (var->flg_export) {
1896 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001897 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001898 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001899 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001900 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001901 var = next;
1902 }
1903}
1904
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001905static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001906{
1907 char **s;
1908 struct variable *old = NULL;
1909
1910 if (!strings)
1911 return old;
1912 s = strings;
1913 while (*s) {
1914 struct variable *var_p;
1915 struct variable **var_pp;
1916 char *eq;
1917
1918 eq = strchr(*s, '=');
1919 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001920 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001921 if (var_pp) {
1922 /* Remove variable from global linked list */
1923 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001924 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001925 *var_pp = var_p->next;
1926 /* Add it to returned list */
1927 var_p->next = old;
1928 old = var_p;
1929 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001930 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001931 }
1932 s++;
1933 }
1934 return old;
1935}
1936
1937
1938/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001939 * in_str support
1940 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001941static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001942{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001943 int ch = *i->p;
1944 if (ch != '\0') {
1945 i->p++;
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001946 i->last_char = ch;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001947 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001948 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001949 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001950}
1951
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001952static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001953{
1954 return *i->p;
1955}
1956
1957#if ENABLE_HUSH_INTERACTIVE
1958
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001959static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001960{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001961 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001962 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001963 if (G.PS1 == NULL)
1964 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001965 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001966 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001967 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001968 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001969 if (G.PS2 == NULL)
1970 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001971}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001972
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001973static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001974{
1975 const char *prompt_str;
1976 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001977 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1978 /* Set up the prompt */
1979 if (promptmode == 0) { /* PS1 */
1980 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001981 /* bash uses $PWD value, even if it is set by user.
1982 * It uses current dir only if PWD is unset.
1983 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001984 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001985 prompt_str = G.PS1;
1986 } else
1987 prompt_str = G.PS2;
1988 } else
1989 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001990 debug_printf("result '%s'\n", prompt_str);
1991 return prompt_str;
1992}
1993
1994static void get_user_input(struct in_str *i)
1995{
1996 int r;
1997 const char *prompt_str;
1998
1999 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002000# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002001 /* Enable command line editing only while a command line
2002 * is actually being read */
2003 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01002004 /* Unicode support should be activated even if LANG is set
2005 * _during_ shell execution, not only if it was set when
2006 * shell was started. Therefore, re-check LANG every time:
2007 */
2008 reinit_unicode(get_local_var_value("LANG"));
2009
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002010 G.flag_SIGINT = 0;
2011 /* buglet: SIGINT will not make new prompt to appear _at once_,
2012 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002013 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 +00002014 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002015 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002016 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002017 i->eof_flag = (r < 0);
2018 if (i->eof_flag) { /* EOF/error detected */
2019 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2020 G.user_input_buf[1] = '\0';
2021 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02002022# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002023 do {
2024 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002025 if (i->last_char == '\0' || i->last_char == '\n') {
2026 /* Why check_and_run_traps here? Try this interactively:
2027 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2028 * $ <[enter], repeatedly...>
2029 * Without check_and_run_traps, handler never runs.
2030 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002031 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002032 fputs(prompt_str, stdout);
2033 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002034 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002035 G.user_input_buf[0] = r = fgetc(i->file);
2036 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002037 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002038 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002039# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002040 i->p = G.user_input_buf;
2041}
2042
2043#endif /* INTERACTIVE */
2044
2045/* This is the magic location that prints prompts
2046 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002047static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002048{
2049 int ch;
2050
2051 /* If there is data waiting, eat it up */
2052 if (i->p && *i->p) {
2053#if ENABLE_HUSH_INTERACTIVE
2054 take_cached:
2055#endif
2056 ch = *i->p++;
2057 if (i->eof_flag && !*i->p)
2058 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002059 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002060 } else {
2061 /* need to double check i->file because we might be doing something
2062 * more complicated by now, like sourcing or substituting. */
2063#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002064 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002065 do {
2066 get_user_input(i);
2067 } while (!*i->p); /* need non-empty line */
2068 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002069 goto take_cached;
2070 }
2071#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00002072 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002073 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002074 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002075 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002076 return ch;
2077}
2078
Denis Vlasenko913a2012009-04-05 22:17:04 +00002079/* All callers guarantee this routine will never
2080 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002081 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002082static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002083{
2084 int ch;
2085 if (i->p && *i->p) {
2086 if (i->eof_flag && !i->p[1])
2087 return EOF;
2088 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002089 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002090 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002091 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002092 i->eof_flag = (ch == EOF);
2093 i->peek_buf[0] = ch;
2094 i->peek_buf[1] = '\0';
2095 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002096 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002097 return ch;
2098}
2099
2100static void setup_file_in_str(struct in_str *i, FILE *f)
2101{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002102 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002103 i->peek = file_peek;
2104 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002105 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002106 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002107 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002108}
2109
2110static void setup_string_in_str(struct in_str *i, const char *s)
2111{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002112 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002113 i->peek = static_peek;
2114 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002115 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002116 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002117 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002118}
2119
2120
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002121/*
2122 * o_string support
2123 */
2124#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002125
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002126static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002127{
2128 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002129 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002130 if (o->data)
2131 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002132}
2133
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002134static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002135{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002136 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002137 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002138}
2139
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002140static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2141{
2142 free(o->data);
2143}
2144
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002145static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002146{
2147 if (o->length + len > o->maxlen) {
2148 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2149 o->data = xrealloc(o->data, 1 + o->maxlen);
2150 }
2151}
2152
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002153static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002154{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002155 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2156 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002157 o->data[o->length] = ch;
2158 o->length++;
2159 o->data[o->length] = '\0';
2160}
2161
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002162static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002163{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002164 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002165 memcpy(&o->data[o->length], str, len);
2166 o->length += len;
2167 o->data[o->length] = '\0';
2168}
2169
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002170static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002171{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002172 o_addblock(o, str, strlen(str));
2173}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002174
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002175#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002176static void nommu_addchr(o_string *o, int ch)
2177{
2178 if (o)
2179 o_addchr(o, ch);
2180}
2181#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002182# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002183#endif
2184
2185static void o_addstr_with_NUL(o_string *o, const char *str)
2186{
2187 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002188}
2189
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002190/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002191 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002192 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2193 * Apparently, on unquoted $v bash still does globbing
2194 * ("v='*.txt'; echo $v" prints all .txt files),
2195 * but NOT brace expansion! Thus, there should be TWO independent
2196 * quoting mechanisms on $v expansion side: one protects
2197 * $v from brace expansion, and other additionally protects "$v" against globbing.
2198 * We have only second one.
2199 */
2200
Denys Vlasenko9e800222010-10-03 14:28:04 +02002201#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002202# define MAYBE_BRACES "{}"
2203#else
2204# define MAYBE_BRACES ""
2205#endif
2206
Eric Andersen25f27032001-04-26 23:22:31 +00002207/* My analysis of quoting semantics tells me that state information
2208 * is associated with a destination, not a source.
2209 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002210static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002211{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002212 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002213 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002214 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002215 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002216 o_grow_by(o, sz);
2217 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002218 o->data[o->length] = '\\';
2219 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002220 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002221 o->data[o->length] = ch;
2222 o->length++;
2223 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002224}
2225
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002226static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002227{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002228 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002229 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2230 && strchr("*?[\\" MAYBE_BRACES, ch)
2231 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002232 sz++;
2233 o->data[o->length] = '\\';
2234 o->length++;
2235 }
2236 o_grow_by(o, sz);
2237 o->data[o->length] = ch;
2238 o->length++;
2239 o->data[o->length] = '\0';
2240}
2241
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002242static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002243{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002244 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002245 char ch;
2246 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002247 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002248 if (ordinary_cnt > len) /* paranoia */
2249 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002250 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002251 if (ordinary_cnt == len)
2252 return;
2253 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002254 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002255
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002256 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002257 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002258 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002259 sz++;
2260 o->data[o->length] = '\\';
2261 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002262 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002263 o_grow_by(o, sz);
2264 o->data[o->length] = ch;
2265 o->length++;
2266 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002267 }
2268}
2269
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002270static void o_addQblock(o_string *o, const char *str, int len)
2271{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002272 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002273 o_addblock(o, str, len);
2274 return;
2275 }
2276 o_addqblock(o, str, len);
2277}
2278
Denys Vlasenko38292b62010-09-05 14:49:40 +02002279static void o_addQstr(o_string *o, const char *str)
2280{
2281 o_addQblock(o, str, strlen(str));
2282}
2283
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002284/* A special kind of o_string for $VAR and `cmd` expansion.
2285 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002286 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002287 * list[i] contains an INDEX (int!) into this string data.
2288 * It means that if list[] needs to grow, data needs to be moved higher up
2289 * but list[i]'s need not be modified.
2290 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002291 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002292 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2293 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002294#if DEBUG_EXPAND || DEBUG_GLOB
2295static void debug_print_list(const char *prefix, o_string *o, int n)
2296{
2297 char **list = (char**)o->data;
2298 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2299 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002300
2301 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002302 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 +02002303 prefix, list, n, string_start, o->length, o->maxlen,
2304 !!(o->o_expflags & EXP_FLAG_GLOB),
2305 o->has_quoted_part,
2306 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002307 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002308 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002309 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2310 o->data + (int)(uintptr_t)list[i] + string_start,
2311 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002312 i++;
2313 }
2314 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002315 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002316 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002317 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002318 }
2319}
2320#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002321# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002322#endif
2323
2324/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2325 * in list[n] so that it points past last stored byte so far.
2326 * It returns n+1. */
2327static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002328{
2329 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002330 int string_start;
2331 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002332
2333 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002334 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2335 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002336 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002337 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002338 /* list[n] points to string_start, make space for 16 more pointers */
2339 o->maxlen += 0x10 * sizeof(list[0]);
2340 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002341 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002342 memmove(list + n + 0x10, list + n, string_len);
2343 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002344 } else {
2345 debug_printf_list("list[%d]=%d string_start=%d\n",
2346 n, string_len, string_start);
2347 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002348 } else {
2349 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002350 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2351 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002352 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2353 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002354 o->has_empty_slot = 0;
2355 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002356 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002357 return n + 1;
2358}
2359
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002360/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002361static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002362{
2363 char **list = (char**)o->data;
2364 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2365
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002366 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002367}
2368
Denys Vlasenko9e800222010-10-03 14:28:04 +02002369#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002370/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2371 * first, it processes even {a} (no commas), second,
2372 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002373 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002374 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002375
2376/* Helper */
2377static int glob_needed(const char *s)
2378{
2379 while (*s) {
2380 if (*s == '\\') {
2381 if (!s[1])
2382 return 0;
2383 s += 2;
2384 continue;
2385 }
2386 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2387 return 1;
2388 s++;
2389 }
2390 return 0;
2391}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002392/* Return pointer to next closing brace or to comma */
2393static const char *next_brace_sub(const char *cp)
2394{
2395 unsigned depth = 0;
2396 cp++;
2397 while (*cp != '\0') {
2398 if (*cp == '\\') {
2399 if (*++cp == '\0')
2400 break;
2401 cp++;
2402 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002403 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002404 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002405 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002406 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002407 depth++;
2408 }
2409
2410 return *cp != '\0' ? cp : NULL;
2411}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002412/* Recursive brace globber. Note: may garble pattern[]. */
2413static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002414{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002415 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002416 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002417 const char *next;
2418 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002419 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002420 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002421
2422 debug_printf_glob("glob_brace('%s')\n", pattern);
2423
2424 begin = pattern;
2425 while (1) {
2426 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002427 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002428 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002429 /* Find the first sub-pattern and at the same time
2430 * find the rest after the closing brace */
2431 next = next_brace_sub(begin);
2432 if (next == NULL) {
2433 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002434 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002435 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002436 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002437 /* "{abc}" with no commas - illegal
2438 * brace expr, disregard and skip it */
2439 begin = next + 1;
2440 continue;
2441 }
2442 break;
2443 }
2444 if (*begin == '\\' && begin[1] != '\0')
2445 begin++;
2446 begin++;
2447 }
2448 debug_printf_glob("begin:%s\n", begin);
2449 debug_printf_glob("next:%s\n", next);
2450
2451 /* Now find the end of the whole brace expression */
2452 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002453 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002454 rest = next_brace_sub(rest);
2455 if (rest == NULL) {
2456 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002457 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002458 }
2459 debug_printf_glob("rest:%s\n", rest);
2460 }
2461 rest_len = strlen(++rest) + 1;
2462
2463 /* We are sure the brace expression is well-formed */
2464
2465 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002466 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002467
2468 /* We have a brace expression. BEGIN points to the opening {,
2469 * NEXT points past the terminator of the first element, and REST
2470 * points past the final }. We will accumulate result names from
2471 * recursive runs for each brace alternative in the buffer using
2472 * GLOB_APPEND. */
2473
2474 p = begin + 1;
2475 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002476 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002477 memcpy(
2478 mempcpy(
2479 mempcpy(new_pattern_buf,
2480 /* We know the prefix for all sub-patterns */
2481 pattern, begin - pattern),
2482 p, next - p),
2483 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002484
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002485 /* Note: glob_brace() may garble new_pattern_buf[].
2486 * That's why we re-copy prefix every time (1st memcpy above).
2487 */
2488 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002489 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002490 /* We saw the last entry */
2491 break;
2492 }
2493 p = next + 1;
2494 next = next_brace_sub(next);
2495 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002496 free(new_pattern_buf);
2497 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002498
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002499 simple_glob:
2500 {
2501 int gr;
2502 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002503
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002504 memset(&globdata, 0, sizeof(globdata));
2505 gr = glob(pattern, 0, NULL, &globdata);
2506 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2507 if (gr != 0) {
2508 if (gr == GLOB_NOMATCH) {
2509 globfree(&globdata);
2510 /* NB: garbles parameter */
2511 unbackslash(pattern);
2512 o_addstr_with_NUL(o, pattern);
2513 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2514 return o_save_ptr_helper(o, n);
2515 }
2516 if (gr == GLOB_NOSPACE)
2517 bb_error_msg_and_die(bb_msg_memory_exhausted);
2518 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2519 * but we didn't specify it. Paranoia again. */
2520 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2521 }
2522 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2523 char **argv = globdata.gl_pathv;
2524 while (1) {
2525 o_addstr_with_NUL(o, *argv);
2526 n = o_save_ptr_helper(o, n);
2527 argv++;
2528 if (!*argv)
2529 break;
2530 }
2531 }
2532 globfree(&globdata);
2533 }
2534 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002535}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002536/* Performs globbing on last list[],
2537 * saving each result as a new list[].
2538 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002539static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002540{
2541 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002542
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002543 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002544 if (!o->data)
2545 return o_save_ptr_helper(o, n);
2546 pattern = o->data + o_get_last_ptr(o, n);
2547 debug_printf_glob("glob pattern '%s'\n", pattern);
2548 if (!glob_needed(pattern)) {
2549 /* unbackslash last string in o in place, fix length */
2550 o->length = unbackslash(pattern) - o->data;
2551 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2552 return o_save_ptr_helper(o, n);
2553 }
2554
2555 copy = xstrdup(pattern);
2556 /* "forget" pattern in o */
2557 o->length = pattern - o->data;
2558 n = glob_brace(copy, o, n);
2559 free(copy);
2560 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002561 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002562 return n;
2563}
2564
Denys Vlasenko238081f2010-10-03 14:26:26 +02002565#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002566
2567/* Helper */
2568static int glob_needed(const char *s)
2569{
2570 while (*s) {
2571 if (*s == '\\') {
2572 if (!s[1])
2573 return 0;
2574 s += 2;
2575 continue;
2576 }
2577 if (*s == '*' || *s == '[' || *s == '?')
2578 return 1;
2579 s++;
2580 }
2581 return 0;
2582}
2583/* Performs globbing on last list[],
2584 * saving each result as a new list[].
2585 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002586static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002587{
2588 glob_t globdata;
2589 int gr;
2590 char *pattern;
2591
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002592 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002593 if (!o->data)
2594 return o_save_ptr_helper(o, n);
2595 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002596 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002597 if (!glob_needed(pattern)) {
2598 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002599 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002600 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002601 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002602 return o_save_ptr_helper(o, n);
2603 }
2604
2605 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002606 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2607 * If we glob "*.\*" and don't find anything, we need
2608 * to fall back to using literal "*.*", but GLOB_NOCHECK
2609 * will return "*.\*"!
2610 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002611 gr = glob(pattern, 0, NULL, &globdata);
2612 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002613 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002614 if (gr == GLOB_NOMATCH) {
2615 globfree(&globdata);
2616 goto literal;
2617 }
2618 if (gr == GLOB_NOSPACE)
2619 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002620 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2621 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002622 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002623 }
2624 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2625 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002626 /* "forget" pattern in o */
2627 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002628 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002629 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002630 n = o_save_ptr_helper(o, n);
2631 argv++;
2632 if (!*argv)
2633 break;
2634 }
2635 }
2636 globfree(&globdata);
2637 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002638 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002639 return n;
2640}
2641
Denys Vlasenko238081f2010-10-03 14:26:26 +02002642#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002643
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002644/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002645 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002646static int o_save_ptr(o_string *o, int n)
2647{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002648 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002649 /* If o->has_empty_slot, list[n] was already globbed
2650 * (if it was requested back then when it was filled)
2651 * so don't do that again! */
2652 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002653 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002654 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002655 return o_save_ptr_helper(o, n);
2656}
2657
2658/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002659static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002660{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002661 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002662 int string_start;
2663
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002664 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2665 if (DEBUG_EXPAND)
2666 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002667 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002668 list = (char**)o->data;
2669 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2670 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002671 while (n) {
2672 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002673 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002674 }
2675 return list;
2676}
2677
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002678static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002679
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002680/* Returns pi->next - next pipe in the list */
2681static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002682{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002683 struct pipe *next;
2684 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002685
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002686 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002687 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002688 struct command *command;
2689 struct redir_struct *r, *rnext;
2690
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002691 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002692 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002693 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002694 if (DEBUG_CLEAN) {
2695 int a;
2696 char **p;
2697 for (a = 0, p = command->argv; *p; a++, p++) {
2698 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2699 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002700 }
2701 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002702 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002703 }
2704 /* not "else if": on syntax error, we may have both! */
2705 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002706 debug_printf_clean(" begin group (cmd_type:%d)\n",
2707 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002708 free_pipe_list(command->group);
2709 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002710 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002711 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002712 /* else is crucial here.
2713 * If group != NULL, child_func is meaningless */
2714#if ENABLE_HUSH_FUNCTIONS
2715 else if (command->child_func) {
2716 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2717 command->child_func->parent_cmd = NULL;
2718 }
2719#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002720#if !BB_MMU
2721 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002722 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002723#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002724 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002725 debug_printf_clean(" redirect %d%s",
2726 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002727 /* guard against the case >$FOO, where foo is unset or blank */
2728 if (r->rd_filename) {
2729 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2730 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002731 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002732 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002733 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002734 rnext = r->next;
2735 free(r);
2736 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002737 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002738 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002739 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002740 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002741#if ENABLE_HUSH_JOB
2742 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002743 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002744#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002745
2746 next = pi->next;
2747 free(pi);
2748 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002749}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002750
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002751static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002752{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002753 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002754#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002755 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002756#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002757 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002758 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002759 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002760}
2761
2762
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002763/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002764
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002765#ifndef debug_print_tree
2766static void debug_print_tree(struct pipe *pi, int lvl)
2767{
2768 static const char *const PIPE[] = {
2769 [PIPE_SEQ] = "SEQ",
2770 [PIPE_AND] = "AND",
2771 [PIPE_OR ] = "OR" ,
2772 [PIPE_BG ] = "BG" ,
2773 };
2774 static const char *RES[] = {
2775 [RES_NONE ] = "NONE" ,
2776# if ENABLE_HUSH_IF
2777 [RES_IF ] = "IF" ,
2778 [RES_THEN ] = "THEN" ,
2779 [RES_ELIF ] = "ELIF" ,
2780 [RES_ELSE ] = "ELSE" ,
2781 [RES_FI ] = "FI" ,
2782# endif
2783# if ENABLE_HUSH_LOOPS
2784 [RES_FOR ] = "FOR" ,
2785 [RES_WHILE] = "WHILE",
2786 [RES_UNTIL] = "UNTIL",
2787 [RES_DO ] = "DO" ,
2788 [RES_DONE ] = "DONE" ,
2789# endif
2790# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2791 [RES_IN ] = "IN" ,
2792# endif
2793# if ENABLE_HUSH_CASE
2794 [RES_CASE ] = "CASE" ,
2795 [RES_CASE_IN ] = "CASE_IN" ,
2796 [RES_MATCH] = "MATCH",
2797 [RES_CASE_BODY] = "CASE_BODY",
2798 [RES_ESAC ] = "ESAC" ,
2799# endif
2800 [RES_XXXX ] = "XXXX" ,
2801 [RES_SNTX ] = "SNTX" ,
2802 };
2803 static const char *const CMDTYPE[] = {
2804 "{}",
2805 "()",
2806 "[noglob]",
2807# if ENABLE_HUSH_FUNCTIONS
2808 "func()",
2809# endif
2810 };
2811
2812 int pin, prn;
2813
2814 pin = 0;
2815 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002816 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002817 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2818 prn = 0;
2819 while (prn < pi->num_cmds) {
2820 struct command *command = &pi->cmds[prn];
2821 char **argv = command->argv;
2822
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002823 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002824 lvl*2, "", prn,
2825 command->assignment_cnt);
2826 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002827 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002828 CMDTYPE[command->cmd_type],
2829 argv
2830# if !BB_MMU
2831 , " group_as_string:", command->group_as_string
2832# else
2833 , "", ""
2834# endif
2835 );
2836 debug_print_tree(command->group, lvl+1);
2837 prn++;
2838 continue;
2839 }
2840 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002841 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002842 argv++;
2843 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002844 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002845 prn++;
2846 }
2847 pi = pi->next;
2848 pin++;
2849 }
2850}
2851#endif /* debug_print_tree */
2852
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002853static struct pipe *new_pipe(void)
2854{
Eric Andersen25f27032001-04-26 23:22:31 +00002855 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002856 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002857 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002858 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002859 return pi;
2860}
2861
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002862/* Command (member of a pipe) is complete, or we start a new pipe
2863 * if ctx->command is NULL.
2864 * No errors possible here.
2865 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002866static int done_command(struct parse_context *ctx)
2867{
2868 /* The command is really already in the pipe structure, so
2869 * advance the pipe counter and make a new, null command. */
2870 struct pipe *pi = ctx->pipe;
2871 struct command *command = ctx->command;
2872
2873 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002874 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002875 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002876 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002877 }
2878 pi->num_cmds++;
2879 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002880 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002881 } else {
2882 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2883 }
2884
2885 /* Only real trickiness here is that the uncommitted
2886 * command structure is not counted in pi->num_cmds. */
2887 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002888 ctx->command = command = &pi->cmds[pi->num_cmds];
2889 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002890 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002891 return pi->num_cmds; /* used only for 0/nonzero check */
2892}
2893
2894static void done_pipe(struct parse_context *ctx, pipe_style type)
2895{
2896 int not_null;
2897
2898 debug_printf_parse("done_pipe entered, followup %d\n", type);
2899 /* Close previous command */
2900 not_null = done_command(ctx);
2901 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002902#if HAS_KEYWORDS
2903 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2904 ctx->ctx_inverted = 0;
2905 ctx->pipe->res_word = ctx->ctx_res_w;
2906#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002907
2908 /* Without this check, even just <enter> on command line generates
2909 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002910 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002911 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002912#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002913 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002914#endif
2915#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002916 || ctx->ctx_res_w == RES_DONE
2917 || ctx->ctx_res_w == RES_FOR
2918 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002919#endif
2920#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002921 || ctx->ctx_res_w == RES_ESAC
2922#endif
2923 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002924 struct pipe *new_p;
2925 debug_printf_parse("done_pipe: adding new pipe: "
2926 "not_null:%d ctx->ctx_res_w:%d\n",
2927 not_null, ctx->ctx_res_w);
2928 new_p = new_pipe();
2929 ctx->pipe->next = new_p;
2930 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002931 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002932 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002933 * This is used to control execution.
2934 * RES_FOR and RES_IN are NOT sticky (needed to support
2935 * cases where variable or value happens to match a keyword):
2936 */
2937#if ENABLE_HUSH_LOOPS
2938 if (ctx->ctx_res_w == RES_FOR
2939 || ctx->ctx_res_w == RES_IN)
2940 ctx->ctx_res_w = RES_NONE;
2941#endif
2942#if ENABLE_HUSH_CASE
2943 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002944 ctx->ctx_res_w = RES_CASE_BODY;
2945 if (ctx->ctx_res_w == RES_CASE)
2946 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002947#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002948 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002949 /* Create the memory for command, roughly:
2950 * ctx->pipe->cmds = new struct command;
2951 * ctx->command = &ctx->pipe->cmds[0];
2952 */
2953 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002954 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002955 }
2956 debug_printf_parse("done_pipe return\n");
2957}
2958
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002959static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002960{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002961 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002962 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002963 /* Create the memory for command, roughly:
2964 * ctx->pipe->cmds = new struct command;
2965 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002966 */
2967 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002968}
2969
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002970/* If a reserved word is found and processed, parse context is modified
2971 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002972 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002973#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002974struct reserved_combo {
2975 char literal[6];
2976 unsigned char res;
2977 unsigned char assignment_flag;
2978 int flag;
2979};
2980enum {
2981 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002982# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002983 FLAG_IF = (1 << RES_IF ),
2984 FLAG_THEN = (1 << RES_THEN ),
2985 FLAG_ELIF = (1 << RES_ELIF ),
2986 FLAG_ELSE = (1 << RES_ELSE ),
2987 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002988# endif
2989# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002990 FLAG_FOR = (1 << RES_FOR ),
2991 FLAG_WHILE = (1 << RES_WHILE),
2992 FLAG_UNTIL = (1 << RES_UNTIL),
2993 FLAG_DO = (1 << RES_DO ),
2994 FLAG_DONE = (1 << RES_DONE ),
2995 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002996# endif
2997# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002998 FLAG_MATCH = (1 << RES_MATCH),
2999 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003000# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003001 FLAG_START = (1 << RES_XXXX ),
3002};
3003
3004static const struct reserved_combo* match_reserved_word(o_string *word)
3005{
Eric Andersen25f27032001-04-26 23:22:31 +00003006 /* Mostly a list of accepted follow-up reserved words.
3007 * FLAG_END means we are done with the sequence, and are ready
3008 * to turn the compound list into a command.
3009 * FLAG_START means the word must start a new compound list.
3010 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003011 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003012# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003013 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3014 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3015 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3016 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3017 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3018 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003019# endif
3020# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003021 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3022 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3023 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3024 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3025 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3026 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003027# endif
3028# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003029 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3030 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003031# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003032 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003033 const struct reserved_combo *r;
3034
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003035 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003036 if (strcmp(word->data, r->literal) == 0)
3037 return r;
3038 }
3039 return NULL;
3040}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003041/* Return 0: not a keyword, 1: keyword
3042 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003043static int reserved_word(o_string *word, struct parse_context *ctx)
3044{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003045# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003046 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003047 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003048 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003049# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003050 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003051
Denys Vlasenko38292b62010-09-05 14:49:40 +02003052 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003053 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003054 r = match_reserved_word(word);
3055 if (!r)
3056 return 0;
3057
3058 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003059# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003060 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3061 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003062 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003063 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003064# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003065 if (r->flag == 0) { /* '!' */
3066 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003067 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003068 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003069 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003070 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003071 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003072 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003073 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003074 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003075
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003076 old = xmalloc(sizeof(*old));
3077 debug_printf_parse("push stack %p\n", old);
3078 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003079 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003080 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003081 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003082 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003083 ctx->ctx_res_w = RES_SNTX;
3084 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003085 } else {
3086 /* "{...} fi" is ok. "{...} if" is not
3087 * Example:
3088 * if { echo foo; } then { echo bar; } fi */
3089 if (ctx->command->group)
3090 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003091 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003092
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003093 ctx->ctx_res_w = r->res;
3094 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003095 word->o_assignment = r->assignment_flag;
3096
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003097 if (ctx->old_flag & FLAG_END) {
3098 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003099
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003100 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003101 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003102 old = ctx->stack;
3103 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003104 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003105# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003106 o_addstr(&old->as_string, ctx->as_string.data);
3107 o_free_unsafe(&ctx->as_string);
3108 old->command->group_as_string = xstrdup(old->as_string.data);
3109 debug_printf_parse("pop, remembering as:'%s'\n",
3110 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003111# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003112 *ctx = *old; /* physical copy */
3113 free(old);
3114 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003115 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003116}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003117#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003118
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003119/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003120 * Normal return is 0. Syntax errors return 1.
3121 * Note: on return, word is reset, but not o_free'd!
3122 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003123static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003124{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003125 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003126
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003127 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003128 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003129 debug_printf_parse("done_word return 0: true null, ignored\n");
3130 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003131 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003132
Eric Andersen25f27032001-04-26 23:22:31 +00003133 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003134 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3135 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003136 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3137 * "2.7 Redirection
3138 * ...the word that follows the redirection operator
3139 * shall be subjected to tilde expansion, parameter expansion,
3140 * command substitution, arithmetic expansion, and quote
3141 * removal. Pathname expansion shall not be performed
3142 * on the word by a non-interactive shell; an interactive
3143 * shell may perform it, but shall do so only when
3144 * the expansion would result in one word."
3145 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003146 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003147 /* Cater for >\file case:
3148 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3149 * Same with heredocs:
3150 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3151 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003152 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3153 unbackslash(ctx->pending_redirect->rd_filename);
3154 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003155 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003156 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3157 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003158 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003159 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003160 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003161 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003162 /* If this word wasn't an assignment, next ones definitely
3163 * can't be assignments. Even if they look like ones. */
3164 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3165 && word->o_assignment != WORD_IS_KEYWORD
3166 ) {
3167 word->o_assignment = NOT_ASSIGNMENT;
3168 } else {
3169 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3170 command->assignment_cnt++;
3171 word->o_assignment = MAYBE_ASSIGNMENT;
3172 }
3173
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003174#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003175# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003176 if (ctx->ctx_dsemicolon
3177 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3178 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003179 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003180 /* ctx->ctx_res_w = RES_MATCH; */
3181 ctx->ctx_dsemicolon = 0;
3182 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003183# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003184 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003185# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003186 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3187 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003188# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003189# if ENABLE_HUSH_CASE
3190 && ctx->ctx_res_w != RES_CASE
3191# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003192 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003193 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003194 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003195 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003196 debug_printf_parse("done_word return %d\n",
3197 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003198 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003199 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003200# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003201 if (strcmp(word->data, "[[") == 0) {
3202 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3203 }
3204 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003205# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003206 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003207#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003208 if (command->group) {
3209 /* "{ echo foo; } echo bar" - bad */
3210 syntax_error_at(word->data);
3211 debug_printf_parse("done_word return 1: syntax error, "
3212 "groups and arglists don't mix\n");
3213 return 1;
3214 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02003215 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003216 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3217 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003218 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003219 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003220 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003221 char *p = word->data;
3222 while (p[0] == SPECIAL_VAR_SYMBOL
3223 && (p[1] & 0x7f) == '@'
3224 && p[2] == SPECIAL_VAR_SYMBOL
3225 ) {
3226 p += 3;
3227 }
3228 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003229 /* saw no "$@", or not only "$@" but some
3230 * real text is there too */
3231 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003232 * e.g. "", $empty"" etc to not disappear */
3233 o_addchr(word, SPECIAL_VAR_SYMBOL);
3234 o_addchr(word, SPECIAL_VAR_SYMBOL);
3235 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003236 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003237 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003238 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003239 }
Eric Andersen25f27032001-04-26 23:22:31 +00003240
Denis Vlasenko06810332007-05-21 23:30:54 +00003241#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003242 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003243 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003244 || !is_well_formed_var_name(command->argv[0], '\0')
3245 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003246 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003247 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003248 return 1;
3249 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003250 /* Force FOR to have just one word (variable name) */
3251 /* NB: basically, this makes hush see "for v in ..."
3252 * syntax as if it is "for v; in ...". FOR and IN become
3253 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003254 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003255 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003256#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003257#if ENABLE_HUSH_CASE
3258 /* Force CASE to have just one word */
3259 if (ctx->ctx_res_w == RES_CASE) {
3260 done_pipe(ctx, PIPE_SEQ);
3261 }
3262#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003263
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003264 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003265
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003266 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003267 return 0;
3268}
3269
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003270
3271/* Peek ahead in the input to find out if we have a "&n" construct,
3272 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003273 * Return:
3274 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3275 * REDIRFD_SYNTAX_ERR if syntax error,
3276 * REDIRFD_TO_FILE if no & was seen,
3277 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003278 */
3279#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003280#define parse_redir_right_fd(as_string, input) \
3281 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003282#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003283static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003284{
3285 int ch, d, ok;
3286
3287 ch = i_peek(input);
3288 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003289 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003290
3291 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003292 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003293 ch = i_peek(input);
3294 if (ch == '-') {
3295 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003296 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003297 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003298 }
3299 d = 0;
3300 ok = 0;
3301 while (ch != EOF && isdigit(ch)) {
3302 d = d*10 + (ch-'0');
3303 ok = 1;
3304 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003305 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003306 ch = i_peek(input);
3307 }
3308 if (ok) return d;
3309
3310//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3311
3312 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003313 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003314}
3315
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003316/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003317 */
3318static int parse_redirect(struct parse_context *ctx,
3319 int fd,
3320 redir_type style,
3321 struct in_str *input)
3322{
3323 struct command *command = ctx->command;
3324 struct redir_struct *redir;
3325 struct redir_struct **redirp;
3326 int dup_num;
3327
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003328 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003329 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003330 /* Check for a '>&1' type redirect */
3331 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3332 if (dup_num == REDIRFD_SYNTAX_ERR)
3333 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003334 } else {
3335 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003336 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003337 if (dup_num) { /* <<-... */
3338 ch = i_getch(input);
3339 nommu_addchr(&ctx->as_string, ch);
3340 ch = i_peek(input);
3341 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003342 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003343
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003344 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003345 int ch = i_peek(input);
3346 if (ch == '|') {
3347 /* >|FILE redirect ("clobbering" >).
3348 * Since we do not support "set -o noclobber" yet,
3349 * >| and > are the same for now. Just eat |.
3350 */
3351 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003352 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003353 }
3354 }
3355
3356 /* Create a new redir_struct and append it to the linked list */
3357 redirp = &command->redirects;
3358 while ((redir = *redirp) != NULL) {
3359 redirp = &(redir->next);
3360 }
3361 *redirp = redir = xzalloc(sizeof(*redir));
3362 /* redir->next = NULL; */
3363 /* redir->rd_filename = NULL; */
3364 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003365 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003366
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003367 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3368 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003369
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003370 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003371 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003372 /* Erik had a check here that the file descriptor in question
3373 * is legit; I postpone that to "run time"
3374 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003375 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3376 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003377 } else {
3378 /* Set ctx->pending_redirect, so we know what to do at the
3379 * end of the next parsed word. */
3380 ctx->pending_redirect = redir;
3381 }
3382 return 0;
3383}
3384
Eric Andersen25f27032001-04-26 23:22:31 +00003385/* If a redirect is immediately preceded by a number, that number is
3386 * supposed to tell which file descriptor to redirect. This routine
3387 * looks for such preceding numbers. In an ideal world this routine
3388 * needs to handle all the following classes of redirects...
3389 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3390 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3391 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3392 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003393 *
3394 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3395 * "2.7 Redirection
3396 * ... If n is quoted, the number shall not be recognized as part of
3397 * the redirection expression. For example:
3398 * echo \2>a
3399 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003400 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003401 *
3402 * A -1 return means no valid number was found,
3403 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003404 */
3405static int redirect_opt_num(o_string *o)
3406{
3407 int num;
3408
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003409 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003410 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003411 num = bb_strtou(o->data, NULL, 10);
3412 if (errno || num < 0)
3413 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003414 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003415 return num;
3416}
3417
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003418#if BB_MMU
3419#define fetch_till_str(as_string, input, word, skip_tabs) \
3420 fetch_till_str(input, word, skip_tabs)
3421#endif
3422static char *fetch_till_str(o_string *as_string,
3423 struct in_str *input,
3424 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003425 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003426{
3427 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003428 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003429 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003430 int ch;
3431
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003432 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003433
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003434 while (1) {
3435 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003436 if (ch != EOF)
3437 nommu_addchr(as_string, ch);
3438 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003439 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3440 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003441 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3442 heredoc.data[past_EOL] = '\0';
3443 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3444 return heredoc.data;
3445 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003446 while (ch == '\n') {
3447 o_addchr(&heredoc, ch);
3448 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003449 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003450 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003451 do {
3452 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003453 if (ch != EOF)
3454 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003455 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003456 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003457 }
3458 if (ch == EOF) {
3459 o_free_unsafe(&heredoc);
3460 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003461 }
3462 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003463 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003464 if (prev == '\\' && ch == '\\')
3465 /* Correctly handle foo\\<eol> (not a line cont.) */
3466 prev = 0; /* not \ */
3467 else
3468 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003469 }
3470}
3471
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003472/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3473 * and load them all. There should be exactly heredoc_cnt of them.
3474 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003475static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3476{
3477 struct pipe *pi = ctx->list_head;
3478
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003479 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003480 int i;
3481 struct command *cmd = pi->cmds;
3482
3483 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3484 pi->num_cmds,
3485 cmd->argv ? cmd->argv[0] : "NONE");
3486 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003487 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003488
3489 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3490 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003491 while (redir) {
3492 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003493 char *p;
3494
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003495 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003496 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003497 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003498 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003499 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003500 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003501 return 1;
3502 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003503 free(redir->rd_filename);
3504 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003505 heredoc_cnt--;
3506 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003507 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003508 }
3509 cmd++;
3510 }
3511 pi = pi->next;
3512 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003513#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003514 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003515 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003516 bb_error_msg_and_die("heredoc BUG 2");
3517#endif
3518 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003519}
3520
3521
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003522static int run_list(struct pipe *pi);
3523#if BB_MMU
3524#define parse_stream(pstring, input, end_trigger) \
3525 parse_stream(input, end_trigger)
3526#endif
3527static struct pipe *parse_stream(char **pstring,
3528 struct in_str *input,
3529 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003530
Eric Andersen25f27032001-04-26 23:22:31 +00003531
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003532#if !ENABLE_HUSH_FUNCTIONS
3533#define parse_group(dest, ctx, input, ch) \
3534 parse_group(ctx, input, ch)
3535#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003536static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003537 struct in_str *input, int ch)
3538{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003539 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003540 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003541 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003542 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003543 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003544 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003545
3546 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003547#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003548 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003549 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003550 if (done_word(dest, ctx))
3551 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003552 if (!command->argv)
3553 goto skip; /* (... */
3554 if (command->argv[1]) { /* word word ... (... */
3555 syntax_error_unexpected_ch('(');
3556 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003557 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003558 /* it is "word(..." or "word (..." */
3559 do
3560 ch = i_getch(input);
3561 while (ch == ' ' || ch == '\t');
3562 if (ch != ')') {
3563 syntax_error_unexpected_ch(ch);
3564 return 1;
3565 }
3566 nommu_addchr(&ctx->as_string, ch);
3567 do
3568 ch = i_getch(input);
3569 while (ch == ' ' || ch == '\t' || ch == '\n');
3570 if (ch != '{') {
3571 syntax_error_unexpected_ch(ch);
3572 return 1;
3573 }
3574 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003575 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003576 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003577 }
3578#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003579
3580#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003581 if (command->argv /* word [word]{... */
3582 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003583 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003584 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003585 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003586 debug_printf_parse("parse_group return 1: "
3587 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003588 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003589 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003590#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003591
3592#if ENABLE_HUSH_FUNCTIONS
3593 skip:
3594#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003595 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003596 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003597 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003598 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003599 } else {
3600 /* bash does not allow "{echo...", requires whitespace */
3601 ch = i_getch(input);
3602 if (ch != ' ' && ch != '\t' && ch != '\n') {
3603 syntax_error_unexpected_ch(ch);
3604 return 1;
3605 }
3606 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003607 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003608
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003609 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003610#if BB_MMU
3611# define as_string NULL
3612#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003613 char *as_string = NULL;
3614#endif
3615 pipe_list = parse_stream(&as_string, input, endch);
3616#if !BB_MMU
3617 if (as_string)
3618 o_addstr(&ctx->as_string, as_string);
3619#endif
3620 /* empty ()/{} or parse error? */
3621 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003622 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003623 if (!BB_MMU)
3624 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003625 debug_printf_parse("parse_group return 1: "
3626 "parse_stream returned %p\n", pipe_list);
3627 return 1;
3628 }
3629 command->group = pipe_list;
3630#if !BB_MMU
3631 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3632 command->group_as_string = as_string;
3633 debug_printf_parse("end of group, remembering as:'%s'\n",
3634 command->group_as_string);
3635#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003636#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003637 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003638 debug_printf_parse("parse_group return 0\n");
3639 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003640 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003641}
3642
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003643#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003644/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003645static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003646/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003647static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003648{
3649 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003650 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003651 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003652 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003653 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003654 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003655 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003656 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003657 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003658 }
3659}
3660/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003661static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003662{
3663 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003664 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003665 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003666 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003667 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003668 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003669 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003670 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003671 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003672 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003673 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003674 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003675 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003676 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003677 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3678 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003679 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003680 continue;
3681 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003682 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003683 }
3684}
3685/* Process `cmd` - copy contents until "`" is seen. Complicated by
3686 * \` quoting.
3687 * "Within the backquoted style of command substitution, backslash
3688 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3689 * The search for the matching backquote shall be satisfied by the first
3690 * backquote found without a preceding backslash; during this search,
3691 * if a non-escaped backquote is encountered within a shell comment,
3692 * a here-document, an embedded command substitution of the $(command)
3693 * form, or a quoted string, undefined results occur. A single-quoted
3694 * or double-quoted string that begins, but does not end, within the
3695 * "`...`" sequence produces undefined results."
3696 * Example Output
3697 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3698 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003699static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003700{
3701 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003702 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003703 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003704 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003705 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003706 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3707 ch = i_getch(input);
3708 if (ch != '`'
3709 && ch != '$'
3710 && ch != '\\'
3711 && (!in_dquote || ch != '"')
3712 ) {
3713 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003714 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003715 }
3716 if (ch == EOF) {
3717 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003718 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003719 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003720 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003721 }
3722}
3723/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3724 * quoting and nested ()s.
3725 * "With the $(command) style of command substitution, all characters
3726 * following the open parenthesis to the matching closing parenthesis
3727 * constitute the command. Any valid shell script can be used for command,
3728 * except a script consisting solely of redirections which produces
3729 * unspecified results."
3730 * Example Output
3731 * echo $(echo '(TEST)' BEST) (TEST) BEST
3732 * echo $(echo 'TEST)' BEST) TEST) BEST
3733 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003734 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003735 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003736 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003737 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3738 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003739 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003740#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003741static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003742{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003743 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003744 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003745# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003746 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003747# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003748 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3749
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003750 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003751 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003752 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003753 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003754 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003755 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003756 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003757 if (!dbl)
3758 break;
3759 /* we look for closing )) of $((EXPR)) */
3760 if (i_peek(input) == end_ch) {
3761 i_getch(input); /* eat second ')' */
3762 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003763 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003764 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003765 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003766 if (ch == '(' || ch == '{') {
3767 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003768 if (!add_till_closing_bracket(dest, input, ch))
3769 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003770 o_addchr(dest, ch);
3771 continue;
3772 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003773 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003774 if (!add_till_single_quote(dest, input))
3775 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003776 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003777 continue;
3778 }
3779 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003780 if (!add_till_double_quote(dest, input))
3781 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003782 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003783 continue;
3784 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003785 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003786 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3787 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003788 o_addchr(dest, ch);
3789 continue;
3790 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003791 if (ch == '\\') {
3792 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003793 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003794 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003795 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003796 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003797 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003798 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003799 continue;
3800 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003801 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003802 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003803}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003804#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003805
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003806/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003807#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003808#define parse_dollar(as_string, dest, input, quote_mask) \
3809 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003810#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003811#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003812static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003813 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003814 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003815{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003816 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003817
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003818 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003819 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003820 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003821 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003822 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003823 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003824 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003825 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003826 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003827 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003828 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003829 if (!isalnum(ch) && ch != '_')
3830 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003831 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003832 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003833 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003834 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003835 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003836 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003837 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003838 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003839 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003840 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003841 o_addchr(dest, ch | quote_mask);
3842 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003843 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003844 case '$': /* pid */
3845 case '!': /* last bg pid */
3846 case '?': /* last exit code */
3847 case '#': /* number of args */
3848 case '*': /* args */
3849 case '@': /* args */
3850 goto make_one_char_var;
3851 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003852 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3853
Denys Vlasenko74369502010-05-21 19:52:01 +02003854 ch = i_getch(input); /* eat '{' */
3855 nommu_addchr(as_string, ch);
3856
3857 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003858 /* It should be ${?}, or ${#var},
3859 * or even ${?+subst} - operator acting on a special variable,
3860 * or the beginning of variable name.
3861 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003862 if (ch == EOF
3863 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3864 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003865 bad_dollar_syntax:
3866 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003867 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3868 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02003869 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003870 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003871 ch |= quote_mask;
3872
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003873 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003874 * However, this regresses some of our testsuite cases
3875 * which check invalid constructs like ${%}.
3876 * Oh well... let's check that the var name part is fine... */
3877
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003878 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003879 unsigned pos;
3880
Denys Vlasenko74369502010-05-21 19:52:01 +02003881 o_addchr(dest, ch);
3882 debug_printf_parse(": '%c'\n", ch);
3883
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003884 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003885 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003886 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003887 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003888
Denys Vlasenko74369502010-05-21 19:52:01 +02003889 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003890 unsigned end_ch;
3891 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003892 /* handle parameter expansions
3893 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3894 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003895 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003896 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003897
3898 /* Eat everything until closing '}' (or ':') */
3899 end_ch = '}';
3900 if (ENABLE_HUSH_BASH_COMPAT
3901 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003902 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003903 ) {
3904 /* It's ${var:N[:M]} thing */
3905 end_ch = '}' * 0x100 + ':';
3906 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003907 if (ENABLE_HUSH_BASH_COMPAT
3908 && ch == '/'
3909 ) {
3910 /* It's ${var/[/]pattern[/repl]} thing */
3911 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3912 i_getch(input);
3913 nommu_addchr(as_string, '/');
3914 ch = '\\';
3915 }
3916 end_ch = '}' * 0x100 + '/';
3917 }
3918 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003919 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003920 if (!BB_MMU)
3921 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003922#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003923 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003924 if (last_ch == 0) /* error? */
3925 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003926#else
3927#error Simple code to only allow ${var} is not implemented
3928#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003929 if (as_string) {
3930 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003931 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003932 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003933
3934 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3935 /* close the first block: */
3936 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003937 /* while parsing N from ${var:N[:M]}
3938 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003939 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003940 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003941 end_ch = '}';
3942 goto again;
3943 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003944 /* got '}' */
3945 if (end_ch == '}' * 0x100 + ':') {
3946 /* it's ${var:N} - emulate :999999999 */
3947 o_addstr(dest, "999999999");
3948 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003949 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003950 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003951 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003952 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003953 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3954 break;
3955 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003956#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003957 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003958 unsigned pos;
3959
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003960 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003961 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003962# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003963 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003964 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003965 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003966 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3967 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003968 if (!BB_MMU)
3969 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003970 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
3971 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003972 if (as_string) {
3973 o_addstr(as_string, dest->data + pos);
3974 o_addchr(as_string, ')');
3975 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003976 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003977 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003978 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003979 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003980# endif
3981# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003982 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3983 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003984 if (!BB_MMU)
3985 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003986 if (!add_till_closing_bracket(dest, input, ')'))
3987 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003988 if (as_string) {
3989 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003990 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003991 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003992 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003993# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003994 break;
3995 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003996#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003997 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003998 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003999 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004000 ch = i_peek(input);
4001 if (isalnum(ch)) { /* it's $_name or $_123 */
4002 ch = '_';
4003 goto make_var;
4004 }
4005 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004006 /* TODO: $_ and $-: */
4007 /* $_ Shell or shell script name; or last argument of last command
4008 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4009 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004010 /* $- Option flags set by set builtin or shell options (-i etc) */
4011 default:
4012 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004013 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004014 debug_printf_parse("parse_dollar return 1 (ok)\n");
4015 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004016#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004017}
4018
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004019#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004020# if ENABLE_HUSH_BASH_COMPAT
4021#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4022 encode_string(dest, input, dquote_end, process_bkslash)
4023# else
4024/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4025#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4026 encode_string(dest, input, dquote_end)
4027# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004028#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004029
4030#else /* !MMU */
4031
4032# if ENABLE_HUSH_BASH_COMPAT
4033/* all parameters are needed, no macro tricks */
4034# else
4035#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4036 encode_string(as_string, dest, input, dquote_end)
4037# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004038#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004039static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004040 o_string *dest,
4041 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004042 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004043 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004044{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004045#if !ENABLE_HUSH_BASH_COMPAT
4046 const int process_bkslash = 1;
4047#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004048 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004049 int next;
4050
4051 again:
4052 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004053 if (ch != EOF)
4054 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004055 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004056 debug_printf_parse("encode_string return 1 (ok)\n");
4057 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004058 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004059 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004060 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004061 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004062 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004063 }
4064 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004065 if (ch != '\n') {
4066 next = i_peek(input);
4067 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004068 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004069 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004070 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004071 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004072 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004073 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004074 }
4075 /* bash:
4076 * "The backslash retains its special meaning [in "..."]
4077 * only when followed by one of the following characters:
4078 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004079 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004080 * NB: in (unquoted) heredoc, above does not apply to ",
4081 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004082 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004083 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004084 ch = i_getch(input); /* eat next */
4085 if (ch == '\n')
4086 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004087 } /* else: ch remains == '\\', and we double it below: */
4088 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004089 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004090 goto again;
4091 }
4092 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004093 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4094 debug_printf_parse("encode_string return 0: "
4095 "parse_dollar returned 0 (error)\n");
4096 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004097 }
4098 goto again;
4099 }
4100#if ENABLE_HUSH_TICK
4101 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004102 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004103 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4104 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004105 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4106 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004107 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4108 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004109 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004110 }
4111#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004112 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004113 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004114#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004115}
4116
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004117/*
4118 * Scan input until EOF or end_trigger char.
4119 * Return a list of pipes to execute, or NULL on EOF
4120 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004121 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004122 * reset parsing machinery and start parsing anew,
4123 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004124 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004125static struct pipe *parse_stream(char **pstring,
4126 struct in_str *input,
4127 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004128{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004129 struct parse_context ctx;
4130 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004131 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004132
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004133 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004134 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004135 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004136 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004137 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004138 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004139
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004140 /* If very first arg is "" or '', dest.data may end up NULL.
4141 * Preventing this: */
4142 o_addchr(&dest, '\0');
4143 dest.length = 0;
4144
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004145 /* We used to separate words on $IFS here. This was wrong.
4146 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004147 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004148 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004149
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004150 if (MAYBE_ASSIGNMENT != 0)
4151 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004152 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004153 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004154 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004155 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004156 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004157 int ch;
4158 int next;
4159 int redir_fd;
4160 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004161
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004162 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004163 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004164 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004165 if (ch == EOF) {
4166 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004167
4168 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004169 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004170 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004171 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004172 /* end_trigger == '}' case errors out earlier,
4173 * checking only ')' */
4174 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004175 syntax_error_unterm_ch('(');
4176 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004177 }
4178
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004179 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004180 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004181 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004182 o_free(&dest);
4183 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004184 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004185 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004186 /* (this makes bare "&" cmd a no-op.
4187 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004188 if (pi->num_cmds == 0
4189 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4190 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004191 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004192 pi = NULL;
4193 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004194#if !BB_MMU
4195 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4196 if (pstring)
4197 *pstring = ctx.as_string.data;
4198 else
4199 o_free_unsafe(&ctx.as_string);
4200#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004201 debug_leave();
4202 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004203 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004204 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004205 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004206
4207 next = '\0';
4208 if (ch != '\n')
4209 next = i_peek(input);
4210
4211 is_special = "{}<>;&|()#'" /* special outside of "str" */
4212 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4213 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004214 if (ctx.command->argv /* word [word]{... - non-special */
4215 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004216 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004217 || (next != ';' /* }; - special */
4218 && next != ')' /* }) - special */
4219 && next != '&' /* }& and }&& ... - special */
4220 && next != '|' /* }|| ... - special */
4221 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004222 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004223 ) {
4224 /* They are not special, skip "{}" */
4225 is_special += 2;
4226 }
4227 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004228 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004229
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004230 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004231 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004232 o_addQchr(&dest, ch);
4233 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4234 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004235 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004236 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004237 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004238 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004239 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004240 continue;
4241 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004242
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004243 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004244 if (done_word(&dest, &ctx)) {
4245 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004246 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004247 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004248 /* Is this a case when newline is simply ignored?
4249 * Some examples:
4250 * "cmd | <newline> cmd ..."
4251 * "case ... in <newline> word) ..."
4252 */
4253 if (IS_NULL_CMD(ctx.command)
4254 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004255 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004256 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004257 * Without check #1, interactive shell
4258 * ignores even bare <newline>,
4259 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004260 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004261 * ps2> _ <=== wrong, should be ps1
4262 * Without check #2, "cmd & <newline>"
4263 * is similarly mistreated.
4264 * (BTW, this makes "cmd & cmd"
4265 * and "cmd && cmd" non-orthogonal.
4266 * Really, ask yourself, why
4267 * "cmd && <newline>" doesn't start
4268 * cmd but waits for more input?
4269 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004270 */
4271 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004272 if (pi->num_cmds != 0 /* check #1 */
4273 && pi->followup != PIPE_BG /* check #2 */
4274 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004275 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004276 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004277 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004278 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004279 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004280 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4281 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004282 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004283 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004284 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004285 heredoc_cnt = 0;
4286 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004287 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004288 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004289 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004290 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004291 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004292 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004293
4294 /* "cmd}" or "cmd }..." without semicolon or &:
4295 * } is an ordinary char in this case, even inside { cmd; }
4296 * Pathological example: { ""}; } should exec "}" cmd
4297 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004298 if (ch == '}') {
4299 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4300 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004301 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004302 ) {
4303 goto ordinary_char;
4304 }
4305 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4306 goto skip_end_trigger;
4307 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004308 }
4309
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004310 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004311 && (ch != ';' || heredoc_cnt == 0)
4312#if ENABLE_HUSH_CASE
4313 && (ch != ')'
4314 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004315 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004316 )
4317#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004318 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004319 if (heredoc_cnt) {
4320 /* This is technically valid:
4321 * { cat <<HERE; }; echo Ok
4322 * heredoc
4323 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004324 * HERE
4325 * but we don't support this.
4326 * We require heredoc to be in enclosing {}/(),
4327 * if any.
4328 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004329 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004330 goto parse_error;
4331 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004332 if (done_word(&dest, &ctx)) {
4333 goto parse_error;
4334 }
4335 done_pipe(&ctx, PIPE_SEQ);
4336 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004337 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004338 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004339 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004340 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004341 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004342#if !BB_MMU
4343 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4344 if (pstring)
4345 *pstring = ctx.as_string.data;
4346 else
4347 o_free_unsafe(&ctx.as_string);
4348#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004349 debug_leave();
4350 debug_printf_parse("parse_stream return %p: "
4351 "end_trigger char found\n",
4352 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004353 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004354 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004355 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004356 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004357 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004358 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004359
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004360 /* Catch <, > before deciding whether this word is
4361 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4362 switch (ch) {
4363 case '>':
4364 redir_fd = redirect_opt_num(&dest);
4365 if (done_word(&dest, &ctx)) {
4366 goto parse_error;
4367 }
4368 redir_style = REDIRECT_OVERWRITE;
4369 if (next == '>') {
4370 redir_style = REDIRECT_APPEND;
4371 ch = i_getch(input);
4372 nommu_addchr(&ctx.as_string, ch);
4373 }
4374#if 0
4375 else if (next == '(') {
4376 syntax_error(">(process) not supported");
4377 goto parse_error;
4378 }
4379#endif
4380 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4381 goto parse_error;
4382 continue; /* back to top of while (1) */
4383 case '<':
4384 redir_fd = redirect_opt_num(&dest);
4385 if (done_word(&dest, &ctx)) {
4386 goto parse_error;
4387 }
4388 redir_style = REDIRECT_INPUT;
4389 if (next == '<') {
4390 redir_style = REDIRECT_HEREDOC;
4391 heredoc_cnt++;
4392 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4393 ch = i_getch(input);
4394 nommu_addchr(&ctx.as_string, ch);
4395 } else if (next == '>') {
4396 redir_style = REDIRECT_IO;
4397 ch = i_getch(input);
4398 nommu_addchr(&ctx.as_string, ch);
4399 }
4400#if 0
4401 else if (next == '(') {
4402 syntax_error("<(process) not supported");
4403 goto parse_error;
4404 }
4405#endif
4406 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4407 goto parse_error;
4408 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004409 case '#':
4410 if (dest.length == 0 && !dest.has_quoted_part) {
4411 /* skip "#comment" */
4412 while (1) {
4413 ch = i_peek(input);
4414 if (ch == EOF || ch == '\n')
4415 break;
4416 i_getch(input);
4417 /* note: we do not add it to &ctx.as_string */
4418 }
4419 nommu_addchr(&ctx.as_string, '\n');
4420 continue; /* back to top of while (1) */
4421 }
4422 break;
4423 case '\\':
4424 if (next == '\n') {
4425 /* It's "\<newline>" */
4426#if !BB_MMU
4427 /* Remove trailing '\' from ctx.as_string */
4428 ctx.as_string.data[--ctx.as_string.length] = '\0';
4429#endif
4430 ch = i_getch(input); /* eat it */
4431 continue; /* back to top of while (1) */
4432 }
4433 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004434 }
4435
4436 if (dest.o_assignment == MAYBE_ASSIGNMENT
4437 /* check that we are not in word in "a=1 2>word b=1": */
4438 && !ctx.pending_redirect
4439 ) {
4440 /* ch is a special char and thus this word
4441 * cannot be an assignment */
4442 dest.o_assignment = NOT_ASSIGNMENT;
4443 }
4444
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004445 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4446
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004447 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004448 case '#': /* non-comment #: "echo a#b" etc */
4449 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004450 break;
4451 case '\\':
4452 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004453 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004454 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004455 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004456 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004457 /* note: ch != '\n' (that case does not reach this place) */
4458 o_addchr(&dest, '\\');
4459 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4460 o_addchr(&dest, ch);
4461 nommu_addchr(&ctx.as_string, ch);
4462 /* Example: echo Hello \2>file
4463 * we need to know that word 2 is quoted */
4464 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004465 break;
4466 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004467 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004468 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004469 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004470 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004471 }
Eric Andersen25f27032001-04-26 23:22:31 +00004472 break;
4473 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004474 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004475 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004476 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004477 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004478 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004479 goto parse_error;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004480 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004481 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004482 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004483 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004484 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004485 }
Eric Andersen25f27032001-04-26 23:22:31 +00004486 break;
4487 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004488 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004489 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004490 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004491 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004492 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004493 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004494 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004495#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004496 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004497 unsigned pos;
4498
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004499 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4500 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004501 pos = dest.length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004502 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4503 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004504# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004505 o_addstr(&ctx.as_string, dest.data + pos);
4506 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004507# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004508 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4509 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004510 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004511 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004512#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004513 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004514#if ENABLE_HUSH_CASE
4515 case_semi:
4516#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004517 if (done_word(&dest, &ctx)) {
4518 goto parse_error;
4519 }
4520 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004521#if ENABLE_HUSH_CASE
4522 /* Eat multiple semicolons, detect
4523 * whether it means something special */
4524 while (1) {
4525 ch = i_peek(input);
4526 if (ch != ';')
4527 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004528 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004529 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004530 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004531 ctx.ctx_dsemicolon = 1;
4532 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004533 break;
4534 }
4535 }
4536#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004537 new_cmd:
4538 /* We just finished a cmd. New one may start
4539 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004540 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004541 break;
4542 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004543 if (done_word(&dest, &ctx)) {
4544 goto parse_error;
4545 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004546 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004547 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004548 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004549 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004550 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004551 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004552 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004553 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004554 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004555 if (done_word(&dest, &ctx)) {
4556 goto parse_error;
4557 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004558#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004559 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004560 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004561#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004562 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004563 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004564 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004565 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004566 } else {
4567 /* we could pick up a file descriptor choice here
4568 * with redirect_opt_num(), but bash doesn't do it.
4569 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004570 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004571#if !BB_MMU
4572 o_reset_to_empty_unquoted(&ctx.as_string);
4573#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004574 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004575 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004576 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004577#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004578 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004579 if (ctx.ctx_res_w == RES_MATCH
4580 && ctx.command->argv == NULL /* not (word|(... */
4581 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004582 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004583 ) {
4584 continue;
4585 }
4586#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004587 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004588 if (parse_group(&dest, &ctx, input, ch) != 0) {
4589 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004590 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004591 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004592 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004593#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004594 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004595 goto case_semi;
4596#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004597 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004598 /* proper use of this character is caught by end_trigger:
4599 * if we see {, we call parse_group(..., end_trigger='}')
4600 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004601 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004602 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004603 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004604 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004605 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004606 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004607 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004608
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004609 parse_error:
4610 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004611 struct parse_context *pctx;
4612 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004613
4614 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004615 * Sample for finding leaks on syntax error recovery path.
4616 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004617 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004618 * Samples to catch leaks at execution:
4619 * while if (true | {true;}); then echo ok; fi; do break; done
4620 * 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 +00004621 */
4622 pctx = &ctx;
4623 do {
4624 /* Update pipe/command counts,
4625 * otherwise freeing may miss some */
4626 done_pipe(pctx, PIPE_SEQ);
4627 debug_printf_clean("freeing list %p from ctx %p\n",
4628 pctx->list_head, pctx);
4629 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004630 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004631 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004632#if !BB_MMU
4633 o_free_unsafe(&pctx->as_string);
4634#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004635 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004636 if (pctx != &ctx) {
4637 free(pctx);
4638 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004639 IF_HAS_KEYWORDS(pctx = p2;)
4640 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004641
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004642 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004643 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004644#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004645 if (pstring)
4646 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004647#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004648 debug_leave();
4649 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004650 }
Eric Andersen25f27032001-04-26 23:22:31 +00004651}
4652
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004653
4654/*** Execution routines ***/
4655
4656/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004657#if !ENABLE_HUSH_BASH_COMPAT
4658/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4659#define expand_string_to_string(str, do_unbackslash) \
4660 expand_string_to_string(str)
4661#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004662static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004663#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004664static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004665#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004666
4667/* expand_strvec_to_strvec() takes a list of strings, expands
4668 * all variable references within and returns a pointer to
4669 * a list of expanded strings, possibly with larger number
4670 * of strings. (Think VAR="a b"; echo $VAR).
4671 * This new list is allocated as a single malloc block.
4672 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004673 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004674 * Caller can deallocate entire list by single free(list). */
4675
Denys Vlasenko238081f2010-10-03 14:26:26 +02004676/* A horde of its helpers come first: */
4677
4678static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4679{
4680 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004681 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004682
Denys Vlasenko9e800222010-10-03 14:28:04 +02004683#if ENABLE_HUSH_BRACE_EXPANSION
4684 if (c == '{' || c == '}') {
4685 /* { -> \{, } -> \} */
4686 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004687 /* And now we want to add { or } and continue:
4688 * o_addchr(o, c);
4689 * continue;
4690 * luckily, just falling throught achieves this.
4691 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004692 }
4693#endif
4694 o_addchr(o, c);
4695 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004696 /* \z -> \\\z; \<eol> -> \\<eol> */
4697 o_addchr(o, '\\');
4698 if (len) {
4699 len--;
4700 o_addchr(o, '\\');
4701 o_addchr(o, *str++);
4702 }
4703 }
4704 }
4705}
4706
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004707/* Store given string, finalizing the word and starting new one whenever
4708 * we encounter IFS char(s). This is used for expanding variable values.
4709 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4710static int expand_on_ifs(o_string *output, int n, const char *str)
4711{
4712 while (1) {
4713 int word_len = strcspn(str, G.ifs);
4714 if (word_len) {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004715 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004716 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004717 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004718 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004719 * Example: "v='\*'; echo b$v" prints "b\*"
4720 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004721 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004722 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004723 /*/ Why can't we do it easier? */
4724 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4725 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4726 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004727 str += word_len;
4728 }
4729 if (!*str) /* EOL - do not finalize word */
4730 break;
4731 o_addchr(output, '\0');
4732 debug_print_list("expand_on_ifs", output, n);
4733 n = o_save_ptr(output, n);
4734 str += strspn(str, G.ifs); /* skip ifs chars */
4735 }
4736 debug_print_list("expand_on_ifs[1]", output, n);
4737 return n;
4738}
4739
4740/* Helper to expand $((...)) and heredoc body. These act as if
4741 * they are in double quotes, with the exception that they are not :).
4742 * Just the rules are similar: "expand only $var and `cmd`"
4743 *
4744 * Returns malloced string.
4745 * As an optimization, we return NULL if expansion is not needed.
4746 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004747#if !ENABLE_HUSH_BASH_COMPAT
4748/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4749#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4750 encode_then_expand_string(str)
4751#endif
4752static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004753{
4754 char *exp_str;
4755 struct in_str input;
4756 o_string dest = NULL_O_STRING;
4757
4758 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004759 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004760#if ENABLE_HUSH_TICK
4761 && !strchr(str, '`')
4762#endif
4763 ) {
4764 return NULL;
4765 }
4766
4767 /* We need to expand. Example:
4768 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4769 */
4770 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004771 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004772//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004773 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004774 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004775 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4776 o_free_unsafe(&dest);
4777 return exp_str;
4778}
4779
4780#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004781static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004782{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004783 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004784 arith_t res;
4785 char *exp_str;
4786
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004787 math_state.lookupvar = get_local_var_value;
4788 math_state.setvar = set_local_var_from_halves;
4789 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004790 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004791 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004792 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004793 if (errmsg_p)
4794 *errmsg_p = math_state.errmsg;
4795 if (math_state.errmsg)
4796 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004797 return res;
4798}
4799#endif
4800
4801#if ENABLE_HUSH_BASH_COMPAT
4802/* ${var/[/]pattern[/repl]} helpers */
4803static char *strstr_pattern(char *val, const char *pattern, int *size)
4804{
4805 while (1) {
4806 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4807 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4808 if (end) {
4809 *size = end - val;
4810 return val;
4811 }
4812 if (*val == '\0')
4813 return NULL;
4814 /* Optimization: if "*pat" did not match the start of "string",
4815 * we know that "tring", "ring" etc will not match too:
4816 */
4817 if (pattern[0] == '*')
4818 return NULL;
4819 val++;
4820 }
4821}
4822static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4823{
4824 char *result = NULL;
4825 unsigned res_len = 0;
4826 unsigned repl_len = strlen(repl);
4827
4828 while (1) {
4829 int size;
4830 char *s = strstr_pattern(val, pattern, &size);
4831 if (!s)
4832 break;
4833
4834 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4835 memcpy(result + res_len, val, s - val);
4836 res_len += s - val;
4837 strcpy(result + res_len, repl);
4838 res_len += repl_len;
4839 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4840
4841 val = s + size;
4842 if (exp_op == '/')
4843 break;
4844 }
4845 if (val[0] && result) {
4846 result = xrealloc(result, res_len + strlen(val) + 1);
4847 strcpy(result + res_len, val);
4848 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4849 }
4850 debug_printf_varexp("result:'%s'\n", result);
4851 return result;
4852}
4853#endif
4854
4855/* Helper:
4856 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4857 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004858static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004859{
4860 const char *val = NULL;
4861 char *to_be_freed = NULL;
4862 char *p = *pp;
4863 char *var;
4864 char first_char;
4865 char exp_op;
4866 char exp_save = exp_save; /* for compiler */
4867 char *exp_saveptr; /* points to expansion operator */
4868 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004869 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004870
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004871 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004872 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004873 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004874 arg0 = arg[0];
4875 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004876 exp_op = 0;
4877
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004878 if (first_char == '#' /* ${#... */
4879 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4880 ) {
4881 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004882 var++;
4883 exp_op = 'L';
4884 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004885 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004886 if (exp_saveptr /* if 2nd char is one of expansion operators */
4887 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4888 ) {
4889 /* ${?:0}, ${#[:]%0} etc */
4890 exp_saveptr = var + 1;
4891 } else {
4892 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4893 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4894 }
4895 exp_op = exp_save = *exp_saveptr;
4896 if (exp_op) {
4897 exp_word = exp_saveptr + 1;
4898 if (exp_op == ':') {
4899 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004900//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004901 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004902 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004903 ) {
4904 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4905 exp_op = ':';
4906 exp_word--;
4907 }
4908 }
4909 *exp_saveptr = '\0';
4910 } /* else: it's not an expansion op, but bare ${var} */
4911 }
4912
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004913 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004914 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004915 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004916 int n = xatoi_positive(var);
4917 if (n < G.global_argc)
4918 val = G.global_argv[n];
4919 /* else val remains NULL: $N with too big N */
4920 } else {
4921 switch (var[0]) {
4922 case '$': /* pid */
4923 val = utoa(G.root_pid);
4924 break;
4925 case '!': /* bg pid */
4926 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4927 break;
4928 case '?': /* exitcode */
4929 val = utoa(G.last_exitcode);
4930 break;
4931 case '#': /* argc */
4932 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4933 break;
4934 default:
4935 val = get_local_var_value(var);
4936 }
4937 }
4938
4939 /* Handle any expansions */
4940 if (exp_op == 'L') {
4941 debug_printf_expand("expand: length(%s)=", val);
4942 val = utoa(val ? strlen(val) : 0);
4943 debug_printf_expand("%s\n", val);
4944 } else if (exp_op) {
4945 if (exp_op == '%' || exp_op == '#') {
4946 /* Standard-mandated substring removal ops:
4947 * ${parameter%word} - remove smallest suffix pattern
4948 * ${parameter%%word} - remove largest suffix pattern
4949 * ${parameter#word} - remove smallest prefix pattern
4950 * ${parameter##word} - remove largest prefix pattern
4951 *
4952 * Word is expanded to produce a glob pattern.
4953 * Then var's value is matched to it and matching part removed.
4954 */
4955 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004956 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004957 char *exp_exp_word;
4958 char *loc;
4959 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02004960 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004961 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004962 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004963 if (exp_exp_word)
4964 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02004965 /* HACK ALERT. We depend here on the fact that
4966 * G.global_argv and results of utoa and get_local_var_value
4967 * are actually in writable memory:
4968 * scan_and_match momentarily stores NULs there. */
4969 t = (char*)val;
4970 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004971 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02004972 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004973 free(exp_exp_word);
4974 if (loc) { /* match was found */
4975 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004976 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004977 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004978 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004979 }
4980 }
4981 }
4982#if ENABLE_HUSH_BASH_COMPAT
4983 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004984 /* It's ${var/[/]pattern[/repl]} thing.
4985 * Note that in encoded form it has TWO parts:
4986 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02004987 * and if // is used, it is encoded as \:
4988 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004989 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004990 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004991 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004992 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004993 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004994 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004995 * by the usual expansion rules:
4996 * >az; >bz;
4997 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4998 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4999 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5000 * v='a bz'; echo ${v/a*z/\z} prints "z"
5001 * (note that a*z _pattern_ is never globbed!)
5002 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005003 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005004 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005005 if (!pattern)
5006 pattern = xstrdup(exp_word);
5007 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5008 *p++ = SPECIAL_VAR_SYMBOL;
5009 exp_word = p;
5010 p = strchr(p, SPECIAL_VAR_SYMBOL);
5011 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005012 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005013 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5014 /* HACK ALERT. We depend here on the fact that
5015 * G.global_argv and results of utoa and get_local_var_value
5016 * are actually in writable memory:
5017 * replace_pattern momentarily stores NULs there. */
5018 t = (char*)val;
5019 to_be_freed = replace_pattern(t,
5020 pattern,
5021 (repl ? repl : exp_word),
5022 exp_op);
5023 if (to_be_freed) /* at least one replace happened */
5024 val = to_be_freed;
5025 free(pattern);
5026 free(repl);
5027 }
5028 }
5029#endif
5030 else if (exp_op == ':') {
5031#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5032 /* It's ${var:N[:M]} bashism.
5033 * Note that in encoded form it has TWO parts:
5034 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5035 */
5036 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005037 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005038
Denys Vlasenko063847d2010-09-15 13:33:02 +02005039 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5040 if (errmsg)
5041 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005042 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5043 *p++ = SPECIAL_VAR_SYMBOL;
5044 exp_word = p;
5045 p = strchr(p, SPECIAL_VAR_SYMBOL);
5046 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005047 len = expand_and_evaluate_arith(exp_word, &errmsg);
5048 if (errmsg)
5049 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005050 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005051 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005052 if (beg < 0) /* bash compat */
5053 beg = 0;
5054 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005055 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005056 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005057 val = NULL;
5058 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005059 /* Paranoia. What if user entered 9999999999999
5060 * which fits in arith_t but not int? */
5061 if (len >= INT_MAX)
5062 len = INT_MAX;
5063 val = to_be_freed = xstrndup(val + beg, len);
5064 }
5065 debug_printf_varexp("val:'%s'\n", val);
5066 } else
5067#endif
5068 {
5069 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005070 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005071 }
5072 } else { /* one of "-=+?" */
5073 /* Standard-mandated substitution ops:
5074 * ${var?word} - indicate error if unset
5075 * If var is unset, word (or a message indicating it is unset
5076 * if word is null) is written to standard error
5077 * and the shell exits with a non-zero exit status.
5078 * Otherwise, the value of var is substituted.
5079 * ${var-word} - use default value
5080 * If var is unset, word is substituted.
5081 * ${var=word} - assign and use default value
5082 * If var is unset, word is assigned to var.
5083 * In all cases, final value of var is substituted.
5084 * ${var+word} - use alternative value
5085 * If var is unset, null is substituted.
5086 * Otherwise, word is substituted.
5087 *
5088 * Word is subjected to tilde expansion, parameter expansion,
5089 * command substitution, and arithmetic expansion.
5090 * If word is not needed, it is not expanded.
5091 *
5092 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5093 * but also treat null var as if it is unset.
5094 */
5095 int use_word = (!val || ((exp_save == ':') && !val[0]));
5096 if (exp_op == '+')
5097 use_word = !use_word;
5098 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5099 (exp_save == ':') ? "true" : "false", use_word);
5100 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005101 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005102 if (to_be_freed)
5103 exp_word = to_be_freed;
5104 if (exp_op == '?') {
5105 /* mimic bash message */
5106 die_if_script("%s: %s",
5107 var,
5108 exp_word[0] ? exp_word : "parameter null or not set"
5109 );
5110//TODO: how interactive bash aborts expansion mid-command?
5111 } else {
5112 val = exp_word;
5113 }
5114
5115 if (exp_op == '=') {
5116 /* ${var=[word]} or ${var:=[word]} */
5117 if (isdigit(var[0]) || var[0] == '#') {
5118 /* mimic bash message */
5119 die_if_script("$%s: cannot assign in this way", var);
5120 val = NULL;
5121 } else {
5122 char *new_var = xasprintf("%s=%s", var, val);
5123 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5124 }
5125 }
5126 }
5127 } /* one of "-=+?" */
5128
5129 *exp_saveptr = exp_save;
5130 } /* if (exp_op) */
5131
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005132 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005133
5134 *pp = p;
5135 *to_be_freed_pp = to_be_freed;
5136 return val;
5137}
5138
5139/* Expand all variable references in given string, adding words to list[]
5140 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5141 * to be filled). This routine is extremely tricky: has to deal with
5142 * variables/parameters with whitespace, $* and $@, and constructs like
5143 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005144static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005145{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005146 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005147 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005148 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005149 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005150 char *p;
5151
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005152 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5153 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005154 debug_print_list("expand_vars_to_list", output, n);
5155 n = o_save_ptr(output, n);
5156 debug_print_list("expand_vars_to_list[0]", output, n);
5157
5158 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5159 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005160 char *to_be_freed = NULL;
5161 const char *val = NULL;
5162#if ENABLE_HUSH_TICK
5163 o_string subst_result = NULL_O_STRING;
5164#endif
5165#if ENABLE_SH_MATH_SUPPORT
5166 char arith_buf[sizeof(arith_t)*3 + 2];
5167#endif
5168 o_addblock(output, arg, p - arg);
5169 debug_print_list("expand_vars_to_list[1]", output, n);
5170 arg = ++p;
5171 p = strchr(p, SPECIAL_VAR_SYMBOL);
5172
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005173 /* Fetch special var name (if it is indeed one of them)
5174 * and quote bit, force the bit on if singleword expansion -
5175 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005176 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005177
5178 /* Is this variable quoted and thus expansion can't be null?
5179 * "$@" is special. Even if quoted, it can still
5180 * expand to nothing (not even an empty string),
5181 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005182 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005183 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005184
5185 switch (first_ch & 0x7f) {
5186 /* Highest bit in first_ch indicates that var is double-quoted */
5187 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005188 case '@': {
5189 int i;
5190 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005191 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005192 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005193 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005194 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005195 while (G.global_argv[i]) {
5196 n = expand_on_ifs(output, n, G.global_argv[i]);
5197 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5198 if (G.global_argv[i++][0] && G.global_argv[i]) {
5199 /* this argv[] is not empty and not last:
5200 * put terminating NUL, start new word */
5201 o_addchr(output, '\0');
5202 debug_print_list("expand_vars_to_list[2]", output, n);
5203 n = o_save_ptr(output, n);
5204 debug_print_list("expand_vars_to_list[3]", output, n);
5205 }
5206 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005207 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005208 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005209 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005210 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005211 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005212 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005213 while (1) {
5214 o_addQstr(output, G.global_argv[i]);
5215 if (++i >= G.global_argc)
5216 break;
5217 o_addchr(output, '\0');
5218 debug_print_list("expand_vars_to_list[4]", output, n);
5219 n = o_save_ptr(output, n);
5220 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005221 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005222 while (1) {
5223 o_addQstr(output, G.global_argv[i]);
5224 if (!G.global_argv[++i])
5225 break;
5226 if (G.ifs[0])
5227 o_addchr(output, G.ifs[0]);
5228 }
5229 }
5230 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005231 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005232 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5233 /* "Empty variable", used to make "" etc to not disappear */
5234 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005235 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005236 break;
5237#if ENABLE_HUSH_TICK
5238 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005239 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005240 arg++;
5241 /* Can't just stuff it into output o_string,
5242 * expanded result may need to be globbed
5243 * and $IFS-splitted */
5244 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5245 G.last_exitcode = process_command_subs(&subst_result, arg);
5246 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5247 val = subst_result.data;
5248 goto store_val;
5249#endif
5250#if ENABLE_SH_MATH_SUPPORT
5251 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5252 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005253
5254 arg++; /* skip '+' */
5255 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5256 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005257 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005258 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5259 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005260 val = arith_buf;
5261 break;
5262 }
5263#endif
5264 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005265 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005266 IF_HUSH_TICK(store_val:)
5267 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005268 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5269 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005270 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005271 n = expand_on_ifs(output, n, val);
5272 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005273 }
5274 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005275 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5276 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005277 }
5278 break;
5279
5280 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5281
5282 if (val && val[0]) {
5283 o_addQstr(output, val);
5284 }
5285 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005286
5287 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5288 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005289 if (*p != SPECIAL_VAR_SYMBOL)
5290 *p = SPECIAL_VAR_SYMBOL;
5291
5292#if ENABLE_HUSH_TICK
5293 o_free(&subst_result);
5294#endif
5295 arg = ++p;
5296 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5297
5298 if (arg[0]) {
5299 debug_print_list("expand_vars_to_list[a]", output, n);
5300 /* this part is literal, and it was already pre-quoted
5301 * if needed (much earlier), do not use o_addQstr here! */
5302 o_addstr_with_NUL(output, arg);
5303 debug_print_list("expand_vars_to_list[b]", output, n);
5304 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005305 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005306 ) {
5307 n--;
5308 /* allow to reuse list[n] later without re-growth */
5309 output->has_empty_slot = 1;
5310 } else {
5311 o_addchr(output, '\0');
5312 }
5313
5314 return n;
5315}
5316
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005317static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005318{
5319 int n;
5320 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005321 o_string output = NULL_O_STRING;
5322
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005323 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005324
5325 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005326 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005327 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005328 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005329 }
5330 debug_print_list("expand_variables", &output, n);
5331
5332 /* output.data (malloced in one block) gets returned in "list" */
5333 list = o_finalize_list(&output, n);
5334 debug_print_strings("expand_variables[1]", list);
5335 return list;
5336}
5337
5338static char **expand_strvec_to_strvec(char **argv)
5339{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005340 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005341}
5342
5343#if ENABLE_HUSH_BASH_COMPAT
5344static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5345{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005346 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005347}
5348#endif
5349
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005350/* Used for expansion of right hand of assignments,
5351 * $((...)), heredocs, variable espansion parts.
5352 *
5353 * NB: should NOT do globbing!
5354 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5355 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005356static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005357{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005358#if !ENABLE_HUSH_BASH_COMPAT
5359 const int do_unbackslash = 1;
5360#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005361 char *argv[2], **list;
5362
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005363 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005364 /* This is generally an optimization, but it also
5365 * handles "", which otherwise trips over !list[0] check below.
5366 * (is this ever happens that we actually get str="" here?)
5367 */
5368 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5369 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005370 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005371 return xstrdup(str);
5372 }
5373
5374 argv[0] = (char*)str;
5375 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005376 list = expand_variables(argv, do_unbackslash
5377 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5378 : EXP_FLAG_SINGLEWORD
5379 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005380 if (HUSH_DEBUG)
5381 if (!list[0] || list[1])
5382 bb_error_msg_and_die("BUG in varexp2");
5383 /* actually, just move string 2*sizeof(char*) bytes back */
5384 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005385 if (do_unbackslash)
5386 unbackslash((char*)list);
5387 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005388 return (char*)list;
5389}
5390
5391/* Used for "eval" builtin */
5392static char* expand_strvec_to_string(char **argv)
5393{
5394 char **list;
5395
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005396 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005397 /* Convert all NULs to spaces */
5398 if (list[0]) {
5399 int n = 1;
5400 while (list[n]) {
5401 if (HUSH_DEBUG)
5402 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5403 bb_error_msg_and_die("BUG in varexp3");
5404 /* bash uses ' ' regardless of $IFS contents */
5405 list[n][-1] = ' ';
5406 n++;
5407 }
5408 }
5409 overlapping_strcpy((char*)list, list[0]);
5410 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5411 return (char*)list;
5412}
5413
5414static char **expand_assignments(char **argv, int count)
5415{
5416 int i;
5417 char **p;
5418
5419 G.expanded_assignments = p = NULL;
5420 /* Expand assignments into one string each */
5421 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005422 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005423 }
5424 G.expanded_assignments = NULL;
5425 return p;
5426}
5427
5428
5429#if BB_MMU
5430/* never called */
5431void re_execute_shell(char ***to_free, const char *s,
5432 char *g_argv0, char **g_argv,
5433 char **builtin_argv) NORETURN;
5434
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005435static void switch_off_special_sigs(unsigned mask)
5436{
5437 unsigned sig = 0;
5438 while ((mask >>= 1) != 0) {
5439 sig++;
5440 if (!(mask & 1))
5441 continue;
5442 if (G.traps) {
5443 if (G.traps[sig] && !G.traps[sig][0])
5444 /* trap is '', has to remain SIG_IGN */
5445 continue;
5446 free(G.traps[sig]);
5447 G.traps[sig] = NULL;
5448 }
5449 /* We are here only if no trap or trap was not '' */
5450 signal(sig, SIG_DFL);
5451 }
5452}
5453
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005454static void reset_traps_to_defaults(void)
5455{
5456 /* This function is always called in a child shell
5457 * after fork (not vfork, NOMMU doesn't use this function).
5458 */
5459 unsigned sig;
5460 unsigned mask;
5461
5462 /* Child shells are not interactive.
5463 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5464 * Testcase: (while :; do :; done) + ^Z should background.
5465 * Same goes for SIGTERM, SIGHUP, SIGINT.
5466 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005467 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5468 if (!G.traps && !mask)
5469 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005470
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005471 /* Switch off special sigs */
5472 switch_off_special_sigs(mask);
5473#if ENABLE_HUSH_JOB
5474 G_fatal_sig_mask = 0;
5475#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005476 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005477 /* SIGQUIT and maybe SPECIAL_JOBSTOP_SIGS remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005478
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005479 if (!G.traps)
5480 return;
5481
5482 /* Reset all sigs to default except ones with empty traps */
5483 for (sig = 0; sig < NSIG; sig++) {
5484 if (!G.traps[sig])
5485 continue; /* no trap: nothing to do */
5486 if (!G.traps[sig][0])
5487 continue; /* empty trap: has to remain SIG_IGN */
5488 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005489 free(G.traps[sig]);
5490 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005491 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005492 if (sig == 0)
5493 continue;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005494 signal(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005495 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005496}
5497
5498#else /* !BB_MMU */
5499
5500static void re_execute_shell(char ***to_free, const char *s,
5501 char *g_argv0, char **g_argv,
5502 char **builtin_argv) NORETURN;
5503static void re_execute_shell(char ***to_free, const char *s,
5504 char *g_argv0, char **g_argv,
5505 char **builtin_argv)
5506{
5507# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5508 /* delims + 2 * (number of bytes in printed hex numbers) */
5509 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5510 char *heredoc_argv[4];
5511 struct variable *cur;
5512# if ENABLE_HUSH_FUNCTIONS
5513 struct function *funcp;
5514# endif
5515 char **argv, **pp;
5516 unsigned cnt;
5517 unsigned long long empty_trap_mask;
5518
5519 if (!g_argv0) { /* heredoc */
5520 argv = heredoc_argv;
5521 argv[0] = (char *) G.argv0_for_re_execing;
5522 argv[1] = (char *) "-<";
5523 argv[2] = (char *) s;
5524 argv[3] = NULL;
5525 pp = &argv[3]; /* used as pointer to empty environment */
5526 goto do_exec;
5527 }
5528
5529 cnt = 0;
5530 pp = builtin_argv;
5531 if (pp) while (*pp++)
5532 cnt++;
5533
5534 empty_trap_mask = 0;
5535 if (G.traps) {
5536 int sig;
5537 for (sig = 1; sig < NSIG; sig++) {
5538 if (G.traps[sig] && !G.traps[sig][0])
5539 empty_trap_mask |= 1LL << sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005540///vda: optimize
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005541 }
5542 }
5543
5544 sprintf(param_buf, NOMMU_HACK_FMT
5545 , (unsigned) G.root_pid
5546 , (unsigned) G.root_ppid
5547 , (unsigned) G.last_bg_pid
5548 , (unsigned) G.last_exitcode
5549 , cnt
5550 , empty_trap_mask
5551 IF_HUSH_LOOPS(, G.depth_of_loop)
5552 );
5553# undef NOMMU_HACK_FMT
5554 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5555 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5556 */
5557 cnt += 6;
5558 for (cur = G.top_var; cur; cur = cur->next) {
5559 if (!cur->flg_export || cur->flg_read_only)
5560 cnt += 2;
5561 }
5562# if ENABLE_HUSH_FUNCTIONS
5563 for (funcp = G.top_func; funcp; funcp = funcp->next)
5564 cnt += 3;
5565# endif
5566 pp = g_argv;
5567 while (*pp++)
5568 cnt++;
5569 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5570 *pp++ = (char *) G.argv0_for_re_execing;
5571 *pp++ = param_buf;
5572 for (cur = G.top_var; cur; cur = cur->next) {
5573 if (strcmp(cur->varstr, hush_version_str) == 0)
5574 continue;
5575 if (cur->flg_read_only) {
5576 *pp++ = (char *) "-R";
5577 *pp++ = cur->varstr;
5578 } else if (!cur->flg_export) {
5579 *pp++ = (char *) "-V";
5580 *pp++ = cur->varstr;
5581 }
5582 }
5583# if ENABLE_HUSH_FUNCTIONS
5584 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5585 *pp++ = (char *) "-F";
5586 *pp++ = funcp->name;
5587 *pp++ = funcp->body_as_string;
5588 }
5589# endif
5590 /* We can pass activated traps here. Say, -Tnn:trap_string
5591 *
5592 * However, POSIX says that subshells reset signals with traps
5593 * to SIG_DFL.
5594 * I tested bash-3.2 and it not only does that with true subshells
5595 * of the form ( list ), but with any forked children shells.
5596 * I set trap "echo W" WINCH; and then tried:
5597 *
5598 * { echo 1; sleep 20; echo 2; } &
5599 * while true; do echo 1; sleep 20; echo 2; break; done &
5600 * true | { echo 1; sleep 20; echo 2; } | cat
5601 *
5602 * In all these cases sending SIGWINCH to the child shell
5603 * did not run the trap. If I add trap "echo V" WINCH;
5604 * _inside_ group (just before echo 1), it works.
5605 *
5606 * I conclude it means we don't need to pass active traps here.
5607 * Even if we would use signal handlers instead of signal masking
5608 * in order to implement trap handling,
5609 * exec syscall below resets signals to SIG_DFL for us.
5610 */
5611 *pp++ = (char *) "-c";
5612 *pp++ = (char *) s;
5613 if (builtin_argv) {
5614 while (*++builtin_argv)
5615 *pp++ = *builtin_argv;
5616 *pp++ = (char *) "";
5617 }
5618 *pp++ = g_argv0;
5619 while (*g_argv)
5620 *pp++ = *g_argv++;
5621 /* *pp = NULL; - is already there */
5622 pp = environ;
5623
5624 do_exec:
5625 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005626 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005627 execve(bb_busybox_exec_path, argv, pp);
5628 /* Fallback. Useful for init=/bin/hush usage etc */
5629 if (argv[0][0] == '/')
5630 execve(argv[0], argv, pp);
5631 xfunc_error_retval = 127;
5632 bb_error_msg_and_die("can't re-execute the shell");
5633}
5634#endif /* !BB_MMU */
5635
5636
5637static int run_and_free_list(struct pipe *pi);
5638
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005639/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005640 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5641 * end_trigger controls how often we stop parsing
5642 * NUL: parse all, execute, return
5643 * ';': parse till ';' or newline, execute, repeat till EOF
5644 */
5645static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005646{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005647 /* Why we need empty flag?
5648 * An obscure corner case "false; ``; echo $?":
5649 * empty command in `` should still set $? to 0.
5650 * But we can't just set $? to 0 at the start,
5651 * this breaks "false; echo `echo $?`" case.
5652 */
5653 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005654 while (1) {
5655 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005656
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005657#if ENABLE_HUSH_INTERACTIVE
5658 if (end_trigger == ';')
5659 inp->promptmode = 0; /* PS1 */
5660#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005661 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005662 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5663 /* If we are in "big" script
5664 * (not in `cmd` or something similar)...
5665 */
5666 if (pipe_list == ERR_PTR && end_trigger == ';') {
5667 /* Discard cached input (rest of line) */
5668 int ch = inp->last_char;
5669 while (ch != EOF && ch != '\n') {
5670 //bb_error_msg("Discarded:'%c'", ch);
5671 ch = i_getch(inp);
5672 }
5673 /* Force prompt */
5674 inp->p = NULL;
5675 /* This stream isn't empty */
5676 empty = 0;
5677 continue;
5678 }
5679 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01005680 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005681 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005682 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005683 debug_print_tree(pipe_list, 0);
5684 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5685 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005686 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005687#if ENABLE_HUSH_FUNCTIONS
5688 if (G.flag_return_in_progress == 1)
5689 break;
5690#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005691 }
Eric Andersen25f27032001-04-26 23:22:31 +00005692}
5693
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005694static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005695{
5696 struct in_str input;
5697 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005698 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005699}
5700
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005701static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005702{
Eric Andersen25f27032001-04-26 23:22:31 +00005703 struct in_str input;
5704 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005705 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005706}
5707
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005708#if ENABLE_HUSH_TICK
5709static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5710{
5711 pid_t pid;
5712 int channel[2];
5713# if !BB_MMU
5714 char **to_free = NULL;
5715# endif
5716
5717 xpipe(channel);
5718 pid = BB_MMU ? xfork() : xvfork();
5719 if (pid == 0) { /* child */
5720 disable_restore_tty_pgrp_on_exit();
5721 /* Process substitution is not considered to be usual
5722 * 'command execution'.
5723 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5724 */
5725 bb_signals(0
5726 + (1 << SIGTSTP)
5727 + (1 << SIGTTIN)
5728 + (1 << SIGTTOU)
5729 , SIG_IGN);
5730 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5731 close(channel[0]); /* NB: close _first_, then move fd! */
5732 xmove_fd(channel[1], 1);
5733 /* Prevent it from trying to handle ctrl-z etc */
5734 IF_HUSH_JOB(G.run_list_level = 1;)
5735 /* Awful hack for `trap` or $(trap).
5736 *
5737 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5738 * contains an example where "trap" is executed in a subshell:
5739 *
5740 * save_traps=$(trap)
5741 * ...
5742 * eval "$save_traps"
5743 *
5744 * Standard does not say that "trap" in subshell shall print
5745 * parent shell's traps. It only says that its output
5746 * must have suitable form, but then, in the above example
5747 * (which is not supposed to be normative), it implies that.
5748 *
5749 * bash (and probably other shell) does implement it
5750 * (traps are reset to defaults, but "trap" still shows them),
5751 * but as a result, "trap" logic is hopelessly messed up:
5752 *
5753 * # trap
5754 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5755 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5756 * # true | trap <--- trap is in subshell - no output (ditto)
5757 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5758 * trap -- 'echo Ho' SIGWINCH
5759 * # echo `(trap)` <--- in subshell in subshell - output
5760 * trap -- 'echo Ho' SIGWINCH
5761 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5762 * trap -- 'echo Ho' SIGWINCH
5763 *
5764 * The rules when to forget and when to not forget traps
5765 * get really complex and nonsensical.
5766 *
5767 * Our solution: ONLY bare $(trap) or `trap` is special.
5768 */
5769 s = skip_whitespace(s);
5770 if (strncmp(s, "trap", 4) == 0
5771 && skip_whitespace(s + 4)[0] == '\0'
5772 ) {
5773 static const char *const argv[] = { NULL, NULL };
5774 builtin_trap((char**)argv);
5775 exit(0); /* not _exit() - we need to fflush */
5776 }
5777# if BB_MMU
5778 reset_traps_to_defaults();
5779 parse_and_run_string(s);
5780 _exit(G.last_exitcode);
5781# else
5782 /* We re-execute after vfork on NOMMU. This makes this script safe:
5783 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5784 * huge=`cat BIG` # was blocking here forever
5785 * echo OK
5786 */
5787 re_execute_shell(&to_free,
5788 s,
5789 G.global_argv[0],
5790 G.global_argv + 1,
5791 NULL);
5792# endif
5793 }
5794
5795 /* parent */
5796 *pid_p = pid;
5797# if ENABLE_HUSH_FAST
5798 G.count_SIGCHLD++;
5799//bb_error_msg("[%d] fork in generate_stream_from_string:"
5800// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5801// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5802# endif
5803 enable_restore_tty_pgrp_on_exit();
5804# if !BB_MMU
5805 free(to_free);
5806# endif
5807 close(channel[1]);
5808 close_on_exec_on(channel[0]);
5809 return xfdopen_for_read(channel[0]);
5810}
5811
5812/* Return code is exit status of the process that is run. */
5813static int process_command_subs(o_string *dest, const char *s)
5814{
5815 FILE *fp;
5816 struct in_str pipe_str;
5817 pid_t pid;
5818 int status, ch, eol_cnt;
5819
5820 fp = generate_stream_from_string(s, &pid);
5821
5822 /* Now send results of command back into original context */
5823 setup_file_in_str(&pipe_str, fp);
5824 eol_cnt = 0;
5825 while ((ch = i_getch(&pipe_str)) != EOF) {
5826 if (ch == '\n') {
5827 eol_cnt++;
5828 continue;
5829 }
5830 while (eol_cnt) {
5831 o_addchr(dest, '\n');
5832 eol_cnt--;
5833 }
5834 o_addQchr(dest, ch);
5835 }
5836
5837 debug_printf("done reading from `cmd` pipe, closing it\n");
5838 fclose(fp);
5839 /* We need to extract exitcode. Test case
5840 * "true; echo `sleep 1; false` $?"
5841 * should print 1 */
5842 safe_waitpid(pid, &status, 0);
5843 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5844 return WEXITSTATUS(status);
5845}
5846#endif /* ENABLE_HUSH_TICK */
5847
5848
5849static void setup_heredoc(struct redir_struct *redir)
5850{
5851 struct fd_pair pair;
5852 pid_t pid;
5853 int len, written;
5854 /* the _body_ of heredoc (misleading field name) */
5855 const char *heredoc = redir->rd_filename;
5856 char *expanded;
5857#if !BB_MMU
5858 char **to_free;
5859#endif
5860
5861 expanded = NULL;
5862 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005863 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005864 if (expanded)
5865 heredoc = expanded;
5866 }
5867 len = strlen(heredoc);
5868
5869 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5870 xpiped_pair(pair);
5871 xmove_fd(pair.rd, redir->rd_fd);
5872
5873 /* Try writing without forking. Newer kernels have
5874 * dynamically growing pipes. Must use non-blocking write! */
5875 ndelay_on(pair.wr);
5876 while (1) {
5877 written = write(pair.wr, heredoc, len);
5878 if (written <= 0)
5879 break;
5880 len -= written;
5881 if (len == 0) {
5882 close(pair.wr);
5883 free(expanded);
5884 return;
5885 }
5886 heredoc += written;
5887 }
5888 ndelay_off(pair.wr);
5889
5890 /* Okay, pipe buffer was not big enough */
5891 /* Note: we must not create a stray child (bastard? :)
5892 * for the unsuspecting parent process. Child creates a grandchild
5893 * and exits before parent execs the process which consumes heredoc
5894 * (that exec happens after we return from this function) */
5895#if !BB_MMU
5896 to_free = NULL;
5897#endif
5898 pid = xvfork();
5899 if (pid == 0) {
5900 /* child */
5901 disable_restore_tty_pgrp_on_exit();
5902 pid = BB_MMU ? xfork() : xvfork();
5903 if (pid != 0)
5904 _exit(0);
5905 /* grandchild */
5906 close(redir->rd_fd); /* read side of the pipe */
5907#if BB_MMU
5908 full_write(pair.wr, heredoc, len); /* may loop or block */
5909 _exit(0);
5910#else
5911 /* Delegate blocking writes to another process */
5912 xmove_fd(pair.wr, STDOUT_FILENO);
5913 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5914#endif
5915 }
5916 /* parent */
5917#if ENABLE_HUSH_FAST
5918 G.count_SIGCHLD++;
5919//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5920#endif
5921 enable_restore_tty_pgrp_on_exit();
5922#if !BB_MMU
5923 free(to_free);
5924#endif
5925 close(pair.wr);
5926 free(expanded);
5927 wait(NULL); /* wait till child has died */
5928}
5929
5930/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5931 * and stderr if they are redirected. */
5932static int setup_redirects(struct command *prog, int squirrel[])
5933{
5934 int openfd, mode;
5935 struct redir_struct *redir;
5936
5937 for (redir = prog->redirects; redir; redir = redir->next) {
5938 if (redir->rd_type == REDIRECT_HEREDOC2) {
5939 /* rd_fd<<HERE case */
5940 if (squirrel && redir->rd_fd < 3
5941 && squirrel[redir->rd_fd] < 0
5942 ) {
5943 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5944 }
5945 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5946 * of the heredoc */
5947 debug_printf_parse("set heredoc '%s'\n",
5948 redir->rd_filename);
5949 setup_heredoc(redir);
5950 continue;
5951 }
5952
5953 if (redir->rd_dup == REDIRFD_TO_FILE) {
5954 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5955 char *p;
5956 if (redir->rd_filename == NULL) {
5957 /* Something went wrong in the parse.
5958 * Pretend it didn't happen */
5959 bb_error_msg("bug in redirect parse");
5960 continue;
5961 }
5962 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005963 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005964 openfd = open_or_warn(p, mode);
5965 free(p);
5966 if (openfd < 0) {
5967 /* this could get lost if stderr has been redirected, but
5968 * bash and ash both lose it as well (though zsh doesn't!) */
5969//what the above comment tries to say?
5970 return 1;
5971 }
5972 } else {
5973 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5974 openfd = redir->rd_dup;
5975 }
5976
5977 if (openfd != redir->rd_fd) {
5978 if (squirrel && redir->rd_fd < 3
5979 && squirrel[redir->rd_fd] < 0
5980 ) {
5981 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5982 }
5983 if (openfd == REDIRFD_CLOSE) {
5984 /* "n>-" means "close me" */
5985 close(redir->rd_fd);
5986 } else {
5987 xdup2(openfd, redir->rd_fd);
5988 if (redir->rd_dup == REDIRFD_TO_FILE)
5989 close(openfd);
5990 }
5991 }
5992 }
5993 return 0;
5994}
5995
5996static void restore_redirects(int squirrel[])
5997{
5998 int i, fd;
5999 for (i = 0; i < 3; i++) {
6000 fd = squirrel[i];
6001 if (fd != -1) {
6002 /* We simply die on error */
6003 xmove_fd(fd, i);
6004 }
6005 }
6006}
6007
6008static char *find_in_path(const char *arg)
6009{
6010 char *ret = NULL;
6011 const char *PATH = get_local_var_value("PATH");
6012
6013 if (!PATH)
6014 return NULL;
6015
6016 while (1) {
6017 const char *end = strchrnul(PATH, ':');
6018 int sz = end - PATH; /* must be int! */
6019
6020 free(ret);
6021 if (sz != 0) {
6022 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6023 } else {
6024 /* We have xxx::yyyy in $PATH,
6025 * it means "use current dir" */
6026 ret = xstrdup(arg);
6027 }
6028 if (access(ret, F_OK) == 0)
6029 break;
6030
6031 if (*end == '\0') {
6032 free(ret);
6033 return NULL;
6034 }
6035 PATH = end + 1;
6036 }
6037
6038 return ret;
6039}
6040
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006041static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006042 const struct built_in_command *x,
6043 const struct built_in_command *end)
6044{
6045 while (x != end) {
6046 if (strcmp(name, x->b_cmd) != 0) {
6047 x++;
6048 continue;
6049 }
6050 debug_printf_exec("found builtin '%s'\n", name);
6051 return x;
6052 }
6053 return NULL;
6054}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006055static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006056{
6057 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6058}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006059static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006060{
6061 const struct built_in_command *x = find_builtin1(name);
6062 if (x)
6063 return x;
6064 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6065}
6066
6067#if ENABLE_HUSH_FUNCTIONS
6068static struct function **find_function_slot(const char *name)
6069{
6070 struct function **funcpp = &G.top_func;
6071 while (*funcpp) {
6072 if (strcmp(name, (*funcpp)->name) == 0) {
6073 break;
6074 }
6075 funcpp = &(*funcpp)->next;
6076 }
6077 return funcpp;
6078}
6079
6080static const struct function *find_function(const char *name)
6081{
6082 const struct function *funcp = *find_function_slot(name);
6083 if (funcp)
6084 debug_printf_exec("found function '%s'\n", name);
6085 return funcp;
6086}
6087
6088/* Note: takes ownership on name ptr */
6089static struct function *new_function(char *name)
6090{
6091 struct function **funcpp = find_function_slot(name);
6092 struct function *funcp = *funcpp;
6093
6094 if (funcp != NULL) {
6095 struct command *cmd = funcp->parent_cmd;
6096 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6097 if (!cmd) {
6098 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6099 free(funcp->name);
6100 /* Note: if !funcp->body, do not free body_as_string!
6101 * This is a special case of "-F name body" function:
6102 * body_as_string was not malloced! */
6103 if (funcp->body) {
6104 free_pipe_list(funcp->body);
6105# if !BB_MMU
6106 free(funcp->body_as_string);
6107# endif
6108 }
6109 } else {
6110 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6111 cmd->argv[0] = funcp->name;
6112 cmd->group = funcp->body;
6113# if !BB_MMU
6114 cmd->group_as_string = funcp->body_as_string;
6115# endif
6116 }
6117 } else {
6118 debug_printf_exec("remembering new function '%s'\n", name);
6119 funcp = *funcpp = xzalloc(sizeof(*funcp));
6120 /*funcp->next = NULL;*/
6121 }
6122
6123 funcp->name = name;
6124 return funcp;
6125}
6126
6127static void unset_func(const char *name)
6128{
6129 struct function **funcpp = find_function_slot(name);
6130 struct function *funcp = *funcpp;
6131
6132 if (funcp != NULL) {
6133 debug_printf_exec("freeing function '%s'\n", funcp->name);
6134 *funcpp = funcp->next;
6135 /* funcp is unlinked now, deleting it.
6136 * Note: if !funcp->body, the function was created by
6137 * "-F name body", do not free ->body_as_string
6138 * and ->name as they were not malloced. */
6139 if (funcp->body) {
6140 free_pipe_list(funcp->body);
6141 free(funcp->name);
6142# if !BB_MMU
6143 free(funcp->body_as_string);
6144# endif
6145 }
6146 free(funcp);
6147 }
6148}
6149
6150# if BB_MMU
6151#define exec_function(to_free, funcp, argv) \
6152 exec_function(funcp, argv)
6153# endif
6154static void exec_function(char ***to_free,
6155 const struct function *funcp,
6156 char **argv) NORETURN;
6157static void exec_function(char ***to_free,
6158 const struct function *funcp,
6159 char **argv)
6160{
6161# if BB_MMU
6162 int n = 1;
6163
6164 argv[0] = G.global_argv[0];
6165 G.global_argv = argv;
6166 while (*++argv)
6167 n++;
6168 G.global_argc = n;
6169 /* On MMU, funcp->body is always non-NULL */
6170 n = run_list(funcp->body);
6171 fflush_all();
6172 _exit(n);
6173# else
6174 re_execute_shell(to_free,
6175 funcp->body_as_string,
6176 G.global_argv[0],
6177 argv + 1,
6178 NULL);
6179# endif
6180}
6181
6182static int run_function(const struct function *funcp, char **argv)
6183{
6184 int rc;
6185 save_arg_t sv;
6186 smallint sv_flg;
6187
6188 save_and_replace_G_args(&sv, argv);
6189
6190 /* "we are in function, ok to use return" */
6191 sv_flg = G.flag_return_in_progress;
6192 G.flag_return_in_progress = -1;
6193# if ENABLE_HUSH_LOCAL
6194 G.func_nest_level++;
6195# endif
6196
6197 /* On MMU, funcp->body is always non-NULL */
6198# if !BB_MMU
6199 if (!funcp->body) {
6200 /* Function defined by -F */
6201 parse_and_run_string(funcp->body_as_string);
6202 rc = G.last_exitcode;
6203 } else
6204# endif
6205 {
6206 rc = run_list(funcp->body);
6207 }
6208
6209# if ENABLE_HUSH_LOCAL
6210 {
6211 struct variable *var;
6212 struct variable **var_pp;
6213
6214 var_pp = &G.top_var;
6215 while ((var = *var_pp) != NULL) {
6216 if (var->func_nest_level < G.func_nest_level) {
6217 var_pp = &var->next;
6218 continue;
6219 }
6220 /* Unexport */
6221 if (var->flg_export)
6222 bb_unsetenv(var->varstr);
6223 /* Remove from global list */
6224 *var_pp = var->next;
6225 /* Free */
6226 if (!var->max_len)
6227 free(var->varstr);
6228 free(var);
6229 }
6230 G.func_nest_level--;
6231 }
6232# endif
6233 G.flag_return_in_progress = sv_flg;
6234
6235 restore_G_args(&sv, argv);
6236
6237 return rc;
6238}
6239#endif /* ENABLE_HUSH_FUNCTIONS */
6240
6241
6242#if BB_MMU
6243#define exec_builtin(to_free, x, argv) \
6244 exec_builtin(x, argv)
6245#else
6246#define exec_builtin(to_free, x, argv) \
6247 exec_builtin(to_free, argv)
6248#endif
6249static void exec_builtin(char ***to_free,
6250 const struct built_in_command *x,
6251 char **argv) NORETURN;
6252static void exec_builtin(char ***to_free,
6253 const struct built_in_command *x,
6254 char **argv)
6255{
6256#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006257 int rcode;
6258 fflush_all();
6259 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006260 fflush_all();
6261 _exit(rcode);
6262#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006263 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006264 /* On NOMMU, we must never block!
6265 * Example: { sleep 99 | read line; } & echo Ok
6266 */
6267 re_execute_shell(to_free,
6268 argv[0],
6269 G.global_argv[0],
6270 G.global_argv + 1,
6271 argv);
6272#endif
6273}
6274
6275
6276static void execvp_or_die(char **argv) NORETURN;
6277static void execvp_or_die(char **argv)
6278{
6279 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006280 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006281 execvp(argv[0], argv);
6282 bb_perror_msg("can't execute '%s'", argv[0]);
6283 _exit(127); /* bash compat */
6284}
6285
6286#if ENABLE_HUSH_MODE_X
6287static void dump_cmd_in_x_mode(char **argv)
6288{
6289 if (G_x_mode && argv) {
6290 /* We want to output the line in one write op */
6291 char *buf, *p;
6292 int len;
6293 int n;
6294
6295 len = 3;
6296 n = 0;
6297 while (argv[n])
6298 len += strlen(argv[n++]) + 1;
6299 buf = xmalloc(len);
6300 buf[0] = '+';
6301 p = buf + 1;
6302 n = 0;
6303 while (argv[n])
6304 p += sprintf(p, " %s", argv[n++]);
6305 *p++ = '\n';
6306 *p = '\0';
6307 fputs(buf, stderr);
6308 free(buf);
6309 }
6310}
6311#else
6312# define dump_cmd_in_x_mode(argv) ((void)0)
6313#endif
6314
6315#if BB_MMU
6316#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6317 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6318#define pseudo_exec(nommu_save, command, argv_expanded) \
6319 pseudo_exec(command, argv_expanded)
6320#endif
6321
6322/* Called after [v]fork() in run_pipe, or from builtin_exec.
6323 * Never returns.
6324 * Don't exit() here. If you don't exec, use _exit instead.
6325 * The at_exit handlers apparently confuse the calling process,
6326 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6327static void pseudo_exec_argv(nommu_save_t *nommu_save,
6328 char **argv, int assignment_cnt,
6329 char **argv_expanded) NORETURN;
6330static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6331 char **argv, int assignment_cnt,
6332 char **argv_expanded)
6333{
6334 char **new_env;
6335
6336 new_env = expand_assignments(argv, assignment_cnt);
6337 dump_cmd_in_x_mode(new_env);
6338
6339 if (!argv[assignment_cnt]) {
6340 /* Case when we are here: ... | var=val | ...
6341 * (note that we do not exit early, i.e., do not optimize out
6342 * expand_assignments(): think about ... | var=`sleep 1` | ...
6343 */
6344 free_strings(new_env);
6345 _exit(EXIT_SUCCESS);
6346 }
6347
6348#if BB_MMU
6349 set_vars_and_save_old(new_env);
6350 free(new_env); /* optional */
6351 /* we can also destroy set_vars_and_save_old's return value,
6352 * to save memory */
6353#else
6354 nommu_save->new_env = new_env;
6355 nommu_save->old_vars = set_vars_and_save_old(new_env);
6356#endif
6357
6358 if (argv_expanded) {
6359 argv = argv_expanded;
6360 } else {
6361 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6362#if !BB_MMU
6363 nommu_save->argv = argv;
6364#endif
6365 }
6366 dump_cmd_in_x_mode(argv);
6367
6368#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6369 if (strchr(argv[0], '/') != NULL)
6370 goto skip;
6371#endif
6372
6373 /* Check if the command matches any of the builtins.
6374 * Depending on context, this might be redundant. But it's
6375 * easier to waste a few CPU cycles than it is to figure out
6376 * if this is one of those cases.
6377 */
6378 {
6379 /* On NOMMU, it is more expensive to re-execute shell
6380 * just in order to run echo or test builtin.
6381 * It's better to skip it here and run corresponding
6382 * non-builtin later. */
6383 const struct built_in_command *x;
6384 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6385 if (x) {
6386 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6387 }
6388 }
6389#if ENABLE_HUSH_FUNCTIONS
6390 /* Check if the command matches any functions */
6391 {
6392 const struct function *funcp = find_function(argv[0]);
6393 if (funcp) {
6394 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6395 }
6396 }
6397#endif
6398
6399#if ENABLE_FEATURE_SH_STANDALONE
6400 /* Check if the command matches any busybox applets */
6401 {
6402 int a = find_applet_by_name(argv[0]);
6403 if (a >= 0) {
6404# if BB_MMU /* see above why on NOMMU it is not allowed */
6405 if (APPLET_IS_NOEXEC(a)) {
6406 debug_printf_exec("running applet '%s'\n", argv[0]);
6407 run_applet_no_and_exit(a, argv);
6408 }
6409# endif
6410 /* Re-exec ourselves */
6411 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006412 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006413 execv(bb_busybox_exec_path, argv);
6414 /* If they called chroot or otherwise made the binary no longer
6415 * executable, fall through */
6416 }
6417 }
6418#endif
6419
6420#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6421 skip:
6422#endif
6423 execvp_or_die(argv);
6424}
6425
6426/* Called after [v]fork() in run_pipe
6427 */
6428static void pseudo_exec(nommu_save_t *nommu_save,
6429 struct command *command,
6430 char **argv_expanded) NORETURN;
6431static void pseudo_exec(nommu_save_t *nommu_save,
6432 struct command *command,
6433 char **argv_expanded)
6434{
6435 if (command->argv) {
6436 pseudo_exec_argv(nommu_save, command->argv,
6437 command->assignment_cnt, argv_expanded);
6438 }
6439
6440 if (command->group) {
6441 /* Cases when we are here:
6442 * ( list )
6443 * { list } &
6444 * ... | ( list ) | ...
6445 * ... | { list } | ...
6446 */
6447#if BB_MMU
6448 int rcode;
6449 debug_printf_exec("pseudo_exec: run_list\n");
6450 reset_traps_to_defaults();
6451 rcode = run_list(command->group);
6452 /* OK to leak memory by not calling free_pipe_list,
6453 * since this process is about to exit */
6454 _exit(rcode);
6455#else
6456 re_execute_shell(&nommu_save->argv_from_re_execing,
6457 command->group_as_string,
6458 G.global_argv[0],
6459 G.global_argv + 1,
6460 NULL);
6461#endif
6462 }
6463
6464 /* Case when we are here: ... | >file */
6465 debug_printf_exec("pseudo_exec'ed null command\n");
6466 _exit(EXIT_SUCCESS);
6467}
6468
6469#if ENABLE_HUSH_JOB
6470static const char *get_cmdtext(struct pipe *pi)
6471{
6472 char **argv;
6473 char *p;
6474 int len;
6475
6476 /* This is subtle. ->cmdtext is created only on first backgrounding.
6477 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6478 * On subsequent bg argv is trashed, but we won't use it */
6479 if (pi->cmdtext)
6480 return pi->cmdtext;
6481 argv = pi->cmds[0].argv;
6482 if (!argv || !argv[0]) {
6483 pi->cmdtext = xzalloc(1);
6484 return pi->cmdtext;
6485 }
6486
6487 len = 0;
6488 do {
6489 len += strlen(*argv) + 1;
6490 } while (*++argv);
6491 p = xmalloc(len);
6492 pi->cmdtext = p;
6493 argv = pi->cmds[0].argv;
6494 do {
6495 len = strlen(*argv);
6496 memcpy(p, *argv, len);
6497 p += len;
6498 *p++ = ' ';
6499 } while (*++argv);
6500 p[-1] = '\0';
6501 return pi->cmdtext;
6502}
6503
6504static void insert_bg_job(struct pipe *pi)
6505{
6506 struct pipe *job, **jobp;
6507 int i;
6508
6509 /* Linear search for the ID of the job to use */
6510 pi->jobid = 1;
6511 for (job = G.job_list; job; job = job->next)
6512 if (job->jobid >= pi->jobid)
6513 pi->jobid = job->jobid + 1;
6514
6515 /* Add job to the list of running jobs */
6516 jobp = &G.job_list;
6517 while ((job = *jobp) != NULL)
6518 jobp = &job->next;
6519 job = *jobp = xmalloc(sizeof(*job));
6520
6521 *job = *pi; /* physical copy */
6522 job->next = NULL;
6523 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6524 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6525 for (i = 0; i < pi->num_cmds; i++) {
6526 job->cmds[i].pid = pi->cmds[i].pid;
6527 /* all other fields are not used and stay zero */
6528 }
6529 job->cmdtext = xstrdup(get_cmdtext(pi));
6530
6531 if (G_interactive_fd)
6532 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6533 G.last_jobid = job->jobid;
6534}
6535
6536static void remove_bg_job(struct pipe *pi)
6537{
6538 struct pipe *prev_pipe;
6539
6540 if (pi == G.job_list) {
6541 G.job_list = pi->next;
6542 } else {
6543 prev_pipe = G.job_list;
6544 while (prev_pipe->next != pi)
6545 prev_pipe = prev_pipe->next;
6546 prev_pipe->next = pi->next;
6547 }
6548 if (G.job_list)
6549 G.last_jobid = G.job_list->jobid;
6550 else
6551 G.last_jobid = 0;
6552}
6553
6554/* Remove a backgrounded job */
6555static void delete_finished_bg_job(struct pipe *pi)
6556{
6557 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006558 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006559}
6560#endif /* JOB */
6561
6562/* Check to see if any processes have exited -- if they
6563 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006564static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006565{
6566 int attributes;
6567 int status;
6568#if ENABLE_HUSH_JOB
6569 struct pipe *pi;
6570#endif
6571 pid_t childpid;
6572 int rcode = 0;
6573
6574 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6575
6576 attributes = WUNTRACED;
6577 if (fg_pipe == NULL)
6578 attributes |= WNOHANG;
6579
6580 errno = 0;
6581#if ENABLE_HUSH_FAST
6582 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6583//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6584//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6585 /* There was neither fork nor SIGCHLD since last waitpid */
6586 /* Avoid doing waitpid syscall if possible */
6587 if (!G.we_have_children) {
6588 errno = ECHILD;
6589 return -1;
6590 }
6591 if (fg_pipe == NULL) { /* is WNOHANG set? */
6592 /* We have children, but they did not exit
6593 * or stop yet (we saw no SIGCHLD) */
6594 return 0;
6595 }
6596 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6597 }
6598#endif
6599
6600/* Do we do this right?
6601 * bash-3.00# sleep 20 | false
6602 * <ctrl-Z pressed>
6603 * [3]+ Stopped sleep 20 | false
6604 * bash-3.00# echo $?
6605 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6606 * [hush 1.14.0: yes we do it right]
6607 */
6608 wait_more:
6609 while (1) {
6610 int i;
6611 int dead;
6612
6613#if ENABLE_HUSH_FAST
6614 i = G.count_SIGCHLD;
6615#endif
6616 childpid = waitpid(-1, &status, attributes);
6617 if (childpid <= 0) {
6618 if (childpid && errno != ECHILD)
6619 bb_perror_msg("waitpid");
6620#if ENABLE_HUSH_FAST
6621 else { /* Until next SIGCHLD, waitpid's are useless */
6622 G.we_have_children = (childpid == 0);
6623 G.handled_SIGCHLD = i;
6624//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6625 }
6626#endif
6627 break;
6628 }
6629 dead = WIFEXITED(status) || WIFSIGNALED(status);
6630
6631#if DEBUG_JOBS
6632 if (WIFSTOPPED(status))
6633 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6634 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6635 if (WIFSIGNALED(status))
6636 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6637 childpid, WTERMSIG(status), WEXITSTATUS(status));
6638 if (WIFEXITED(status))
6639 debug_printf_jobs("pid %d exited, exitcode %d\n",
6640 childpid, WEXITSTATUS(status));
6641#endif
6642 /* Were we asked to wait for fg pipe? */
6643 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006644 i = fg_pipe->num_cmds;
6645 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006646 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6647 if (fg_pipe->cmds[i].pid != childpid)
6648 continue;
6649 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006650 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006651 fg_pipe->cmds[i].pid = 0;
6652 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006653 ex = WEXITSTATUS(status);
6654 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006655 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006656 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6657 */
6658 if (WIFSIGNALED(status)) {
6659 int sig = WTERMSIG(status);
6660 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006661 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6662 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6663 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006664 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6665 * Maybe we need to use sig | 128? */
6666 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006667 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006668 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006669 } else {
6670 fg_pipe->cmds[i].is_stopped = 1;
6671 fg_pipe->stopped_cmds++;
6672 }
6673 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6674 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006675 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006676 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006677 i = fg_pipe->num_cmds;
6678 while (--i >= 0) {
6679 rcode = fg_pipe->cmds[i].cmd_exitcode;
6680 /* usually last process gives overall exitstatus,
6681 * but with "set -o pipefail", last *failed* process does */
6682 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6683 break;
6684 }
6685 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006686/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6687 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6688 * and "killall -STOP cat" */
6689 if (G_interactive_fd) {
6690#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006691 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006692 insert_bg_job(fg_pipe);
6693#endif
6694 return rcode;
6695 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006696 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006697 return rcode;
6698 }
6699 /* There are still running processes in the fg pipe */
6700 goto wait_more; /* do waitpid again */
6701 }
6702 /* it wasnt fg_pipe, look for process in bg pipes */
6703 }
6704
6705#if ENABLE_HUSH_JOB
6706 /* We asked to wait for bg or orphaned children */
6707 /* No need to remember exitcode in this case */
6708 for (pi = G.job_list; pi; pi = pi->next) {
6709 for (i = 0; i < pi->num_cmds; i++) {
6710 if (pi->cmds[i].pid == childpid)
6711 goto found_pi_and_prognum;
6712 }
6713 }
6714 /* Happens when shell is used as init process (init=/bin/sh) */
6715 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6716 continue; /* do waitpid again */
6717
6718 found_pi_and_prognum:
6719 if (dead) {
6720 /* child exited */
6721 pi->cmds[i].pid = 0;
6722 pi->alive_cmds--;
6723 if (!pi->alive_cmds) {
6724 if (G_interactive_fd)
6725 printf(JOB_STATUS_FORMAT, pi->jobid,
6726 "Done", pi->cmdtext);
6727 delete_finished_bg_job(pi);
6728 }
6729 } else {
6730 /* child stopped */
6731 pi->cmds[i].is_stopped = 1;
6732 pi->stopped_cmds++;
6733 }
6734#endif
6735 } /* while (waitpid succeeds)... */
6736
6737 return rcode;
6738}
6739
6740#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006741static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006742{
6743 pid_t p;
6744 int rcode = checkjobs(fg_pipe);
6745 if (G_saved_tty_pgrp) {
6746 /* Job finished, move the shell to the foreground */
6747 p = getpgrp(); /* our process group id */
6748 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6749 tcsetpgrp(G_interactive_fd, p);
6750 }
6751 return rcode;
6752}
6753#endif
6754
6755/* Start all the jobs, but don't wait for anything to finish.
6756 * See checkjobs().
6757 *
6758 * Return code is normally -1, when the caller has to wait for children
6759 * to finish to determine the exit status of the pipe. If the pipe
6760 * is a simple builtin command, however, the action is done by the
6761 * time run_pipe returns, and the exit code is provided as the
6762 * return value.
6763 *
6764 * Returns -1 only if started some children. IOW: we have to
6765 * mask out retvals of builtins etc with 0xff!
6766 *
6767 * The only case when we do not need to [v]fork is when the pipe
6768 * is single, non-backgrounded, non-subshell command. Examples:
6769 * cmd ; ... { list } ; ...
6770 * cmd && ... { list } && ...
6771 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006772 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006773 * or (if SH_STANDALONE) an applet, and we can run the { list }
6774 * with run_list. If it isn't one of these, we fork and exec cmd.
6775 *
6776 * Cases when we must fork:
6777 * non-single: cmd | cmd
6778 * backgrounded: cmd & { list } &
6779 * subshell: ( list ) [&]
6780 */
6781#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006782#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006783 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6784#endif
6785static int redirect_and_varexp_helper(char ***new_env_p,
6786 struct variable **old_vars_p,
6787 struct command *command,
6788 int squirrel[3],
6789 char **argv_expanded)
6790{
6791 /* setup_redirects acts on file descriptors, not FILEs.
6792 * This is perfect for work that comes after exec().
6793 * Is it really safe for inline use? Experimentally,
6794 * things seem to work. */
6795 int rcode = setup_redirects(command, squirrel);
6796 if (rcode == 0) {
6797 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6798 *new_env_p = new_env;
6799 dump_cmd_in_x_mode(new_env);
6800 dump_cmd_in_x_mode(argv_expanded);
6801 if (old_vars_p)
6802 *old_vars_p = set_vars_and_save_old(new_env);
6803 }
6804 return rcode;
6805}
6806static NOINLINE int run_pipe(struct pipe *pi)
6807{
6808 static const char *const null_ptr = NULL;
6809
6810 int cmd_no;
6811 int next_infd;
6812 struct command *command;
6813 char **argv_expanded;
6814 char **argv;
6815 /* it is not always needed, but we aim to smaller code */
6816 int squirrel[] = { -1, -1, -1 };
6817 int rcode;
6818
6819 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6820 debug_enter();
6821
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006822 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6823 * Result should be 3 lines: q w e, qwe, q w e
6824 */
6825 G.ifs = get_local_var_value("IFS");
6826 if (!G.ifs)
6827 G.ifs = defifs;
6828
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006829 IF_HUSH_JOB(pi->pgrp = -1;)
6830 pi->stopped_cmds = 0;
6831 command = &pi->cmds[0];
6832 argv_expanded = NULL;
6833
6834 if (pi->num_cmds != 1
6835 || pi->followup == PIPE_BG
6836 || command->cmd_type == CMD_SUBSHELL
6837 ) {
6838 goto must_fork;
6839 }
6840
6841 pi->alive_cmds = 1;
6842
6843 debug_printf_exec(": group:%p argv:'%s'\n",
6844 command->group, command->argv ? command->argv[0] : "NONE");
6845
6846 if (command->group) {
6847#if ENABLE_HUSH_FUNCTIONS
6848 if (command->cmd_type == CMD_FUNCDEF) {
6849 /* "executing" func () { list } */
6850 struct function *funcp;
6851
6852 funcp = new_function(command->argv[0]);
6853 /* funcp->name is already set to argv[0] */
6854 funcp->body = command->group;
6855# if !BB_MMU
6856 funcp->body_as_string = command->group_as_string;
6857 command->group_as_string = NULL;
6858# endif
6859 command->group = NULL;
6860 command->argv[0] = NULL;
6861 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6862 funcp->parent_cmd = command;
6863 command->child_func = funcp;
6864
6865 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6866 debug_leave();
6867 return EXIT_SUCCESS;
6868 }
6869#endif
6870 /* { list } */
6871 debug_printf("non-subshell group\n");
6872 rcode = 1; /* exitcode if redir failed */
6873 if (setup_redirects(command, squirrel) == 0) {
6874 debug_printf_exec(": run_list\n");
6875 rcode = run_list(command->group) & 0xff;
6876 }
6877 restore_redirects(squirrel);
6878 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6879 debug_leave();
6880 debug_printf_exec("run_pipe: return %d\n", rcode);
6881 return rcode;
6882 }
6883
6884 argv = command->argv ? command->argv : (char **) &null_ptr;
6885 {
6886 const struct built_in_command *x;
6887#if ENABLE_HUSH_FUNCTIONS
6888 const struct function *funcp;
6889#else
6890 enum { funcp = 0 };
6891#endif
6892 char **new_env = NULL;
6893 struct variable *old_vars = NULL;
6894
6895 if (argv[command->assignment_cnt] == NULL) {
6896 /* Assignments, but no command */
6897 /* Ensure redirects take effect (that is, create files).
6898 * Try "a=t >file" */
6899#if 0 /* A few cases in testsuite fail with this code. FIXME */
6900 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6901 /* Set shell variables */
6902 if (new_env) {
6903 argv = new_env;
6904 while (*argv) {
6905 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6906 /* Do we need to flag set_local_var() errors?
6907 * "assignment to readonly var" and "putenv error"
6908 */
6909 argv++;
6910 }
6911 }
6912 /* Redirect error sets $? to 1. Otherwise,
6913 * if evaluating assignment value set $?, retain it.
6914 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6915 if (rcode == 0)
6916 rcode = G.last_exitcode;
6917 /* Exit, _skipping_ variable restoring code: */
6918 goto clean_up_and_ret0;
6919
6920#else /* Older, bigger, but more correct code */
6921
6922 rcode = setup_redirects(command, squirrel);
6923 restore_redirects(squirrel);
6924 /* Set shell variables */
6925 if (G_x_mode)
6926 bb_putchar_stderr('+');
6927 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006928 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006929 if (G_x_mode)
6930 fprintf(stderr, " %s", p);
6931 debug_printf_exec("set shell var:'%s'->'%s'\n",
6932 *argv, p);
6933 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6934 /* Do we need to flag set_local_var() errors?
6935 * "assignment to readonly var" and "putenv error"
6936 */
6937 argv++;
6938 }
6939 if (G_x_mode)
6940 bb_putchar_stderr('\n');
6941 /* Redirect error sets $? to 1. Otherwise,
6942 * if evaluating assignment value set $?, retain it.
6943 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6944 if (rcode == 0)
6945 rcode = G.last_exitcode;
6946 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6947 debug_leave();
6948 debug_printf_exec("run_pipe: return %d\n", rcode);
6949 return rcode;
6950#endif
6951 }
6952
6953 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006954#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006955 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006956 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006957 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006958#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006959 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006960 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6961 }
6962
6963 /* if someone gives us an empty string: `cmd with empty output` */
6964 if (!argv_expanded[0]) {
6965 free(argv_expanded);
6966 debug_leave();
6967 return G.last_exitcode;
6968 }
6969
6970 x = find_builtin(argv_expanded[0]);
6971#if ENABLE_HUSH_FUNCTIONS
6972 funcp = NULL;
6973 if (!x)
6974 funcp = find_function(argv_expanded[0]);
6975#endif
6976 if (x || funcp) {
6977 if (!funcp) {
6978 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6979 debug_printf("exec with redirects only\n");
6980 rcode = setup_redirects(command, NULL);
6981 goto clean_up_and_ret1;
6982 }
6983 }
6984 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6985 if (rcode == 0) {
6986 if (!funcp) {
6987 debug_printf_exec(": builtin '%s' '%s'...\n",
6988 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006989 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006990 rcode = x->b_function(argv_expanded) & 0xff;
6991 fflush_all();
6992 }
6993#if ENABLE_HUSH_FUNCTIONS
6994 else {
6995# if ENABLE_HUSH_LOCAL
6996 struct variable **sv;
6997 sv = G.shadowed_vars_pp;
6998 G.shadowed_vars_pp = &old_vars;
6999# endif
7000 debug_printf_exec(": function '%s' '%s'...\n",
7001 funcp->name, argv_expanded[1]);
7002 rcode = run_function(funcp, argv_expanded) & 0xff;
7003# if ENABLE_HUSH_LOCAL
7004 G.shadowed_vars_pp = sv;
7005# endif
7006 }
7007#endif
7008 }
7009 clean_up_and_ret:
7010 unset_vars(new_env);
7011 add_vars(old_vars);
7012/* clean_up_and_ret0: */
7013 restore_redirects(squirrel);
7014 clean_up_and_ret1:
7015 free(argv_expanded);
7016 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7017 debug_leave();
7018 debug_printf_exec("run_pipe return %d\n", rcode);
7019 return rcode;
7020 }
7021
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007022 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007023 int n = find_applet_by_name(argv_expanded[0]);
7024 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7025 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7026 if (rcode == 0) {
7027 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7028 argv_expanded[0], argv_expanded[1]);
7029 rcode = run_nofork_applet(n, argv_expanded);
7030 }
7031 goto clean_up_and_ret;
7032 }
7033 }
7034 /* It is neither builtin nor applet. We must fork. */
7035 }
7036
7037 must_fork:
7038 /* NB: argv_expanded may already be created, and that
7039 * might include `cmd` runs! Do not rerun it! We *must*
7040 * use argv_expanded if it's non-NULL */
7041
7042 /* Going to fork a child per each pipe member */
7043 pi->alive_cmds = 0;
7044 next_infd = 0;
7045
7046 cmd_no = 0;
7047 while (cmd_no < pi->num_cmds) {
7048 struct fd_pair pipefds;
7049#if !BB_MMU
7050 volatile nommu_save_t nommu_save;
7051 nommu_save.new_env = NULL;
7052 nommu_save.old_vars = NULL;
7053 nommu_save.argv = NULL;
7054 nommu_save.argv_from_re_execing = NULL;
7055#endif
7056 command = &pi->cmds[cmd_no];
7057 cmd_no++;
7058 if (command->argv) {
7059 debug_printf_exec(": pipe member '%s' '%s'...\n",
7060 command->argv[0], command->argv[1]);
7061 } else {
7062 debug_printf_exec(": pipe member with no argv\n");
7063 }
7064
7065 /* pipes are inserted between pairs of commands */
7066 pipefds.rd = 0;
7067 pipefds.wr = 1;
7068 if (cmd_no < pi->num_cmds)
7069 xpiped_pair(pipefds);
7070
7071 command->pid = BB_MMU ? fork() : vfork();
7072 if (!command->pid) { /* child */
7073#if ENABLE_HUSH_JOB
7074 disable_restore_tty_pgrp_on_exit();
7075 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7076
7077 /* Every child adds itself to new process group
7078 * with pgid == pid_of_first_child_in_pipe */
7079 if (G.run_list_level == 1 && G_interactive_fd) {
7080 pid_t pgrp;
7081 pgrp = pi->pgrp;
7082 if (pgrp < 0) /* true for 1st process only */
7083 pgrp = getpid();
7084 if (setpgid(0, pgrp) == 0
7085 && pi->followup != PIPE_BG
7086 && G_saved_tty_pgrp /* we have ctty */
7087 ) {
7088 /* We do it in *every* child, not just first,
7089 * to avoid races */
7090 tcsetpgrp(G_interactive_fd, pgrp);
7091 }
7092 }
7093#endif
7094 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7095 /* 1st cmd in backgrounded pipe
7096 * should have its stdin /dev/null'ed */
7097 close(0);
7098 if (open(bb_dev_null, O_RDONLY))
7099 xopen("/", O_RDONLY);
7100 } else {
7101 xmove_fd(next_infd, 0);
7102 }
7103 xmove_fd(pipefds.wr, 1);
7104 if (pipefds.rd > 1)
7105 close(pipefds.rd);
7106 /* Like bash, explicit redirects override pipes,
7107 * and the pipe fd is available for dup'ing. */
7108 if (setup_redirects(command, NULL))
7109 _exit(1);
7110
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007111 /* Stores to nommu_save list of env vars putenv'ed
7112 * (NOMMU, on MMU we don't need that) */
7113 /* cast away volatility... */
7114 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7115 /* pseudo_exec() does not return */
7116 }
7117
7118 /* parent or error */
7119#if ENABLE_HUSH_FAST
7120 G.count_SIGCHLD++;
7121//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7122#endif
7123 enable_restore_tty_pgrp_on_exit();
7124#if !BB_MMU
7125 /* Clean up after vforked child */
7126 free(nommu_save.argv);
7127 free(nommu_save.argv_from_re_execing);
7128 unset_vars(nommu_save.new_env);
7129 add_vars(nommu_save.old_vars);
7130#endif
7131 free(argv_expanded);
7132 argv_expanded = NULL;
7133 if (command->pid < 0) { /* [v]fork failed */
7134 /* Clearly indicate, was it fork or vfork */
7135 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7136 } else {
7137 pi->alive_cmds++;
7138#if ENABLE_HUSH_JOB
7139 /* Second and next children need to know pid of first one */
7140 if (pi->pgrp < 0)
7141 pi->pgrp = command->pid;
7142#endif
7143 }
7144
7145 if (cmd_no > 1)
7146 close(next_infd);
7147 if (cmd_no < pi->num_cmds)
7148 close(pipefds.wr);
7149 /* Pass read (output) pipe end to next iteration */
7150 next_infd = pipefds.rd;
7151 }
7152
7153 if (!pi->alive_cmds) {
7154 debug_leave();
7155 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7156 return 1;
7157 }
7158
7159 debug_leave();
7160 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7161 return -1;
7162}
7163
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007164/* NB: called by pseudo_exec, and therefore must not modify any
7165 * global data until exec/_exit (we can be a child after vfork!) */
7166static int run_list(struct pipe *pi)
7167{
7168#if ENABLE_HUSH_CASE
7169 char *case_word = NULL;
7170#endif
7171#if ENABLE_HUSH_LOOPS
7172 struct pipe *loop_top = NULL;
7173 char **for_lcur = NULL;
7174 char **for_list = NULL;
7175#endif
7176 smallint last_followup;
7177 smalluint rcode;
7178#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7179 smalluint cond_code = 0;
7180#else
7181 enum { cond_code = 0 };
7182#endif
7183#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007184 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007185 smallint last_rword; /* ditto */
7186#endif
7187
7188 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7189 debug_enter();
7190
7191#if ENABLE_HUSH_LOOPS
7192 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007193 {
7194 struct pipe *cpipe;
7195 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7196 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7197 continue;
7198 /* current word is FOR or IN (BOLD in comments below) */
7199 if (cpipe->next == NULL) {
7200 syntax_error("malformed for");
7201 debug_leave();
7202 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7203 return 1;
7204 }
7205 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7206 if (cpipe->next->res_word == RES_DO)
7207 continue;
7208 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7209 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7210 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7211 ) {
7212 syntax_error("malformed for");
7213 debug_leave();
7214 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7215 return 1;
7216 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007217 }
7218 }
7219#endif
7220
7221 /* Past this point, all code paths should jump to ret: label
7222 * in order to return, no direct "return" statements please.
7223 * This helps to ensure that no memory is leaked. */
7224
7225#if ENABLE_HUSH_JOB
7226 G.run_list_level++;
7227#endif
7228
7229#if HAS_KEYWORDS
7230 rword = RES_NONE;
7231 last_rword = RES_XXXX;
7232#endif
7233 last_followup = PIPE_SEQ;
7234 rcode = G.last_exitcode;
7235
7236 /* Go through list of pipes, (maybe) executing them. */
7237 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7238 if (G.flag_SIGINT)
7239 break;
7240
7241 IF_HAS_KEYWORDS(rword = pi->res_word;)
7242 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7243 rword, cond_code, last_rword);
7244#if ENABLE_HUSH_LOOPS
7245 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7246 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7247 ) {
7248 /* start of a loop: remember where loop starts */
7249 loop_top = pi;
7250 G.depth_of_loop++;
7251 }
7252#endif
7253 /* Still in the same "if...", "then..." or "do..." branch? */
7254 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7255 if ((rcode == 0 && last_followup == PIPE_OR)
7256 || (rcode != 0 && last_followup == PIPE_AND)
7257 ) {
7258 /* It is "<true> || CMD" or "<false> && CMD"
7259 * and we should not execute CMD */
7260 debug_printf_exec("skipped cmd because of || or &&\n");
7261 last_followup = pi->followup;
7262 continue;
7263 }
7264 }
7265 last_followup = pi->followup;
7266 IF_HAS_KEYWORDS(last_rword = rword;)
7267#if ENABLE_HUSH_IF
7268 if (cond_code) {
7269 if (rword == RES_THEN) {
7270 /* if false; then ... fi has exitcode 0! */
7271 G.last_exitcode = rcode = EXIT_SUCCESS;
7272 /* "if <false> THEN cmd": skip cmd */
7273 continue;
7274 }
7275 } else {
7276 if (rword == RES_ELSE || rword == RES_ELIF) {
7277 /* "if <true> then ... ELSE/ELIF cmd":
7278 * skip cmd and all following ones */
7279 break;
7280 }
7281 }
7282#endif
7283#if ENABLE_HUSH_LOOPS
7284 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7285 if (!for_lcur) {
7286 /* first loop through for */
7287
7288 static const char encoded_dollar_at[] ALIGN1 = {
7289 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7290 }; /* encoded representation of "$@" */
7291 static const char *const encoded_dollar_at_argv[] = {
7292 encoded_dollar_at, NULL
7293 }; /* argv list with one element: "$@" */
7294 char **vals;
7295
7296 vals = (char**)encoded_dollar_at_argv;
7297 if (pi->next->res_word == RES_IN) {
7298 /* if no variable values after "in" we skip "for" */
7299 if (!pi->next->cmds[0].argv) {
7300 G.last_exitcode = rcode = EXIT_SUCCESS;
7301 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7302 break;
7303 }
7304 vals = pi->next->cmds[0].argv;
7305 } /* else: "for var; do..." -> assume "$@" list */
7306 /* create list of variable values */
7307 debug_print_strings("for_list made from", vals);
7308 for_list = expand_strvec_to_strvec(vals);
7309 for_lcur = for_list;
7310 debug_print_strings("for_list", for_list);
7311 }
7312 if (!*for_lcur) {
7313 /* "for" loop is over, clean up */
7314 free(for_list);
7315 for_list = NULL;
7316 for_lcur = NULL;
7317 break;
7318 }
7319 /* Insert next value from for_lcur */
7320 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7321 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7322 continue;
7323 }
7324 if (rword == RES_IN) {
7325 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7326 }
7327 if (rword == RES_DONE) {
7328 continue; /* "done" has no cmds too */
7329 }
7330#endif
7331#if ENABLE_HUSH_CASE
7332 if (rword == RES_CASE) {
7333 case_word = expand_strvec_to_string(pi->cmds->argv);
7334 continue;
7335 }
7336 if (rword == RES_MATCH) {
7337 char **argv;
7338
7339 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7340 break;
7341 /* all prev words didn't match, does this one match? */
7342 argv = pi->cmds->argv;
7343 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007344 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007345 /* TODO: which FNM_xxx flags to use? */
7346 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7347 free(pattern);
7348 if (cond_code == 0) { /* match! we will execute this branch */
7349 free(case_word); /* make future "word)" stop */
7350 case_word = NULL;
7351 break;
7352 }
7353 argv++;
7354 }
7355 continue;
7356 }
7357 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7358 if (cond_code != 0)
7359 continue; /* not matched yet, skip this pipe */
7360 }
7361#endif
7362 /* Just pressing <enter> in shell should check for jobs.
7363 * OTOH, in non-interactive shell this is useless
7364 * and only leads to extra job checks */
7365 if (pi->num_cmds == 0) {
7366 if (G_interactive_fd)
7367 goto check_jobs_and_continue;
7368 continue;
7369 }
7370
7371 /* After analyzing all keywords and conditions, we decided
7372 * to execute this pipe. NB: have to do checkjobs(NULL)
7373 * after run_pipe to collect any background children,
7374 * even if list execution is to be stopped. */
7375 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7376 {
7377 int r;
7378#if ENABLE_HUSH_LOOPS
7379 G.flag_break_continue = 0;
7380#endif
7381 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7382 if (r != -1) {
7383 /* We ran a builtin, function, or group.
7384 * rcode is already known
7385 * and we don't need to wait for anything. */
7386 G.last_exitcode = rcode;
7387 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007388 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007389#if ENABLE_HUSH_LOOPS
7390 /* Was it "break" or "continue"? */
7391 if (G.flag_break_continue) {
7392 smallint fbc = G.flag_break_continue;
7393 /* We might fall into outer *loop*,
7394 * don't want to break it too */
7395 if (loop_top) {
7396 G.depth_break_continue--;
7397 if (G.depth_break_continue == 0)
7398 G.flag_break_continue = 0;
7399 /* else: e.g. "continue 2" should *break* once, *then* continue */
7400 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7401 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7402 goto check_jobs_and_break;
7403 /* "continue": simulate end of loop */
7404 rword = RES_DONE;
7405 continue;
7406 }
7407#endif
7408#if ENABLE_HUSH_FUNCTIONS
7409 if (G.flag_return_in_progress == 1) {
7410 /* same as "goto check_jobs_and_break" */
7411 checkjobs(NULL);
7412 break;
7413 }
7414#endif
7415 } else if (pi->followup == PIPE_BG) {
7416 /* What does bash do with attempts to background builtins? */
7417 /* even bash 3.2 doesn't do that well with nested bg:
7418 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7419 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007420 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007421#if ENABLE_HUSH_JOB
7422 if (G.run_list_level == 1)
7423 insert_bg_job(pi);
7424#endif
7425 /* Last command's pid goes to $! */
7426 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7427 G.last_exitcode = rcode = EXIT_SUCCESS;
7428 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7429 } else {
7430#if ENABLE_HUSH_JOB
7431 if (G.run_list_level == 1 && G_interactive_fd) {
7432 /* Waits for completion, then fg's main shell */
7433 rcode = checkjobs_and_fg_shell(pi);
7434 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007435 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007436 } else
7437#endif
7438 { /* This one just waits for completion */
7439 rcode = checkjobs(pi);
7440 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007441 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007442 }
7443 G.last_exitcode = rcode;
7444 }
7445 }
7446
7447 /* Analyze how result affects subsequent commands */
7448#if ENABLE_HUSH_IF
7449 if (rword == RES_IF || rword == RES_ELIF)
7450 cond_code = rcode;
7451#endif
7452#if ENABLE_HUSH_LOOPS
7453 /* Beware of "while false; true; do ..."! */
7454 if (pi->next && pi->next->res_word == RES_DO) {
7455 if (rword == RES_WHILE) {
7456 if (rcode) {
7457 /* "while false; do...done" - exitcode 0 */
7458 G.last_exitcode = rcode = EXIT_SUCCESS;
7459 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7460 goto check_jobs_and_break;
7461 }
7462 }
7463 if (rword == RES_UNTIL) {
7464 if (!rcode) {
7465 debug_printf_exec(": until expr is true: breaking\n");
7466 check_jobs_and_break:
7467 checkjobs(NULL);
7468 break;
7469 }
7470 }
7471 }
7472#endif
7473
7474 check_jobs_and_continue:
7475 checkjobs(NULL);
7476 } /* for (pi) */
7477
7478#if ENABLE_HUSH_JOB
7479 G.run_list_level--;
7480#endif
7481#if ENABLE_HUSH_LOOPS
7482 if (loop_top)
7483 G.depth_of_loop--;
7484 free(for_list);
7485#endif
7486#if ENABLE_HUSH_CASE
7487 free(case_word);
7488#endif
7489 debug_leave();
7490 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7491 return rcode;
7492}
7493
7494/* Select which version we will use */
7495static int run_and_free_list(struct pipe *pi)
7496{
7497 int rcode = 0;
7498 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007499 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007500 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7501 rcode = run_list(pi);
7502 }
7503 /* free_pipe_list has the side effect of clearing memory.
7504 * In the long run that function can be merged with run_list,
7505 * but doing that now would hobble the debugging effort. */
7506 free_pipe_list(pi);
7507 debug_printf_exec("run_and_free_list return %d\n", rcode);
7508 return rcode;
7509}
7510
7511
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007512static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007513{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007514 sighandler_t old_handler;
7515 unsigned sig = 0;
7516 while ((mask >>= 1) != 0) {
7517 sig++;
7518 if (!(mask & 1))
7519 continue;
7520 old_handler = signal(sig, pick_sighandler(sig));
7521 /* POSIX allows shell to re-enable SIGCHLD
7522 * even if it was SIG_IGN on entry.
7523 * Therefore we skip IGN check for it:
7524 */
7525 if (sig == SIGCHLD)
7526 continue;
7527 if (old_handler == SIG_IGN) {
7528 /* oops... restore back to IGN, and record this fact */
7529 signal(sig, old_handler);
7530 if (!G.traps)
7531 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7532 free(G.traps[sig]);
7533 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7534 }
7535 }
7536}
7537
7538/* Called a few times only (or even once if "sh -c") */
7539static void install_special_sighandlers(void)
7540{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007541 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007542
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007543 if (G.special_sig_mask != 0)
7544 return;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007545
7546 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007547 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007548 if (G_interactive_fd) {
7549 mask |= SPECIAL_INTERACTIVE_SIGS;
7550 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007551 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007552 }
Denys Vlasenko10c01312011-05-11 11:49:21 +02007553 G.special_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007554
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007555 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007556}
7557
7558#if ENABLE_HUSH_JOB
7559/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007560/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007561static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007562{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007563 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007564
7565 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007566 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007567 + (1 << SIGILL ) * HUSH_DEBUG
7568 + (1 << SIGFPE ) * HUSH_DEBUG
7569 + (1 << SIGBUS ) * HUSH_DEBUG
7570 + (1 << SIGSEGV) * HUSH_DEBUG
7571 + (1 << SIGTRAP) * HUSH_DEBUG
7572 + (1 << SIGABRT)
7573 /* bash 3.2 seems to handle these just like 'fatal' ones */
7574 + (1 << SIGPIPE)
7575 + (1 << SIGALRM)
7576 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
7577 * if we aren't interactive... but in this case
7578 * we never want to restore pgrp on exit, and this fn is not called */
7579 /*+ (1 << SIGHUP )*/
7580 /*+ (1 << SIGTERM)*/
7581 /*+ (1 << SIGINT )*/
7582 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007583 /* special_sig_mask'ed signals are set to record_pending_signo
Denis Vlasenkof9375282009-04-05 19:13:39 +00007584 * no need to set handler for them.
7585 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007586 /*mask &= ~G.special_sig_mask; - they never overlap */
7587 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007588
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007589 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007590}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007591#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007592
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007593static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007594{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007595 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007596 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007597 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007598 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007599 break;
7600 case 'x':
7601 IF_HUSH_MODE_X(G_x_mode = state;)
7602 break;
7603 case 'o':
7604 if (!o_opt) {
7605 /* "set -+o" without parameter.
7606 * in bash, set -o produces this output:
7607 * pipefail off
7608 * and set +o:
7609 * set +o pipefail
7610 * We always use the second form.
7611 */
7612 const char *p = o_opt_strings;
7613 idx = 0;
7614 while (*p) {
7615 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7616 idx++;
7617 p += strlen(p) + 1;
7618 }
7619 break;
7620 }
7621 idx = index_in_strings(o_opt_strings, o_opt);
7622 if (idx >= 0) {
7623 G.o_opt[idx] = state;
7624 break;
7625 }
7626 default:
7627 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007628 }
7629 return EXIT_SUCCESS;
7630}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007631
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007632int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007633int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007634{
7635 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007636 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007637 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007638 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007639 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007640
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007641 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02007642 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007643 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenko10c01312011-05-11 11:49:21 +02007644#if ENABLE_HUSH_FAST
7645 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7646#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007647#if !BB_MMU
7648 G.argv0_for_re_execing = argv[0];
7649#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007650 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007651 shell_ver = xzalloc(sizeof(*shell_ver));
7652 shell_ver->flg_export = 1;
7653 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007654 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007655 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007656 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007657 /* Create shell local variables from the values
7658 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007659 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007660 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007661 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007662 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007663 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007664 if (e) while (*e) {
7665 char *value = strchr(*e, '=');
7666 if (value) { /* paranoia */
7667 cur_var->next = xzalloc(sizeof(*cur_var));
7668 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007669 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007670 cur_var->max_len = strlen(*e);
7671 cur_var->flg_export = 1;
7672 }
7673 e++;
7674 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007675 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007676 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7677 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007678
7679 /* Export PWD */
7680 set_pwd_var(/*exp:*/ 1);
7681 /* bash also exports SHLVL and _,
7682 * and sets (but doesn't export) the following variables:
7683 * BASH=/bin/bash
7684 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7685 * BASH_VERSION='3.2.0(1)-release'
7686 * HOSTTYPE=i386
7687 * MACHTYPE=i386-pc-linux-gnu
7688 * OSTYPE=linux-gnu
7689 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007690 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007691 * EUID=<NNNNN>
7692 * UID=<NNNNN>
7693 * GROUPS=()
7694 * LINES=<NNN>
7695 * COLUMNS=<NNN>
7696 * BASH_ARGC=()
7697 * BASH_ARGV=()
7698 * BASH_LINENO=()
7699 * BASH_SOURCE=()
7700 * DIRSTACK=()
7701 * PIPESTATUS=([0]="0")
7702 * HISTFILE=/<xxx>/.bash_history
7703 * HISTFILESIZE=500
7704 * HISTSIZE=500
7705 * MAILCHECK=60
7706 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7707 * SHELL=/bin/bash
7708 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7709 * TERM=dumb
7710 * OPTERR=1
7711 * OPTIND=1
7712 * IFS=$' \t\n'
7713 * PS1='\s-\v\$ '
7714 * PS2='> '
7715 * PS4='+ '
7716 */
7717
Denis Vlasenko38f63192007-01-22 09:03:07 +00007718#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007719 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007720# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7721 {
7722 const char *hp = get_local_var_value("HISTFILE");
7723 if (!hp) {
7724 hp = get_local_var_value("HOME");
7725 if (hp) {
7726 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7727 //set_local_var(xasprintf("HISTFILE=%s", ...));
7728 }
7729 }
Denys Vlasenko2c4de5b2011-03-31 13:16:52 +02007730# if ENABLE_FEATURE_SH_HISTFILESIZE
7731 hp = get_local_var_value("HISTFILESIZE");
7732 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
7733# endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007734 }
7735# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007736#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007737
Denis Vlasenko87a86552008-07-29 19:43:10 +00007738 G.global_argc = argc;
7739 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007740 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007741 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007742
Denis Vlasenkoed782372009-04-10 00:45:02 +00007743 if (setjmp(die_jmp)) {
7744 /* xfunc has failed! die die die */
7745 /* no EXIT traps, this is an escape hatch! */
7746 G.exiting = 1;
7747 hush_exit(xfunc_error_retval);
7748 }
7749
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007750 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007751 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007752 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007753 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007754 * in order to intercept (more) signals.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007755//FIXME: re-running is currently most likely broken, it's a no-op.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007756 */
7757
7758 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007759 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007760 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007761 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007762 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007763#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007764 "<:$:R:V:"
7765# if ENABLE_HUSH_FUNCTIONS
7766 "F:"
7767# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007768#endif
7769 );
7770 if (opt <= 0)
7771 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007772 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007773 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007774 /* Possibilities:
7775 * sh ... -c 'script'
7776 * sh ... -c 'script' ARG0 [ARG1...]
7777 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007778 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007779 * "" needs to be replaced with NULL
7780 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007781 * Note: the form without ARG0 never happens:
7782 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007783 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007784 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007785 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007786 G.root_ppid = getppid();
7787 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007788 G.global_argv = argv + optind;
7789 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007790 if (builtin_argc) {
7791 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7792 const struct built_in_command *x;
7793
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007794 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007795 x = find_builtin(optarg);
7796 if (x) { /* paranoia */
7797 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7798 G.global_argv += builtin_argc;
7799 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007800 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007801 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007802 }
7803 goto final_return;
7804 }
7805 if (!G.global_argv[0]) {
7806 /* -c 'script' (no params): prevent empty $0 */
7807 G.global_argv--; /* points to argv[i] of 'script' */
7808 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007809 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007810 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007811 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007812 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007813 goto final_return;
7814 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007815 /* Well, we cannot just declare interactiveness,
7816 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007817 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007818 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007819 case 's':
7820 /* "-s" means "read from stdin", but this is how we always
7821 * operate, so simply do nothing here. */
7822 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007823#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007824 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007825 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007826 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007827 case '$': {
7828 unsigned long long empty_trap_mask;
7829
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007830 G.root_pid = bb_strtou(optarg, &optarg, 16);
7831 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007832 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7833 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007834 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7835 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007836 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007837 optarg++;
7838 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007839 optarg++;
7840 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7841 if (empty_trap_mask != 0) {
7842 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007843 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007844 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7845 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007846///vda: fixme: more efficient code
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007847 if (empty_trap_mask & (1LL << sig)) {
7848 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007849 signal(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007850 }
7851 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007852 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007853# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007854 optarg++;
7855 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007856# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007857 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007858 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007859 case 'R':
7860 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007861 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007862 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007863# if ENABLE_HUSH_FUNCTIONS
7864 case 'F': {
7865 struct function *funcp = new_function(optarg);
7866 /* funcp->name is already set to optarg */
7867 /* funcp->body is set to NULL. It's a special case. */
7868 funcp->body_as_string = argv[optind];
7869 optind++;
7870 break;
7871 }
7872# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007873#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007874 case 'n':
7875 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007876 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007877 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007878 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007879#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007880 fprintf(stderr, "Usage: sh [FILE]...\n"
7881 " or: sh -c command [args]...\n\n");
7882 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007883#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007884 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007885#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007886 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007887 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007888
Denys Vlasenkodea47882009-10-09 15:40:49 +02007889 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007890 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007891 G.root_ppid = getppid();
7892 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007893
7894 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007895 if (argv[0] && argv[0][0] == '-') {
7896 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007897 debug_printf("sourcing /etc/profile\n");
7898 input = fopen_for_read("/etc/profile");
7899 if (input != NULL) {
7900 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007901 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007902 parse_and_run_file(input);
7903 fclose(input);
7904 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007905 /* bash: after sourcing /etc/profile,
7906 * tries to source (in the given order):
7907 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007908 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007909 * bash also sources ~/.bash_logout on exit.
7910 * If called as sh, skips .bash_XXX files.
7911 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007912 }
7913
Denis Vlasenkof9375282009-04-05 19:13:39 +00007914 if (argv[optind]) {
7915 FILE *input;
7916 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007917 * "bash <script>" (which is never interactive (unless -i?))
7918 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007919 * If called as sh, does the same but with $ENV.
7920 */
7921 debug_printf("running script '%s'\n", argv[optind]);
7922 G.global_argv = argv + optind;
7923 G.global_argc = argc - optind;
7924 input = xfopen_for_read(argv[optind]);
7925 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007926 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007927 parse_and_run_file(input);
7928#if ENABLE_FEATURE_CLEAN_UP
7929 fclose(input);
7930#endif
7931 goto final_return;
7932 }
7933
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007934 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007935 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007936 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007937
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007938 /* A shell is interactive if the '-i' flag was given,
7939 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007940 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007941 * no arguments remaining or the -s flag given
7942 * standard input is a terminal
7943 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007944 * Refer to Posix.2, the description of the 'sh' utility.
7945 */
7946#if ENABLE_HUSH_JOB
7947 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007948 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7949 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7950 if (G_saved_tty_pgrp < 0)
7951 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007952
7953 /* try to dup stdin to high fd#, >= 255 */
7954 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7955 if (G_interactive_fd < 0) {
7956 /* try to dup to any fd */
7957 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007958 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007959 /* give up */
7960 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007961 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007962 }
7963 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007964// TODO: track & disallow any attempts of user
7965// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007966 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007967 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007968 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007969 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007970
Mike Frysinger38478a62009-05-20 04:48:06 -04007971 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007972 /* If we were run as 'hush &', sleep until we are
7973 * in the foreground (tty pgrp == our pgrp).
7974 * If we get started under a job aware app (like bash),
7975 * make sure we are now in charge so we don't fight over
7976 * who gets the foreground */
7977 while (1) {
7978 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007979 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7980 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007981 break;
7982 /* send TTIN to ourself (should stop us) */
7983 kill(- shell_pgrp, SIGTTIN);
7984 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007985 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007986
Denis Vlasenkof9375282009-04-05 19:13:39 +00007987 /* Block some signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007988 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007989
Mike Frysinger38478a62009-05-20 04:48:06 -04007990 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007991 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007992 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007993 /* Put ourselves in our own process group
7994 * (bash, too, does this only if ctty is available) */
7995 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7996 /* Grab control of the terminal */
7997 tcsetpgrp(G_interactive_fd, getpid());
7998 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007999 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00008000 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00008001 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008002 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008003 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008004 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008005#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008006 /* No job control compiled in, only prompt/line editing */
8007 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008008 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8009 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008010 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008011 G_interactive_fd = dup(STDIN_FILENO);
8012 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008013 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008014 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008015 }
8016 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008017 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008018 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008019 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008020 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008021#else
8022 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008023 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008024#endif
8025 /* bash:
8026 * if interactive but not a login shell, sources ~/.bashrc
8027 * (--norc turns this off, --rcfile <file> overrides)
8028 */
8029
8030 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008031 /* note: ash and hush share this string */
8032 printf("\n\n%s %s\n"
8033 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8034 "\n",
8035 bb_banner,
8036 "hush - the humble shell"
8037 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008038 }
8039
Denis Vlasenkof9375282009-04-05 19:13:39 +00008040 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008041
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008042 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008043 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008044}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008045
8046
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008047#if ENABLE_MSH
8048int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8049int msh_main(int argc, char **argv)
8050{
8051 //bb_error_msg("msh is deprecated, please use hush instead");
8052 return hush_main(argc, argv);
8053}
8054#endif
8055
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008056
8057/*
8058 * Built-ins
8059 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008060static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008061{
8062 return 0;
8063}
8064
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008065static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008066{
8067 int argc = 0;
8068 while (*argv) {
8069 argc++;
8070 argv++;
8071 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008072 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008073}
8074
8075static int FAST_FUNC builtin_test(char **argv)
8076{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008077 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008078}
8079
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008080static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008081{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008082 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008083}
8084
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008085#if ENABLE_PRINTF
8086static int FAST_FUNC builtin_printf(char **argv)
8087{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008088 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008089}
8090#endif
8091
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008092static char **skip_dash_dash(char **argv)
8093{
8094 argv++;
8095 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8096 argv++;
8097 return argv;
8098}
8099
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008100static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008101{
8102 int rcode = EXIT_SUCCESS;
8103
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008104 argv = skip_dash_dash(argv);
8105 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008106 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008107 /* bash:
8108 * eval "echo Hi; done" ("done" is syntax error):
8109 * "echo Hi" will not execute too.
8110 */
8111 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008112 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008113 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008114 }
8115 return rcode;
8116}
8117
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008118static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008119{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008120 const char *newdir;
8121
8122 argv = skip_dash_dash(argv);
8123 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008124 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008125 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008126 * bash says "bash: cd: HOME not set" and does nothing
8127 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008128 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008129 const char *home = get_local_var_value("HOME");
8130 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008131 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008132 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008133 /* Mimic bash message exactly */
8134 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008135 return EXIT_FAILURE;
8136 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008137 /* Read current dir (get_cwd(1) is inside) and set PWD.
8138 * Note: do not enforce exporting. If PWD was unset or unexported,
8139 * set it again, but do not export. bash does the same.
8140 */
8141 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008142 return EXIT_SUCCESS;
8143}
8144
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008145static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008146{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008147 argv = skip_dash_dash(argv);
8148 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008149 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008150
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008151 /* Careful: we can end up here after [v]fork. Do not restore
8152 * tty pgrp then, only top-level shell process does that */
8153 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8154 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8155
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008156 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008157 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008158 * and tcsetpgrp, and this is inherently racy.
8159 */
8160 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008161}
8162
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008163static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008164{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008165 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008166
8167 /* interactive bash:
8168 * # trap "echo EEE" EXIT
8169 * # exit
8170 * exit
8171 * There are stopped jobs.
8172 * (if there are _stopped_ jobs, running ones don't count)
8173 * # exit
8174 * exit
8175 # EEE (then bash exits)
8176 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008177 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008178 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008179
8180 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008181 argv = skip_dash_dash(argv);
8182 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008183 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008184 /* mimic bash: exit 123abc == exit 255 + error msg */
8185 xfunc_error_retval = 255;
8186 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008187 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008188}
8189
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008190static void print_escaped(const char *s)
8191{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008192 if (*s == '\'')
8193 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008194 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008195 const char *p = strchrnul(s, '\'');
8196 /* print 'xxxx', possibly just '' */
8197 printf("'%.*s'", (int)(p - s), s);
8198 if (*p == '\0')
8199 break;
8200 s = p;
8201 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008202 /* s points to '; print "'''...'''" */
8203 putchar('"');
8204 do putchar('\''); while (*++s == '\'');
8205 putchar('"');
8206 } while (*s);
8207}
8208
Denys Vlasenko295fef82009-06-03 12:47:26 +02008209#if !ENABLE_HUSH_LOCAL
8210#define helper_export_local(argv, exp, lvl) \
8211 helper_export_local(argv, exp)
8212#endif
8213static void helper_export_local(char **argv, int exp, int lvl)
8214{
8215 do {
8216 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008217 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008218
8219 /* So far we do not check that name is valid (TODO?) */
8220
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008221 if (*name_end == '\0') {
8222 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008223
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008224 vpp = get_ptr_to_local_var(name, name_end - name);
8225 var = vpp ? *vpp : NULL;
8226
Denys Vlasenko295fef82009-06-03 12:47:26 +02008227 if (exp == -1) { /* unexporting? */
8228 /* export -n NAME (without =VALUE) */
8229 if (var) {
8230 var->flg_export = 0;
8231 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8232 unsetenv(name);
8233 } /* else: export -n NOT_EXISTING_VAR: no-op */
8234 continue;
8235 }
8236 if (exp == 1) { /* exporting? */
8237 /* export NAME (without =VALUE) */
8238 if (var) {
8239 var->flg_export = 1;
8240 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8241 putenv(var->varstr);
8242 continue;
8243 }
8244 }
8245 /* Exporting non-existing variable.
8246 * bash does not put it in environment,
8247 * but remembers that it is exported,
8248 * and does put it in env when it is set later.
8249 * We just set it to "" and export. */
8250 /* Or, it's "local NAME" (without =VALUE).
8251 * bash sets the value to "". */
8252 name = xasprintf("%s=", name);
8253 } else {
8254 /* (Un)exporting/making local NAME=VALUE */
8255 name = xstrdup(name);
8256 }
8257 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8258 } while (*++argv);
8259}
8260
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008261static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008262{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008263 unsigned opt_unexport;
8264
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008265#if ENABLE_HUSH_EXPORT_N
8266 /* "!": do not abort on errors */
8267 opt_unexport = getopt32(argv, "!n");
8268 if (opt_unexport == (uint32_t)-1)
8269 return EXIT_FAILURE;
8270 argv += optind;
8271#else
8272 opt_unexport = 0;
8273 argv++;
8274#endif
8275
8276 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008277 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008278 if (e) {
8279 while (*e) {
8280#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008281 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008282#else
8283 /* ash emits: export VAR='VAL'
8284 * bash: declare -x VAR="VAL"
8285 * we follow ash example */
8286 const char *s = *e++;
8287 const char *p = strchr(s, '=');
8288
8289 if (!p) /* wtf? take next variable */
8290 continue;
8291 /* export var= */
8292 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008293 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008294 putchar('\n');
8295#endif
8296 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008297 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008298 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008299 return EXIT_SUCCESS;
8300 }
8301
Denys Vlasenko295fef82009-06-03 12:47:26 +02008302 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008303
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008304 return EXIT_SUCCESS;
8305}
8306
Denys Vlasenko295fef82009-06-03 12:47:26 +02008307#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008308static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008309{
8310 if (G.func_nest_level == 0) {
8311 bb_error_msg("%s: not in a function", argv[0]);
8312 return EXIT_FAILURE; /* bash compat */
8313 }
8314 helper_export_local(argv, 0, G.func_nest_level);
8315 return EXIT_SUCCESS;
8316}
8317#endif
8318
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008319static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008320{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008321 int sig;
8322 char *new_cmd;
8323
8324 if (!G.traps)
8325 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8326
8327 argv++;
8328 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008329 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008330 /* No args: print all trapped */
8331 for (i = 0; i < NSIG; ++i) {
8332 if (G.traps[i]) {
8333 printf("trap -- ");
8334 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008335 /* note: bash adds "SIG", but only if invoked
8336 * as "bash". If called as "sh", or if set -o posix,
8337 * then it prints short signal names.
8338 * We are printing short names: */
8339 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008340 }
8341 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008342 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008343 return EXIT_SUCCESS;
8344 }
8345
8346 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008347 /* If first arg is a number: reset all specified signals */
8348 sig = bb_strtou(*argv, NULL, 10);
8349 if (errno == 0) {
8350 int ret;
8351 process_sig_list:
8352 ret = EXIT_SUCCESS;
8353 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008354 sighandler_t handler;
8355
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008356 sig = get_signum(*argv++);
8357 if (sig < 0 || sig >= NSIG) {
8358 ret = EXIT_FAILURE;
8359 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008360 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008361 continue;
8362 }
8363
8364 free(G.traps[sig]);
8365 G.traps[sig] = xstrdup(new_cmd);
8366
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008367 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008368 get_signame(sig), sig, G.traps[sig]);
8369
8370 /* There is no signal for 0 (EXIT) */
8371 if (sig == 0)
8372 continue;
8373
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008374 if (new_cmd)
8375 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8376 else
8377 /* We are removing trap handler */
8378 handler = pick_sighandler(sig);
8379 signal(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008380 }
8381 return ret;
8382 }
8383
8384 if (!argv[1]) { /* no second arg */
8385 bb_error_msg("trap: invalid arguments");
8386 return EXIT_FAILURE;
8387 }
8388
8389 /* First arg is "-": reset all specified to default */
8390 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8391 /* Everything else: set arg as signal handler
8392 * (includes "" case, which ignores signal) */
8393 if (argv[0][0] == '-') {
8394 if (argv[0][1] == '\0') { /* "-" */
8395 /* new_cmd remains NULL: "reset these sigs" */
8396 goto reset_traps;
8397 }
8398 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8399 argv++;
8400 }
8401 /* else: "-something", no special meaning */
8402 }
8403 new_cmd = *argv;
8404 reset_traps:
8405 argv++;
8406 goto process_sig_list;
8407}
8408
Mike Frysinger93cadc22009-05-27 17:06:25 -04008409/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008410static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008411{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008412 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008413
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008414 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008415 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008416 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008417
8418 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008419 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008420 type = "an alias";*/
8421#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008422 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008423 type = "a function";
8424#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008425 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008426 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008427 else if ((path = find_in_path(*argv)) != NULL)
8428 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008429 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008430 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008431 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008432 continue;
8433 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008434
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008435 printf("%s is %s\n", *argv, type);
8436 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008437 }
8438
8439 return ret;
8440}
8441
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008442#if ENABLE_HUSH_JOB
8443/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008444static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008445{
8446 int i, jobnum;
8447 struct pipe *pi;
8448
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008449 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008450 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008451
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008452 /* If they gave us no args, assume they want the last backgrounded task */
8453 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008454 for (pi = G.job_list; pi; pi = pi->next) {
8455 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008456 goto found;
8457 }
8458 }
8459 bb_error_msg("%s: no current job", argv[0]);
8460 return EXIT_FAILURE;
8461 }
8462 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8463 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8464 return EXIT_FAILURE;
8465 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008466 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008467 if (pi->jobid == jobnum) {
8468 goto found;
8469 }
8470 }
8471 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8472 return EXIT_FAILURE;
8473 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008474 /* TODO: bash prints a string representation
8475 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008476 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008477 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008478 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008479 }
8480
8481 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008482 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8483 for (i = 0; i < pi->num_cmds; i++) {
8484 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8485 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008486 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008487 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008488
8489 i = kill(- pi->pgrp, SIGCONT);
8490 if (i < 0) {
8491 if (errno == ESRCH) {
8492 delete_finished_bg_job(pi);
8493 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008494 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008495 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008496 }
8497
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008498 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008499 remove_bg_job(pi);
8500 return checkjobs_and_fg_shell(pi);
8501 }
8502 return EXIT_SUCCESS;
8503}
8504#endif
8505
8506#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008507static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008508{
8509 const struct built_in_command *x;
8510
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008511 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008512 "Built-in commands:\n"
8513 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008514 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008515 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008516 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008517 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008518 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008519 return EXIT_SUCCESS;
8520}
8521#endif
8522
8523#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008524static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008525{
8526 struct pipe *job;
8527 const char *status_string;
8528
Denis Vlasenko87a86552008-07-29 19:43:10 +00008529 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008530 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008531 status_string = "Stopped";
8532 else
8533 status_string = "Running";
8534
8535 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8536 }
8537 return EXIT_SUCCESS;
8538}
8539#endif
8540
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008541#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008542static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008543{
8544 void *p;
8545 unsigned long l;
8546
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008547# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008548 /* Optional. Reduces probability of false positives */
8549 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008550# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008551 /* Crude attempt to find where "free memory" starts,
8552 * sans fragmentation. */
8553 p = malloc(240);
8554 l = (unsigned long)p;
8555 free(p);
8556 p = malloc(3400);
8557 if (l < (unsigned long)p) l = (unsigned long)p;
8558 free(p);
8559
8560 if (!G.memleak_value)
8561 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008562
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008563 l -= G.memleak_value;
8564 if ((long)l < 0)
8565 l = 0;
8566 l /= 1024;
8567 if (l > 127)
8568 l = 127;
8569
8570 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8571 return l;
8572}
8573#endif
8574
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008575static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008576{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008577 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008578 return EXIT_SUCCESS;
8579}
8580
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008581/* Interruptibility of read builtin in bash
8582 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8583 *
8584 * Empty trap makes read ignore corresponding signal, for any signal.
8585 *
8586 * SIGINT:
8587 * - terminates non-interactive shell;
8588 * - interrupts read in interactive shell;
8589 * if it has non-empty trap:
8590 * - executes trap and returns to command prompt in interactive shell;
8591 * - executes trap and returns to read in non-interactive shell;
8592 * SIGTERM:
8593 * - is ignored (does not interrupt) read in interactive shell;
8594 * - terminates non-interactive shell;
8595 * if it has non-empty trap:
8596 * - executes trap and returns to read;
8597 * SIGHUP:
8598 * - terminates shell (regardless of interactivity);
8599 * if it has non-empty trap:
8600 * - executes trap and returns to read;
8601 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008602static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008603{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008604 const char *r;
8605 char *opt_n = NULL;
8606 char *opt_p = NULL;
8607 char *opt_t = NULL;
8608 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008609 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01008610 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008611
Denys Vlasenko03dad222010-01-12 23:29:57 +01008612 /* "!": do not abort on errors.
8613 * Option string must start with "sr" to match BUILTIN_READ_xxx
8614 */
8615 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8616 if (read_flags == (uint32_t)-1)
8617 return EXIT_FAILURE;
8618 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008619 ifs = get_local_var_value("IFS"); /* can be NULL */
8620
8621 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01008622 r = shell_builtin_read(set_local_var_from_halves,
8623 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008624 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01008625 read_flags,
8626 opt_n,
8627 opt_p,
8628 opt_t,
8629 opt_u
8630 );
8631
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008632 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008633 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008634 if (sig && sig != SIGINT)
8635 goto again;
8636 }
8637
Denys Vlasenko03dad222010-01-12 23:29:57 +01008638 if ((uintptr_t)r > 1) {
8639 bb_error_msg("%s", r);
8640 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008641 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008642
Denys Vlasenko03dad222010-01-12 23:29:57 +01008643 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008644}
8645
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008646/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8647 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008648 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008649 * set [-abCefhmnuvx] [-o option] [argument...]
8650 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008651 * set -- [argument...]
8652 * set -o
8653 * set +o
8654 * Implementations shall support the options in both their hyphen and
8655 * plus-sign forms. These options can also be specified as options to sh.
8656 * Examples:
8657 * Write out all variables and their values: set
8658 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8659 * Turn on the -x and -v options: set -xv
8660 * Unset all positional parameters: set --
8661 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8662 * Set the positional parameters to the expansion of x, even if x expands
8663 * with a leading '-' or '+': set -- $x
8664 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008665 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008666 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008667static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008668{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008669 int n;
8670 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008671 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008672
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008673 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008674 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008675 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008676 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008677 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008678 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008679
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008680 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008681 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008682 ++argv;
8683 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008684 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008685 if (arg[0] != '+' && arg[0] != '-')
8686 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008687 for (n = 1; arg[n]; ++n) {
8688 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008689 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008690 if (arg[n] == 'o' && argv[1])
8691 argv++;
8692 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008693 } while ((arg = *++argv) != NULL);
8694 /* Now argv[0] is 1st argument */
8695
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008696 if (arg == NULL)
8697 return EXIT_SUCCESS;
8698 set_argv:
8699
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008700 /* NB: G.global_argv[0] ($0) is never freed/changed */
8701 g_argv = G.global_argv;
8702 if (G.global_args_malloced) {
8703 pp = g_argv;
8704 while (*++pp)
8705 free(*pp);
8706 g_argv[1] = NULL;
8707 } else {
8708 G.global_args_malloced = 1;
8709 pp = xzalloc(sizeof(pp[0]) * 2);
8710 pp[0] = g_argv[0]; /* retain $0 */
8711 g_argv = pp;
8712 }
8713 /* This realloc's G.global_argv */
8714 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8715
8716 n = 1;
8717 while (*++pp)
8718 n++;
8719 G.global_argc = n;
8720
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008721 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008722
8723 /* Nothing known, so abort */
8724 error:
8725 bb_error_msg("set: %s: invalid option", arg);
8726 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008727}
8728
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008729static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008730{
8731 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008732 argv = skip_dash_dash(argv);
8733 if (argv[0]) {
8734 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008735 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008736 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008737 if (G.global_args_malloced) {
8738 int m = 1;
8739 while (m <= n)
8740 free(G.global_argv[m++]);
8741 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008742 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008743 memmove(&G.global_argv[1], &G.global_argv[n+1],
8744 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008745 return EXIT_SUCCESS;
8746 }
8747 return EXIT_FAILURE;
8748}
8749
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008750static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008751{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008752 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008753 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008754 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008755#if ENABLE_HUSH_FUNCTIONS
8756 smallint sv_flg;
8757#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008758
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008759 argv = skip_dash_dash(argv);
8760 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008761 if (!filename) {
8762 /* bash says: "bash: .: filename argument required" */
8763 return 2; /* bash compat */
8764 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008765 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008766 if (!strchr(filename, '/')) {
8767 arg_path = find_in_path(filename);
8768 if (arg_path)
8769 filename = arg_path;
8770 }
8771 input = fopen_or_warn(filename, "r");
8772 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008773 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008774 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008775 return EXIT_FAILURE;
8776 }
8777 close_on_exec_on(fileno(input));
8778
Mike Frysinger885b6f22009-04-18 21:04:25 +00008779#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008780 sv_flg = G.flag_return_in_progress;
8781 /* "we are inside sourced file, ok to use return" */
8782 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008783#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008784 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008785
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008786 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008787 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008788
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008789 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008790#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008791 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008792#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008793
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008794 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008795}
8796
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008797static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008798{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008799 int rc;
8800 mode_t mask;
8801
8802 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008803 argv = skip_dash_dash(argv);
8804 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008805 mode_t old_mask = mask;
8806
8807 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008808 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008809 mask ^= 0777;
8810 if (rc == 0) {
8811 mask = old_mask;
8812 /* bash messages:
8813 * bash: umask: 'q': invalid symbolic mode operator
8814 * bash: umask: 999: octal number out of range
8815 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008816 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008817 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008818 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008819 rc = 1;
8820 /* Mimic bash */
8821 printf("%04o\n", (unsigned) mask);
8822 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008823 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008824 umask(mask);
8825
8826 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008827}
8828
Mike Frysingerd690f682009-03-30 06:50:54 +00008829/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008830static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008831{
Mike Frysingerd690f682009-03-30 06:50:54 +00008832 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008833 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008834
Denis Vlasenko28e67962009-04-26 23:22:40 +00008835 /* "!": do not abort on errors */
8836 /* "+": stop at 1st non-option */
8837 opts = getopt32(argv, "!+vf");
8838 if (opts == (unsigned)-1)
8839 return EXIT_FAILURE;
8840 if (opts == 3) {
8841 bb_error_msg("unset: -v and -f are exclusive");
8842 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008843 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008844 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008845
8846 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008847 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008848 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008849 if (unset_local_var(*argv)) {
8850 /* unset <nonexistent_var> doesn't fail.
8851 * Error is when one tries to unset RO var.
8852 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008853 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008854 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008855 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008856#if ENABLE_HUSH_FUNCTIONS
8857 else {
8858 unset_func(*argv);
8859 }
8860#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008861 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008862 }
8863 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008864}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008865
Mike Frysinger56bdea12009-03-28 20:01:58 +00008866/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008867static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008868{
8869 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008870 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008871
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008872 argv = skip_dash_dash(argv);
8873 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008874 /* Don't care about wait results */
8875 /* Note 1: must wait until there are no more children */
8876 /* Note 2: must be interruptible */
8877 /* Examples:
8878 * $ sleep 3 & sleep 6 & wait
8879 * [1] 30934 sleep 3
8880 * [2] 30935 sleep 6
8881 * [1] Done sleep 3
8882 * [2] Done sleep 6
8883 * $ sleep 3 & sleep 6 & wait
8884 * [1] 30936 sleep 3
8885 * [2] 30937 sleep 6
8886 * [1] Done sleep 3
8887 * ^C <-- after ~4 sec from keyboard
8888 * $
8889 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008890 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008891 int sig;
8892 sigset_t oldset, allsigs;
8893
8894 /* waitpid is not interruptible by SA_RESTARTed
8895 * signals which we use. Thus, this ugly dance:
8896 */
8897
8898 /* Make sure possible SIGCHLD is stored in kernel's
8899 * pending signal mask before we call waitpid.
8900 * Or else we may race with SIGCHLD, lose it,
8901 * and get stuck in sigwaitinfo...
8902 */
8903 sigfillset(&allsigs);
8904 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
8905
8906 if (!sigisemptyset(&G.pending_set)) {
8907 /* Crap! we raced with some signal! */
8908 // sig = 0;
8909 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008910 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008911
8912 checkjobs(NULL); /* waitpid(WNOHANG) inside */
8913 if (errno == ECHILD) {
8914 sigprocmask(SIG_SETMASK, &oldset, NULL);
8915 break;
8916 }
8917
8918 /* Wait for SIGCHLD or any other signal */
8919 //sig = sigwaitinfo(&allsigs, NULL);
8920 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
8921 /* Note: sigsuspend invokes signal handler */
8922 sigsuspend(&oldset);
8923 restore:
8924 sigprocmask(SIG_SETMASK, &oldset, NULL);
8925
8926 /* So, did we get a signal? */
8927 //if (sig > 0)
8928 // raise(sig); /* run handler */
8929 sig = check_and_run_traps();
8930 if (sig /*&& sig != SIGCHLD - always true */) {
8931 /* see note 2 */
8932 ret = 128 + sig;
8933 break;
8934 }
8935 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008936 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008937 return ret;
8938 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008939
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008940 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008941 while (*argv) {
8942 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008943 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008944 /* mimic bash message */
8945 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008946 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008947 }
8948 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008949 if (WIFSIGNALED(status))
8950 ret = 128 + WTERMSIG(status);
8951 else if (WIFEXITED(status))
8952 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008953 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008954 ret = EXIT_FAILURE;
8955 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008956 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008957 ret = 127;
8958 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008959 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008960 }
8961
8962 return ret;
8963}
8964
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008965#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8966static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8967{
8968 if (argv[1]) {
8969 def = bb_strtou(argv[1], NULL, 10);
8970 if (errno || def < def_min || argv[2]) {
8971 bb_error_msg("%s: bad arguments", argv[0]);
8972 def = UINT_MAX;
8973 }
8974 }
8975 return def;
8976}
8977#endif
8978
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008979#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008980static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008981{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008982 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008983 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008984 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008985 return EXIT_SUCCESS; /* bash compat */
8986 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008987 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008988
8989 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8990 if (depth == UINT_MAX)
8991 G.flag_break_continue = BC_BREAK;
8992 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008993 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008994
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008995 return EXIT_SUCCESS;
8996}
8997
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008998static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008999{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009000 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9001 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009002}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009003#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009004
9005#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009006static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009007{
9008 int rc;
9009
9010 if (G.flag_return_in_progress != -1) {
9011 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9012 return EXIT_FAILURE; /* bash compat */
9013 }
9014
9015 G.flag_return_in_progress = 1;
9016
9017 /* bash:
9018 * out of range: wraps around at 256, does not error out
9019 * non-numeric param:
9020 * f() { false; return qwe; }; f; echo $?
9021 * bash: return: qwe: numeric argument required <== we do this
9022 * 255 <== we also do this
9023 */
9024 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9025 return rc;
9026}
9027#endif