blob: 9cc86fa9a1b6d3d5942715d5bd85976fb303ac98 [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 Vlasenkof58f7052011-05-12 02:10:33 +0200263//usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100264//usage:#define hush_full_usage "\n\n"
265//usage: "Unix shell interpreter"
266
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100267//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100268//usage:#define msh_full_usage hush_full_usage
269
270//usage:#if ENABLE_FEATURE_SH_IS_HUSH
271//usage:# define sh_trivial_usage hush_trivial_usage
272//usage:# define sh_full_usage hush_full_usage
273//usage:#endif
274//usage:#if ENABLE_FEATURE_BASH_IS_HUSH
275//usage:# define bash_trivial_usage hush_trivial_usage
276//usage:# define bash_full_usage hush_full_usage
277//usage:#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200278
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000279
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200280/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000281#define LEAK_HUNTING 0
282#define BUILD_AS_NOMMU 0
283/* Enable/disable sanity checks. Ok to enable in production,
284 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
285 * Keeping 1 for now even in released versions.
286 */
287#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200288/* Slightly bigger (+200 bytes), but faster hush.
289 * So far it only enables a trick with counting SIGCHLDs and forks,
290 * which allows us to do fewer waitpid's.
291 * (we can detect a case where neither forks were done nor SIGCHLDs happened
292 * and therefore waitpid will return the same result as last time)
293 */
294#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200295/* TODO: implement simplified code for users which do not need ${var%...} ops
296 * So far ${var%...} ops are always enabled:
297 */
298#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000299
300
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000301#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000302# undef BB_MMU
303# undef USE_FOR_NOMMU
304# undef USE_FOR_MMU
305# define BB_MMU 0
306# define USE_FOR_NOMMU(...) __VA_ARGS__
307# define USE_FOR_MMU(...)
308#endif
309
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200310#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100311#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000312/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000313# undef CONFIG_FEATURE_SH_STANDALONE
314# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000315# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100316# undef IF_NOT_FEATURE_SH_STANDALONE
317# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000318# define IF_FEATURE_SH_STANDALONE(...)
319# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000320#endif
321
Denis Vlasenko05743d72008-02-10 12:10:08 +0000322#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000323# undef ENABLE_FEATURE_EDITING
324# define ENABLE_FEATURE_EDITING 0
325# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
326# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
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;
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200808# define G_fatal_sig_mask G.fatal_sig_mask
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200809#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200810# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200811#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 Vlasenko0806e402011-05-12 23:06:20 +0200818 struct sigaction sa;
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200819 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000820};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000821#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000822/* Not #defining name to G.name - this quickly gets unwieldy
823 * (too many defines). Also, I actually prefer to see when a variable
824 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000825#define INIT_G() do { \
826 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200827 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
828 sigfillset(&G.sa.sa_mask); \
829 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000830} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000831
832
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000833/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200834static int builtin_cd(char **argv) FAST_FUNC;
835static int builtin_echo(char **argv) FAST_FUNC;
836static int builtin_eval(char **argv) FAST_FUNC;
837static int builtin_exec(char **argv) FAST_FUNC;
838static int builtin_exit(char **argv) FAST_FUNC;
839static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000840#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200841static int builtin_fg_bg(char **argv) FAST_FUNC;
842static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000843#endif
844#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200845static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000846#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200847#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200848static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200849#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000850#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200851static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000852#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400853#if ENABLE_PRINTF
854static int builtin_printf(char **argv) FAST_FUNC;
855#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200856static int builtin_pwd(char **argv) FAST_FUNC;
857static int builtin_read(char **argv) FAST_FUNC;
858static int builtin_set(char **argv) FAST_FUNC;
859static int builtin_shift(char **argv) FAST_FUNC;
860static int builtin_source(char **argv) FAST_FUNC;
861static int builtin_test(char **argv) FAST_FUNC;
862static int builtin_trap(char **argv) FAST_FUNC;
863static int builtin_type(char **argv) FAST_FUNC;
864static int builtin_true(char **argv) FAST_FUNC;
865static int builtin_umask(char **argv) FAST_FUNC;
866static int builtin_unset(char **argv) FAST_FUNC;
867static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000868#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200869static int builtin_break(char **argv) FAST_FUNC;
870static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000871#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000872#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200873static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000874#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000875
876/* Table of built-in functions. They can be forked or not, depending on
877 * context: within pipes, they fork. As simple commands, they do not.
878 * When used in non-forking context, they can change global variables
879 * in the parent shell process. If forked, of course they cannot.
880 * For example, 'unset foo | whatever' will parse and run, but foo will
881 * still be set at the end. */
882struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100883 const char *b_cmd;
884 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000885#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100886 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200887# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000888#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200889# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000890#endif
891};
892
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200893static const struct built_in_command bltins1[] = {
894 BLTIN("." , builtin_source , "Run commands in a file"),
895 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000896#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200897 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000898#endif
899#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200900 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000901#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200902 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000903#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200904 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000905#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200906 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
907 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
908 BLTIN("exit" , builtin_exit , "Exit"),
909 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000910#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200911 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000912#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000913#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200914 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000915#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000916#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200917 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000918#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200919#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200920 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200921#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000922#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200923 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000924#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200925 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000926#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200927 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000928#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200929 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
930 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200931#if ENABLE_HUSH_BASH_COMPAT
932 BLTIN("source" , builtin_source , "Run commands in a file"),
933#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200934 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100935 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100936 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200937 BLTIN("umask" , builtin_umask , "Set file creation mask"),
938 BLTIN("unset" , builtin_unset , "Unset variables"),
939 BLTIN("wait" , builtin_wait , "Wait for process"),
940};
941/* For now, echo and test are unconditionally enabled.
942 * Maybe make it configurable? */
943static const struct built_in_command bltins2[] = {
944 BLTIN("[" , builtin_test , NULL),
945 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400946#if ENABLE_PRINTF
947 BLTIN("printf" , builtin_printf , NULL),
948#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200949 BLTIN("pwd" , builtin_pwd , NULL),
950 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000951};
952
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000953
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000954/* Debug printouts.
955 */
956#if HUSH_DEBUG
957/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100958# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000959# define debug_enter() (G.debug_indent++)
960# define debug_leave() (G.debug_indent--)
961#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200962# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000963# define debug_enter() ((void)0)
964# define debug_leave() ((void)0)
965#endif
966
967#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100968# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000969#endif
970
971#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100972# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000973#endif
974
975#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100976#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000977#endif
978
979#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100980# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000981#endif
982
983#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100984# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000985# define DEBUG_JOBS 1
986#else
987# define DEBUG_JOBS 0
988#endif
989
990#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100991# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000992# define DEBUG_EXPAND 1
993#else
994# define DEBUG_EXPAND 0
995#endif
996
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200997#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100998# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200999#endif
1000
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001001#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001002# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001003# define DEBUG_GLOB 1
1004#else
1005# define DEBUG_GLOB 0
1006#endif
1007
1008#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001009# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001010#endif
1011
1012#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001013# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001014#endif
1015
1016#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001017# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001018# define DEBUG_CLEAN 1
1019#else
1020# define DEBUG_CLEAN 0
1021#endif
1022
1023#if DEBUG_EXPAND
1024static void debug_print_strings(const char *prefix, char **vv)
1025{
1026 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001027 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001028 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001029 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001030}
1031#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001032# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001033#endif
1034
1035
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001036/* Leak hunting. Use hush_leaktool.sh for post-processing.
1037 */
1038#if LEAK_HUNTING
1039static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001040{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001041 void *ptr = xmalloc((size + 0xff) & ~0xff);
1042 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1043 return ptr;
1044}
1045static void *xxrealloc(int lineno, void *ptr, size_t size)
1046{
1047 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1048 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1049 return ptr;
1050}
1051static char *xxstrdup(int lineno, const char *str)
1052{
1053 char *ptr = xstrdup(str);
1054 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1055 return ptr;
1056}
1057static void xxfree(void *ptr)
1058{
1059 fdprintf(2, "free %p\n", ptr);
1060 free(ptr);
1061}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001062# define xmalloc(s) xxmalloc(__LINE__, s)
1063# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1064# define xstrdup(s) xxstrdup(__LINE__, s)
1065# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001066#endif
1067
1068
1069/* Syntax and runtime errors. They always abort scripts.
1070 * In interactive use they usually discard unparsed and/or unexecuted commands
1071 * and return to the prompt.
1072 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1073 */
1074#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001075# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001076# define syntax_error(lineno, msg) syntax_error(msg)
1077# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1078# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1079# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1080# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001081#endif
1082
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001083static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001084{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001085 va_list p;
1086
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001087#if HUSH_DEBUG >= 2
1088 bb_error_msg("hush.c:%u", lineno);
1089#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001090 va_start(p, fmt);
1091 bb_verror_msg(fmt, p, NULL);
1092 va_end(p);
1093 if (!G_interactive_fd)
1094 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001095}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001096
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001097static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001098{
1099 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001100 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001101 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001102 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001103}
1104
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001105static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001106{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001107 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001108}
1109
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001110static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001111{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001112 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001113}
1114
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001115static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001116{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001117 char msg[2] = { ch, '\0' };
1118 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001119}
1120
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001121static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001122{
1123 char msg[2];
1124 msg[0] = ch;
1125 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001126 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001127}
1128
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001129#if HUSH_DEBUG < 2
1130# undef die_if_script
1131# undef syntax_error
1132# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001133# undef syntax_error_unterm_ch
1134# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001135# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001136#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001137# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001138# define syntax_error(msg) syntax_error(__LINE__, msg)
1139# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1140# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1141# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1142# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001143#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001144
Denis Vlasenko552433b2009-04-04 19:29:21 +00001145
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001146#if ENABLE_HUSH_INTERACTIVE
1147static void cmdedit_update_prompt(void);
1148#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001149# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001150#endif
1151
1152
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001153/* Utility functions
1154 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001155/* Replace each \x with x in place, return ptr past NUL. */
1156static char *unbackslash(char *src)
1157{
Denys Vlasenko71885402009-09-24 01:44:13 +02001158 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001159 while (1) {
1160 if (*src == '\\')
1161 src++;
1162 if ((*dst++ = *src++) == '\0')
1163 break;
1164 }
1165 return dst;
1166}
1167
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001168static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001169{
1170 int i;
1171 unsigned count1;
1172 unsigned count2;
1173 char **v;
1174
1175 v = strings;
1176 count1 = 0;
1177 if (v) {
1178 while (*v) {
1179 count1++;
1180 v++;
1181 }
1182 }
1183 count2 = 0;
1184 v = add;
1185 while (*v) {
1186 count2++;
1187 v++;
1188 }
1189 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1190 v[count1 + count2] = NULL;
1191 i = count2;
1192 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001193 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001194 return v;
1195}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001196#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001197static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1198{
1199 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1200 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1201 return ptr;
1202}
1203#define add_strings_to_strings(strings, add, need_to_dup) \
1204 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1205#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001206
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001207/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001208static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001209{
1210 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001211 v[0] = add;
1212 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001213 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001214}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001215#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001216static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1217{
1218 char **ptr = add_string_to_strings(strings, add);
1219 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1220 return ptr;
1221}
1222#define add_string_to_strings(strings, add) \
1223 xx_add_string_to_strings(__LINE__, strings, add)
1224#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001225
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001226static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001227{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001228 char **v;
1229
1230 if (!strings)
1231 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001232 v = strings;
1233 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001234 free(*v);
1235 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001236 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001237 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001238}
1239
Denis Vlasenko76d50412008-06-10 16:19:39 +00001240
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001241/* Helpers for setting new $n and restoring them back
1242 */
1243typedef struct save_arg_t {
1244 char *sv_argv0;
1245 char **sv_g_argv;
1246 int sv_g_argc;
1247 smallint sv_g_malloced;
1248} save_arg_t;
1249
1250static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1251{
1252 int n;
1253
1254 sv->sv_argv0 = argv[0];
1255 sv->sv_g_argv = G.global_argv;
1256 sv->sv_g_argc = G.global_argc;
1257 sv->sv_g_malloced = G.global_args_malloced;
1258
1259 argv[0] = G.global_argv[0]; /* retain $0 */
1260 G.global_argv = argv;
1261 G.global_args_malloced = 0;
1262
1263 n = 1;
1264 while (*++argv)
1265 n++;
1266 G.global_argc = n;
1267}
1268
1269static void restore_G_args(save_arg_t *sv, char **argv)
1270{
1271 char **pp;
1272
1273 if (G.global_args_malloced) {
1274 /* someone ran "set -- arg1 arg2 ...", undo */
1275 pp = G.global_argv;
1276 while (*++pp) /* note: does not free $0 */
1277 free(*pp);
1278 free(G.global_argv);
1279 }
1280 argv[0] = sv->sv_argv0;
1281 G.global_argv = sv->sv_g_argv;
1282 G.global_argc = sv->sv_g_argc;
1283 G.global_args_malloced = sv->sv_g_malloced;
1284}
1285
1286
Denis Vlasenkod5762932009-03-31 11:22:57 +00001287/* Basic theory of signal handling in shell
1288 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001289 * This does not describe what hush does, rather, it is current understanding
1290 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001291 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1292 *
1293 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1294 * is finished or backgrounded. It is the same in interactive and
1295 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001296 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001297 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001298 * backgrounds (i.e. stops) or kills all members of currently running
1299 * pipe.
1300 *
1301 * Wait builtin in interruptible by signals for which user trap is set
1302 * or by SIGINT in interactive shell.
1303 *
1304 * Trap handlers will execute even within trap handlers. (right?)
1305 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001306 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1307 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001308 *
1309 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001310 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001311 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001312 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001313 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001314 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001315 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001316 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001317 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001318 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001319 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001320 *
1321 * SIGQUIT: ignore
1322 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001323 * SIGHUP (interactive):
1324 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001325 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001326 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1327 * that all pipe members are stopped. Try this in bash:
1328 * while :; do :; done - ^Z does not background it
1329 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001330 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001331 * of the command line, show prompt. NB: ^C does not send SIGINT
1332 * to interactive shell while shell is waiting for a pipe,
1333 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001334 * Example 1: this waits 5 sec, but does not execute ls:
1335 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1336 * Example 2: this does not wait and does not execute ls:
1337 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1338 * Example 3: this does not wait 5 sec, but executes ls:
1339 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001340 * Example 4: this does not wait and does not execute ls:
1341 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001342 *
1343 * (What happens to signals which are IGN on shell start?)
1344 * (What happens with signal mask on shell start?)
1345 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001346 * Old implementation
1347 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001348 * We use in-kernel pending signal mask to determine which signals were sent.
1349 * We block all signals which we don't want to take action immediately,
1350 * i.e. we block all signals which need to have special handling as described
1351 * above, and all signals which have traps set.
1352 * After each pipe execution, we extract any pending signals via sigtimedwait()
1353 * and act on them.
1354 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001355 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001356 * sigset_t blocked_set: current blocked signal set
1357 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001358 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001359 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001360 * "trap 'cmd' SIGxxx":
1361 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001362 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001363 * unblock signals with special interactive handling
1364 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001365 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001366 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001367 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001368 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001369 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001370 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001371 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001372 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001373 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001374 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001375 * Standard says "When a subshell is entered, traps that are not being ignored
1376 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001377 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001378 *
1379 * Problem: the above approach makes it unwieldy to catch signals while
1380 * we are in read builtin, of while we read commands from stdin:
1381 * masked signals are not visible!
1382 *
1383 * New implementation
1384 * ==================
1385 * We record each signal we are interested in by installing signal handler
1386 * for them - a bit like emulating kernel pending signal mask in userspace.
1387 * We are interested in: signals which need to have special handling
1388 * as described above, and all signals which have traps set.
1389 * Signals are rocorded in pending_set.
1390 * After each pipe execution, we extract any pending signals
1391 * and act on them.
1392 *
1393 * unsigned special_sig_mask: a mask of shell-special signals.
1394 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1395 * char *traps[sig] if trap for sig is set (even if it's '').
1396 * sigset_t pending_set: set of sigs we received.
1397 *
1398 * "trap - SIGxxx":
1399 * if sig is in special_sig_mask, set handler back to:
1400 * record_pending_signo, or to IGN if it's a tty stop signal
1401 * if sig is in fatal_sig_mask, set handler back to sigexit.
1402 * else: set handler back to SIG_DFL
1403 * "trap 'cmd' SIGxxx":
1404 * set handler to record_pending_signo.
1405 * "trap '' SIGxxx":
1406 * set handler to SIG_IGN.
1407 * after [v]fork, if we plan to be a shell:
1408 * set signals with special interactive handling to SIG_DFL
1409 * (because child shell is not interactive),
1410 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1411 * after [v]fork, if we plan to exec:
1412 * POSIX says fork clears pending signal mask in child - no need to clear it.
1413 *
1414 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1415 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1416 *
1417 * Note (compat):
1418 * Standard says "When a subshell is entered, traps that are not being ignored
1419 * are set to the default actions". bash interprets it so that traps which
1420 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001421 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001422enum {
1423 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001424 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001425 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001426 | (1 << SIGHUP)
1427 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001428 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001429#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001430 | (1 << SIGTTIN)
1431 | (1 << SIGTTOU)
1432 | (1 << SIGTSTP)
1433#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001434 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001435};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001436
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001437static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001438{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001439 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001440#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001441 if (sig == SIGCHLD) {
1442 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001443//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 +02001444 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001445#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001446}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001447
Denys Vlasenko0806e402011-05-12 23:06:20 +02001448static sighandler_t install_sighandler(int sig, sighandler_t handler)
1449{
1450 struct sigaction old_sa;
1451
1452 /* We could use signal() to install handlers... almost:
1453 * except that we need to mask ALL signals while handlers run.
1454 * I saw signal nesting in strace, race window isn't small.
1455 * SA_RESTART is also needed, but in Linux, signal()
1456 * sets SA_RESTART too.
1457 */
1458 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1459 /* sigfillset(&G.sa.sa_mask); - already done */
1460 /* G.sa.sa_flags = SA_RESTART; - already done */
1461 G.sa.sa_handler = handler;
1462 sigaction(sig, &G.sa, &old_sa);
1463 return old_sa.sa_handler;
1464}
1465
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001466#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001467
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001468/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001469# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001470/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001471# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001472
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001473/* Restores tty foreground process group, and exits.
1474 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001475 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001476 * or called directly with -EXITCODE.
1477 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001478static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001479static void sigexit(int sig)
1480{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001481 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001482 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001483 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1484 /* Disable all signals: job control, SIGPIPE, etc.
1485 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1486 */
1487 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001488 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001489 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001490
1491 /* Not a signal, just exit */
1492 if (sig <= 0)
1493 _exit(- sig);
1494
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001495 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001496}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001497#else
1498
Denys Vlasenko8391c482010-05-22 17:50:43 +02001499# define disable_restore_tty_pgrp_on_exit() ((void)0)
1500# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001501
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001502#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001503
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001504static sighandler_t pick_sighandler(unsigned sig)
1505{
1506 sighandler_t handler = SIG_DFL;
1507 if (sig < sizeof(unsigned)*8) {
1508 unsigned sigmask = (1 << sig);
1509
1510#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001511 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001512 if (G_fatal_sig_mask & sigmask)
1513 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001514 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001515#endif
1516 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001517 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001518 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001519 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001520 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001521 * in an endless loop when we try to do some
1522 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001523 */
1524 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1525 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001526 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001527 }
1528 return handler;
1529}
1530
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001531/* Restores tty foreground process group, and exits. */
1532static void hush_exit(int exitcode) NORETURN;
1533static void hush_exit(int exitcode)
1534{
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001535 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001536 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001537 char *argv[3];
1538 /* argv[0] is unused */
1539 argv[1] = G.traps[0];
1540 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001541 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001542 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001543 * "trap" will still show it, if executed
1544 * in the handler */
1545 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001546 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001547
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001548#if ENABLE_FEATURE_CLEAN_UP
1549 {
1550 struct variable *cur_var;
1551 if (G.cwd != bb_msg_unknown)
1552 free((char*)G.cwd);
1553 cur_var = G.top_var;
1554 while (cur_var) {
1555 struct variable *tmp = cur_var;
1556 if (!cur_var->max_len)
1557 free(cur_var->varstr);
1558 cur_var = cur_var->next;
1559 free(tmp);
1560 }
1561 }
1562#endif
1563
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001564#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001565 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001566 sigexit(- (exitcode & 0xff));
1567#else
1568 exit(exitcode);
1569#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001570}
1571
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001572
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001573//TODO: return a mask of ALL handled sigs?
1574static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001575{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001576 int last_sig = 0;
1577
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001578 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001579 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001580
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001581 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001582 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001583 sig = 0;
1584 do {
1585 sig++;
1586 if (sigismember(&G.pending_set, sig)) {
1587 sigdelset(&G.pending_set, sig);
1588 goto got_sig;
1589 }
1590 } while (sig < NSIG);
1591 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001592 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001593 if (G.traps && G.traps[sig]) {
1594 if (G.traps[sig][0]) {
1595 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001596 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001597 char *argv[3];
1598 /* argv[0] is unused */
1599 argv[1] = G.traps[sig];
1600 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001601 save_rcode = G.last_exitcode;
1602 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001603 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001604 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001605 } /* else: "" trap, ignoring signal */
1606 continue;
1607 }
1608 /* not a trap: special action */
1609 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001610 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001611 /* Builtin was ^C'ed, make it look prettier: */
1612 bb_putchar('\n');
1613 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001614 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001615 break;
1616#if ENABLE_HUSH_JOB
1617 case SIGHUP: {
1618 struct pipe *job;
1619 /* bash is observed to signal whole process groups,
1620 * not individual processes */
1621 for (job = G.job_list; job; job = job->next) {
1622 if (job->pgrp <= 0)
1623 continue;
1624 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1625 if (kill(- job->pgrp, SIGHUP) == 0)
1626 kill(- job->pgrp, SIGCONT);
1627 }
1628 sigexit(SIGHUP);
1629 }
1630#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001631#if ENABLE_HUSH_FAST
1632 case SIGCHLD:
1633 G.count_SIGCHLD++;
1634//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1635 /* Note:
1636 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1637 * This simplifies wait builtin a bit.
1638 */
1639 break;
1640#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001641 default: /* ignored: */
1642 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001643 /* Note:
1644 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1645 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001646 * in interactive shell, because TERM is ignored.
1647 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001648 break;
1649 }
1650 }
1651 return last_sig;
1652}
1653
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001654
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001655static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001656{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001657 if (force || G.cwd == NULL) {
1658 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1659 * we must not try to free(bb_msg_unknown) */
1660 if (G.cwd == bb_msg_unknown)
1661 G.cwd = NULL;
1662 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1663 if (!G.cwd)
1664 G.cwd = bb_msg_unknown;
1665 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001666 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001667}
1668
Denis Vlasenko83506862007-11-23 13:11:42 +00001669
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001670/*
1671 * Shell and environment variable support
1672 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001673static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001674{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001675 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001676 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001677
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001678 pp = &G.top_var;
1679 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001680 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001681 return pp;
1682 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001683 }
1684 return NULL;
1685}
1686
Denys Vlasenko03dad222010-01-12 23:29:57 +01001687static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001688{
Denys Vlasenko29082232010-07-16 13:52:32 +02001689 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001690 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001691
1692 if (G.expanded_assignments) {
1693 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001694 while (*cpp) {
1695 char *cp = *cpp;
1696 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1697 return cp + len + 1;
1698 cpp++;
1699 }
1700 }
1701
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001702 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001703 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001704 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001705
Denys Vlasenkodea47882009-10-09 15:40:49 +02001706 if (strcmp(name, "PPID") == 0)
1707 return utoa(G.root_ppid);
1708 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001709#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001710 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001711 return utoa(next_random(&G.random_gen));
1712#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001713 return NULL;
1714}
1715
1716/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001717 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001718 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001719 * 0: do not change export flag
1720 * (if creating new variable, flag will be 0)
1721 * 1: set export flag and putenv the variable
1722 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001723 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001724 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001725#if !BB_MMU && ENABLE_HUSH_LOCAL
1726/* all params are used */
1727#elif BB_MMU && ENABLE_HUSH_LOCAL
1728#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1729 set_local_var(str, flg_export, local_lvl)
1730#elif BB_MMU && !ENABLE_HUSH_LOCAL
1731#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001732 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001733#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1734#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1735 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001736#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001737static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001738{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001739 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001740 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001741 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001742 int name_len;
1743
Denis Vlasenko950bd722009-04-21 11:23:56 +00001744 eq_sign = strchr(str, '=');
1745 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001746 free(str);
1747 return -1;
1748 }
1749
Denis Vlasenko950bd722009-04-21 11:23:56 +00001750 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001751 var_pp = &G.top_var;
1752 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001753 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001754 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001755 continue;
1756 }
1757 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001758 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001759#if !BB_MMU
1760 if (!flg_read_only)
1761#endif
1762 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001763 free(str);
1764 return -1;
1765 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001766 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001767 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1768 *eq_sign = '\0';
1769 unsetenv(str);
1770 *eq_sign = '=';
1771 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001772#if ENABLE_HUSH_LOCAL
1773 if (cur->func_nest_level < local_lvl) {
1774 /* New variable is declared as local,
1775 * and existing one is global, or local
1776 * from enclosing function.
1777 * Remove and save old one: */
1778 *var_pp = cur->next;
1779 cur->next = *G.shadowed_vars_pp;
1780 *G.shadowed_vars_pp = cur;
1781 /* bash 3.2.33(1) and exported vars:
1782 * # export z=z
1783 * # f() { local z=a; env | grep ^z; }
1784 * # f
1785 * z=a
1786 * # env | grep ^z
1787 * z=z
1788 */
1789 if (cur->flg_export)
1790 flg_export = 1;
1791 break;
1792 }
1793#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001794 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001795 free_and_exp:
1796 free(str);
1797 goto exp;
1798 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001799 if (cur->max_len != 0) {
1800 if (cur->max_len >= strlen(str)) {
1801 /* This one is from startup env, reuse space */
1802 strcpy(cur->varstr, str);
1803 goto free_and_exp;
1804 }
1805 } else {
1806 /* max_len == 0 signifies "malloced" var, which we can
1807 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001808 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001809 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001810 cur->max_len = 0;
1811 goto set_str_and_exp;
1812 }
1813
Denys Vlasenko295fef82009-06-03 12:47:26 +02001814 /* Not found - create new variable struct */
1815 cur = xzalloc(sizeof(*cur));
1816#if ENABLE_HUSH_LOCAL
1817 cur->func_nest_level = local_lvl;
1818#endif
1819 cur->next = *var_pp;
1820 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001821
1822 set_str_and_exp:
1823 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001824#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001825 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001826#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001827 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001828 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001829 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001830 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1831 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001832 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001833 if (flg_export == -1) {
1834 cur->flg_export = 0;
1835 /* unsetenv was already done */
1836 } else {
1837 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1838 return putenv(cur->varstr);
1839 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001840 }
1841 return 0;
1842}
1843
Denys Vlasenko6db47842009-09-05 20:15:17 +02001844/* Used at startup and after each cd */
1845static void set_pwd_var(int exp)
1846{
1847 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1848 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1849}
1850
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001851static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001852{
1853 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001854 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001855
1856 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001857 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001858 var_pp = &G.top_var;
1859 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001860 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1861 if (cur->flg_read_only) {
1862 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001863 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001864 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001865 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001866 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1867 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001868 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1869 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001870 if (!cur->max_len)
1871 free(cur->varstr);
1872 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001873 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001874 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001875 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001876 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001877 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001878}
1879
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001880static int unset_local_var(const char *name)
1881{
1882 return unset_local_var_len(name, strlen(name));
1883}
1884
1885static void unset_vars(char **strings)
1886{
1887 char **v;
1888
1889 if (!strings)
1890 return;
1891 v = strings;
1892 while (*v) {
1893 const char *eq = strchrnul(*v, '=');
1894 unset_local_var_len(*v, (int)(eq - *v));
1895 v++;
1896 }
1897 free(strings);
1898}
1899
Denys Vlasenko03dad222010-01-12 23:29:57 +01001900static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001901{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001902 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001903 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001904}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001905
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001906
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001907/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001908 * Helpers for "var1=val1 var2=val2 cmd" feature
1909 */
1910static void add_vars(struct variable *var)
1911{
1912 struct variable *next;
1913
1914 while (var) {
1915 next = var->next;
1916 var->next = G.top_var;
1917 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001918 if (var->flg_export) {
1919 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001920 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001921 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001922 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001923 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001924 var = next;
1925 }
1926}
1927
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001928static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001929{
1930 char **s;
1931 struct variable *old = NULL;
1932
1933 if (!strings)
1934 return old;
1935 s = strings;
1936 while (*s) {
1937 struct variable *var_p;
1938 struct variable **var_pp;
1939 char *eq;
1940
1941 eq = strchr(*s, '=');
1942 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001943 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001944 if (var_pp) {
1945 /* Remove variable from global linked list */
1946 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001947 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001948 *var_pp = var_p->next;
1949 /* Add it to returned list */
1950 var_p->next = old;
1951 old = var_p;
1952 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001953 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001954 }
1955 s++;
1956 }
1957 return old;
1958}
1959
1960
1961/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001962 * in_str support
1963 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001964static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001965{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001966 int ch = *i->p;
1967 if (ch != '\0') {
1968 i->p++;
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001969 i->last_char = ch;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001970 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001971 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001972 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001973}
1974
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001975static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001976{
1977 return *i->p;
1978}
1979
1980#if ENABLE_HUSH_INTERACTIVE
1981
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001982static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001983{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001984 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001985 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001986 if (G.PS1 == NULL)
1987 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001988 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001989 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001990 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001991 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001992 if (G.PS2 == NULL)
1993 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001994}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001995
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001996static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001997{
1998 const char *prompt_str;
1999 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002000 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2001 /* Set up the prompt */
2002 if (promptmode == 0) { /* PS1 */
2003 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002004 /* bash uses $PWD value, even if it is set by user.
2005 * It uses current dir only if PWD is unset.
2006 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002007 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002008 prompt_str = G.PS1;
2009 } else
2010 prompt_str = G.PS2;
2011 } else
2012 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002013 debug_printf("result '%s'\n", prompt_str);
2014 return prompt_str;
2015}
2016
2017static void get_user_input(struct in_str *i)
2018{
2019 int r;
2020 const char *prompt_str;
2021
2022 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002023# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002024 /* Enable command line editing only while a command line
2025 * is actually being read */
2026 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01002027 /* Unicode support should be activated even if LANG is set
2028 * _during_ shell execution, not only if it was set when
2029 * shell was started. Therefore, re-check LANG every time:
2030 */
2031 reinit_unicode(get_local_var_value("LANG"));
2032
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002033 G.flag_SIGINT = 0;
2034 /* buglet: SIGINT will not make new prompt to appear _at once_,
2035 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002036 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 +00002037 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002038 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002039 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002040 i->eof_flag = (r < 0);
2041 if (i->eof_flag) { /* EOF/error detected */
2042 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2043 G.user_input_buf[1] = '\0';
2044 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02002045# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002046 do {
2047 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002048 if (i->last_char == '\0' || i->last_char == '\n') {
2049 /* Why check_and_run_traps here? Try this interactively:
2050 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2051 * $ <[enter], repeatedly...>
2052 * Without check_and_run_traps, handler never runs.
2053 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002054 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002055 fputs(prompt_str, stdout);
2056 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002057 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002058 G.user_input_buf[0] = r = fgetc(i->file);
2059 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002060 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002061 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002062# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002063 i->p = G.user_input_buf;
2064}
2065
2066#endif /* INTERACTIVE */
2067
2068/* This is the magic location that prints prompts
2069 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002070static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002071{
2072 int ch;
2073
2074 /* If there is data waiting, eat it up */
2075 if (i->p && *i->p) {
2076#if ENABLE_HUSH_INTERACTIVE
2077 take_cached:
2078#endif
2079 ch = *i->p++;
2080 if (i->eof_flag && !*i->p)
2081 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002082 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002083 } else {
2084 /* need to double check i->file because we might be doing something
2085 * more complicated by now, like sourcing or substituting. */
2086#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002087 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002088 do {
2089 get_user_input(i);
2090 } while (!*i->p); /* need non-empty line */
2091 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002092 goto take_cached;
2093 }
2094#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00002095 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002096 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002097 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002098 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002099 return ch;
2100}
2101
Denis Vlasenko913a2012009-04-05 22:17:04 +00002102/* All callers guarantee this routine will never
2103 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002104 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002105static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002106{
2107 int ch;
2108 if (i->p && *i->p) {
2109 if (i->eof_flag && !i->p[1])
2110 return EOF;
2111 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002112 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002113 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002114 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002115 i->eof_flag = (ch == EOF);
2116 i->peek_buf[0] = ch;
2117 i->peek_buf[1] = '\0';
2118 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002119 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002120 return ch;
2121}
2122
2123static void setup_file_in_str(struct in_str *i, FILE *f)
2124{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002125 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002126 i->peek = file_peek;
2127 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002128 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002129 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002130 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002131}
2132
2133static void setup_string_in_str(struct in_str *i, const char *s)
2134{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002135 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002136 i->peek = static_peek;
2137 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002138 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002139 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002140 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002141}
2142
2143
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002144/*
2145 * o_string support
2146 */
2147#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002148
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002149static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002150{
2151 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002152 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002153 if (o->data)
2154 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002155}
2156
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002157static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002158{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002159 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002160 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002161}
2162
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002163static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2164{
2165 free(o->data);
2166}
2167
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002168static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002169{
2170 if (o->length + len > o->maxlen) {
2171 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2172 o->data = xrealloc(o->data, 1 + o->maxlen);
2173 }
2174}
2175
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002176static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002177{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002178 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2179 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002180 o->data[o->length] = ch;
2181 o->length++;
2182 o->data[o->length] = '\0';
2183}
2184
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002185static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002186{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002187 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002188 memcpy(&o->data[o->length], str, len);
2189 o->length += len;
2190 o->data[o->length] = '\0';
2191}
2192
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002193static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002194{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002195 o_addblock(o, str, strlen(str));
2196}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002197
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002198#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002199static void nommu_addchr(o_string *o, int ch)
2200{
2201 if (o)
2202 o_addchr(o, ch);
2203}
2204#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002205# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002206#endif
2207
2208static void o_addstr_with_NUL(o_string *o, const char *str)
2209{
2210 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002211}
2212
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002213/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002214 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002215 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2216 * Apparently, on unquoted $v bash still does globbing
2217 * ("v='*.txt'; echo $v" prints all .txt files),
2218 * but NOT brace expansion! Thus, there should be TWO independent
2219 * quoting mechanisms on $v expansion side: one protects
2220 * $v from brace expansion, and other additionally protects "$v" against globbing.
2221 * We have only second one.
2222 */
2223
Denys Vlasenko9e800222010-10-03 14:28:04 +02002224#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002225# define MAYBE_BRACES "{}"
2226#else
2227# define MAYBE_BRACES ""
2228#endif
2229
Eric Andersen25f27032001-04-26 23:22:31 +00002230/* My analysis of quoting semantics tells me that state information
2231 * is associated with a destination, not a source.
2232 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002233static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002234{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002235 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002236 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002237 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002238 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002239 o_grow_by(o, sz);
2240 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002241 o->data[o->length] = '\\';
2242 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002243 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002244 o->data[o->length] = ch;
2245 o->length++;
2246 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002247}
2248
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002249static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002250{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002251 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002252 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2253 && strchr("*?[\\" MAYBE_BRACES, ch)
2254 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002255 sz++;
2256 o->data[o->length] = '\\';
2257 o->length++;
2258 }
2259 o_grow_by(o, sz);
2260 o->data[o->length] = ch;
2261 o->length++;
2262 o->data[o->length] = '\0';
2263}
2264
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002265static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002266{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002267 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002268 char ch;
2269 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002270 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002271 if (ordinary_cnt > len) /* paranoia */
2272 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002273 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002274 if (ordinary_cnt == len)
2275 return;
2276 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002277 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002278
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002279 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002280 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002281 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002282 sz++;
2283 o->data[o->length] = '\\';
2284 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002285 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002286 o_grow_by(o, sz);
2287 o->data[o->length] = ch;
2288 o->length++;
2289 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002290 }
2291}
2292
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002293static void o_addQblock(o_string *o, const char *str, int len)
2294{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002295 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002296 o_addblock(o, str, len);
2297 return;
2298 }
2299 o_addqblock(o, str, len);
2300}
2301
Denys Vlasenko38292b62010-09-05 14:49:40 +02002302static void o_addQstr(o_string *o, const char *str)
2303{
2304 o_addQblock(o, str, strlen(str));
2305}
2306
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002307/* A special kind of o_string for $VAR and `cmd` expansion.
2308 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002309 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002310 * list[i] contains an INDEX (int!) into this string data.
2311 * It means that if list[] needs to grow, data needs to be moved higher up
2312 * but list[i]'s need not be modified.
2313 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002314 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002315 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2316 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002317#if DEBUG_EXPAND || DEBUG_GLOB
2318static void debug_print_list(const char *prefix, o_string *o, int n)
2319{
2320 char **list = (char**)o->data;
2321 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2322 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002323
2324 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002325 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 +02002326 prefix, list, n, string_start, o->length, o->maxlen,
2327 !!(o->o_expflags & EXP_FLAG_GLOB),
2328 o->has_quoted_part,
2329 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002330 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002331 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002332 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2333 o->data + (int)(uintptr_t)list[i] + string_start,
2334 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002335 i++;
2336 }
2337 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002338 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002339 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002340 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002341 }
2342}
2343#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002344# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002345#endif
2346
2347/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2348 * in list[n] so that it points past last stored byte so far.
2349 * It returns n+1. */
2350static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002351{
2352 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002353 int string_start;
2354 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002355
2356 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002357 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2358 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002359 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002360 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002361 /* list[n] points to string_start, make space for 16 more pointers */
2362 o->maxlen += 0x10 * sizeof(list[0]);
2363 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002364 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002365 memmove(list + n + 0x10, list + n, string_len);
2366 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002367 } else {
2368 debug_printf_list("list[%d]=%d string_start=%d\n",
2369 n, string_len, string_start);
2370 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002371 } else {
2372 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002373 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2374 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002375 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2376 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002377 o->has_empty_slot = 0;
2378 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002379 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002380 return n + 1;
2381}
2382
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002383/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002384static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002385{
2386 char **list = (char**)o->data;
2387 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2388
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002389 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002390}
2391
Denys Vlasenko9e800222010-10-03 14:28:04 +02002392#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002393/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2394 * first, it processes even {a} (no commas), second,
2395 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002396 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002397 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002398
2399/* Helper */
2400static int glob_needed(const char *s)
2401{
2402 while (*s) {
2403 if (*s == '\\') {
2404 if (!s[1])
2405 return 0;
2406 s += 2;
2407 continue;
2408 }
2409 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2410 return 1;
2411 s++;
2412 }
2413 return 0;
2414}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002415/* Return pointer to next closing brace or to comma */
2416static const char *next_brace_sub(const char *cp)
2417{
2418 unsigned depth = 0;
2419 cp++;
2420 while (*cp != '\0') {
2421 if (*cp == '\\') {
2422 if (*++cp == '\0')
2423 break;
2424 cp++;
2425 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002426 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002427 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002428 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002429 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002430 depth++;
2431 }
2432
2433 return *cp != '\0' ? cp : NULL;
2434}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002435/* Recursive brace globber. Note: may garble pattern[]. */
2436static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002437{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002438 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002439 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002440 const char *next;
2441 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002442 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002443 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002444
2445 debug_printf_glob("glob_brace('%s')\n", pattern);
2446
2447 begin = pattern;
2448 while (1) {
2449 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002450 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002451 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002452 /* Find the first sub-pattern and at the same time
2453 * find the rest after the closing brace */
2454 next = next_brace_sub(begin);
2455 if (next == NULL) {
2456 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002457 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002458 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002459 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002460 /* "{abc}" with no commas - illegal
2461 * brace expr, disregard and skip it */
2462 begin = next + 1;
2463 continue;
2464 }
2465 break;
2466 }
2467 if (*begin == '\\' && begin[1] != '\0')
2468 begin++;
2469 begin++;
2470 }
2471 debug_printf_glob("begin:%s\n", begin);
2472 debug_printf_glob("next:%s\n", next);
2473
2474 /* Now find the end of the whole brace expression */
2475 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002476 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002477 rest = next_brace_sub(rest);
2478 if (rest == NULL) {
2479 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002480 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002481 }
2482 debug_printf_glob("rest:%s\n", rest);
2483 }
2484 rest_len = strlen(++rest) + 1;
2485
2486 /* We are sure the brace expression is well-formed */
2487
2488 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002489 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002490
2491 /* We have a brace expression. BEGIN points to the opening {,
2492 * NEXT points past the terminator of the first element, and REST
2493 * points past the final }. We will accumulate result names from
2494 * recursive runs for each brace alternative in the buffer using
2495 * GLOB_APPEND. */
2496
2497 p = begin + 1;
2498 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002499 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002500 memcpy(
2501 mempcpy(
2502 mempcpy(new_pattern_buf,
2503 /* We know the prefix for all sub-patterns */
2504 pattern, begin - pattern),
2505 p, next - p),
2506 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002507
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002508 /* Note: glob_brace() may garble new_pattern_buf[].
2509 * That's why we re-copy prefix every time (1st memcpy above).
2510 */
2511 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002512 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002513 /* We saw the last entry */
2514 break;
2515 }
2516 p = next + 1;
2517 next = next_brace_sub(next);
2518 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002519 free(new_pattern_buf);
2520 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002521
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002522 simple_glob:
2523 {
2524 int gr;
2525 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002526
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002527 memset(&globdata, 0, sizeof(globdata));
2528 gr = glob(pattern, 0, NULL, &globdata);
2529 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2530 if (gr != 0) {
2531 if (gr == GLOB_NOMATCH) {
2532 globfree(&globdata);
2533 /* NB: garbles parameter */
2534 unbackslash(pattern);
2535 o_addstr_with_NUL(o, pattern);
2536 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2537 return o_save_ptr_helper(o, n);
2538 }
2539 if (gr == GLOB_NOSPACE)
2540 bb_error_msg_and_die(bb_msg_memory_exhausted);
2541 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2542 * but we didn't specify it. Paranoia again. */
2543 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2544 }
2545 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2546 char **argv = globdata.gl_pathv;
2547 while (1) {
2548 o_addstr_with_NUL(o, *argv);
2549 n = o_save_ptr_helper(o, n);
2550 argv++;
2551 if (!*argv)
2552 break;
2553 }
2554 }
2555 globfree(&globdata);
2556 }
2557 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002558}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002559/* Performs globbing on last list[],
2560 * saving each result as a new list[].
2561 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002562static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002563{
2564 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002565
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002566 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002567 if (!o->data)
2568 return o_save_ptr_helper(o, n);
2569 pattern = o->data + o_get_last_ptr(o, n);
2570 debug_printf_glob("glob pattern '%s'\n", pattern);
2571 if (!glob_needed(pattern)) {
2572 /* unbackslash last string in o in place, fix length */
2573 o->length = unbackslash(pattern) - o->data;
2574 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2575 return o_save_ptr_helper(o, n);
2576 }
2577
2578 copy = xstrdup(pattern);
2579 /* "forget" pattern in o */
2580 o->length = pattern - o->data;
2581 n = glob_brace(copy, o, n);
2582 free(copy);
2583 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002584 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002585 return n;
2586}
2587
Denys Vlasenko238081f2010-10-03 14:26:26 +02002588#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002589
2590/* Helper */
2591static int glob_needed(const char *s)
2592{
2593 while (*s) {
2594 if (*s == '\\') {
2595 if (!s[1])
2596 return 0;
2597 s += 2;
2598 continue;
2599 }
2600 if (*s == '*' || *s == '[' || *s == '?')
2601 return 1;
2602 s++;
2603 }
2604 return 0;
2605}
2606/* Performs globbing on last list[],
2607 * saving each result as a new list[].
2608 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002609static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002610{
2611 glob_t globdata;
2612 int gr;
2613 char *pattern;
2614
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002615 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002616 if (!o->data)
2617 return o_save_ptr_helper(o, n);
2618 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002619 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002620 if (!glob_needed(pattern)) {
2621 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002622 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002623 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002624 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002625 return o_save_ptr_helper(o, n);
2626 }
2627
2628 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002629 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2630 * If we glob "*.\*" and don't find anything, we need
2631 * to fall back to using literal "*.*", but GLOB_NOCHECK
2632 * will return "*.\*"!
2633 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002634 gr = glob(pattern, 0, NULL, &globdata);
2635 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002636 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002637 if (gr == GLOB_NOMATCH) {
2638 globfree(&globdata);
2639 goto literal;
2640 }
2641 if (gr == GLOB_NOSPACE)
2642 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002643 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2644 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002645 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002646 }
2647 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2648 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002649 /* "forget" pattern in o */
2650 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002651 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002652 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002653 n = o_save_ptr_helper(o, n);
2654 argv++;
2655 if (!*argv)
2656 break;
2657 }
2658 }
2659 globfree(&globdata);
2660 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002661 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002662 return n;
2663}
2664
Denys Vlasenko238081f2010-10-03 14:26:26 +02002665#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002666
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002667/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002668 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002669static int o_save_ptr(o_string *o, int n)
2670{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002671 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002672 /* If o->has_empty_slot, list[n] was already globbed
2673 * (if it was requested back then when it was filled)
2674 * so don't do that again! */
2675 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002676 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002677 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002678 return o_save_ptr_helper(o, n);
2679}
2680
2681/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002682static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002683{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002684 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002685 int string_start;
2686
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002687 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2688 if (DEBUG_EXPAND)
2689 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002690 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002691 list = (char**)o->data;
2692 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2693 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002694 while (n) {
2695 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002696 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002697 }
2698 return list;
2699}
2700
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002701static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002702
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002703/* Returns pi->next - next pipe in the list */
2704static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002705{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002706 struct pipe *next;
2707 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002708
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002709 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002710 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002711 struct command *command;
2712 struct redir_struct *r, *rnext;
2713
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002714 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002715 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002716 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002717 if (DEBUG_CLEAN) {
2718 int a;
2719 char **p;
2720 for (a = 0, p = command->argv; *p; a++, p++) {
2721 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2722 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002723 }
2724 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002725 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002726 }
2727 /* not "else if": on syntax error, we may have both! */
2728 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002729 debug_printf_clean(" begin group (cmd_type:%d)\n",
2730 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002731 free_pipe_list(command->group);
2732 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002733 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002734 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002735 /* else is crucial here.
2736 * If group != NULL, child_func is meaningless */
2737#if ENABLE_HUSH_FUNCTIONS
2738 else if (command->child_func) {
2739 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2740 command->child_func->parent_cmd = NULL;
2741 }
2742#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002743#if !BB_MMU
2744 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002745 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002746#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002747 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002748 debug_printf_clean(" redirect %d%s",
2749 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002750 /* guard against the case >$FOO, where foo is unset or blank */
2751 if (r->rd_filename) {
2752 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2753 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002754 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002755 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002756 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002757 rnext = r->next;
2758 free(r);
2759 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002760 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002761 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002762 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002763 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002764#if ENABLE_HUSH_JOB
2765 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002766 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002767#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002768
2769 next = pi->next;
2770 free(pi);
2771 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002772}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002773
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002774static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002775{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002776 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002777#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002778 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002779#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002780 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002781 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002782 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002783}
2784
2785
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002786/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002787
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002788#ifndef debug_print_tree
2789static void debug_print_tree(struct pipe *pi, int lvl)
2790{
2791 static const char *const PIPE[] = {
2792 [PIPE_SEQ] = "SEQ",
2793 [PIPE_AND] = "AND",
2794 [PIPE_OR ] = "OR" ,
2795 [PIPE_BG ] = "BG" ,
2796 };
2797 static const char *RES[] = {
2798 [RES_NONE ] = "NONE" ,
2799# if ENABLE_HUSH_IF
2800 [RES_IF ] = "IF" ,
2801 [RES_THEN ] = "THEN" ,
2802 [RES_ELIF ] = "ELIF" ,
2803 [RES_ELSE ] = "ELSE" ,
2804 [RES_FI ] = "FI" ,
2805# endif
2806# if ENABLE_HUSH_LOOPS
2807 [RES_FOR ] = "FOR" ,
2808 [RES_WHILE] = "WHILE",
2809 [RES_UNTIL] = "UNTIL",
2810 [RES_DO ] = "DO" ,
2811 [RES_DONE ] = "DONE" ,
2812# endif
2813# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2814 [RES_IN ] = "IN" ,
2815# endif
2816# if ENABLE_HUSH_CASE
2817 [RES_CASE ] = "CASE" ,
2818 [RES_CASE_IN ] = "CASE_IN" ,
2819 [RES_MATCH] = "MATCH",
2820 [RES_CASE_BODY] = "CASE_BODY",
2821 [RES_ESAC ] = "ESAC" ,
2822# endif
2823 [RES_XXXX ] = "XXXX" ,
2824 [RES_SNTX ] = "SNTX" ,
2825 };
2826 static const char *const CMDTYPE[] = {
2827 "{}",
2828 "()",
2829 "[noglob]",
2830# if ENABLE_HUSH_FUNCTIONS
2831 "func()",
2832# endif
2833 };
2834
2835 int pin, prn;
2836
2837 pin = 0;
2838 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002839 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002840 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2841 prn = 0;
2842 while (prn < pi->num_cmds) {
2843 struct command *command = &pi->cmds[prn];
2844 char **argv = command->argv;
2845
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002846 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002847 lvl*2, "", prn,
2848 command->assignment_cnt);
2849 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002850 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002851 CMDTYPE[command->cmd_type],
2852 argv
2853# if !BB_MMU
2854 , " group_as_string:", command->group_as_string
2855# else
2856 , "", ""
2857# endif
2858 );
2859 debug_print_tree(command->group, lvl+1);
2860 prn++;
2861 continue;
2862 }
2863 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002864 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002865 argv++;
2866 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002867 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002868 prn++;
2869 }
2870 pi = pi->next;
2871 pin++;
2872 }
2873}
2874#endif /* debug_print_tree */
2875
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002876static struct pipe *new_pipe(void)
2877{
Eric Andersen25f27032001-04-26 23:22:31 +00002878 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002879 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002880 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002881 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002882 return pi;
2883}
2884
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002885/* Command (member of a pipe) is complete, or we start a new pipe
2886 * if ctx->command is NULL.
2887 * No errors possible here.
2888 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002889static int done_command(struct parse_context *ctx)
2890{
2891 /* The command is really already in the pipe structure, so
2892 * advance the pipe counter and make a new, null command. */
2893 struct pipe *pi = ctx->pipe;
2894 struct command *command = ctx->command;
2895
2896 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002897 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002898 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002899 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002900 }
2901 pi->num_cmds++;
2902 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002903 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002904 } else {
2905 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2906 }
2907
2908 /* Only real trickiness here is that the uncommitted
2909 * command structure is not counted in pi->num_cmds. */
2910 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002911 ctx->command = command = &pi->cmds[pi->num_cmds];
2912 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002913 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002914 return pi->num_cmds; /* used only for 0/nonzero check */
2915}
2916
2917static void done_pipe(struct parse_context *ctx, pipe_style type)
2918{
2919 int not_null;
2920
2921 debug_printf_parse("done_pipe entered, followup %d\n", type);
2922 /* Close previous command */
2923 not_null = done_command(ctx);
2924 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002925#if HAS_KEYWORDS
2926 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2927 ctx->ctx_inverted = 0;
2928 ctx->pipe->res_word = ctx->ctx_res_w;
2929#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002930
2931 /* Without this check, even just <enter> on command line generates
2932 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002933 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002934 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002935#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002936 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002937#endif
2938#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002939 || ctx->ctx_res_w == RES_DONE
2940 || ctx->ctx_res_w == RES_FOR
2941 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002942#endif
2943#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002944 || ctx->ctx_res_w == RES_ESAC
2945#endif
2946 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002947 struct pipe *new_p;
2948 debug_printf_parse("done_pipe: adding new pipe: "
2949 "not_null:%d ctx->ctx_res_w:%d\n",
2950 not_null, ctx->ctx_res_w);
2951 new_p = new_pipe();
2952 ctx->pipe->next = new_p;
2953 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002954 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002955 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002956 * This is used to control execution.
2957 * RES_FOR and RES_IN are NOT sticky (needed to support
2958 * cases where variable or value happens to match a keyword):
2959 */
2960#if ENABLE_HUSH_LOOPS
2961 if (ctx->ctx_res_w == RES_FOR
2962 || ctx->ctx_res_w == RES_IN)
2963 ctx->ctx_res_w = RES_NONE;
2964#endif
2965#if ENABLE_HUSH_CASE
2966 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002967 ctx->ctx_res_w = RES_CASE_BODY;
2968 if (ctx->ctx_res_w == RES_CASE)
2969 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002970#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002971 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002972 /* Create the memory for command, roughly:
2973 * ctx->pipe->cmds = new struct command;
2974 * ctx->command = &ctx->pipe->cmds[0];
2975 */
2976 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002977 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002978 }
2979 debug_printf_parse("done_pipe return\n");
2980}
2981
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002982static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002983{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002984 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002985 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002986 /* Create the memory for command, roughly:
2987 * ctx->pipe->cmds = new struct command;
2988 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002989 */
2990 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002991}
2992
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002993/* If a reserved word is found and processed, parse context is modified
2994 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002995 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002996#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002997struct reserved_combo {
2998 char literal[6];
2999 unsigned char res;
3000 unsigned char assignment_flag;
3001 int flag;
3002};
3003enum {
3004 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003005# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003006 FLAG_IF = (1 << RES_IF ),
3007 FLAG_THEN = (1 << RES_THEN ),
3008 FLAG_ELIF = (1 << RES_ELIF ),
3009 FLAG_ELSE = (1 << RES_ELSE ),
3010 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003011# endif
3012# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003013 FLAG_FOR = (1 << RES_FOR ),
3014 FLAG_WHILE = (1 << RES_WHILE),
3015 FLAG_UNTIL = (1 << RES_UNTIL),
3016 FLAG_DO = (1 << RES_DO ),
3017 FLAG_DONE = (1 << RES_DONE ),
3018 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003019# endif
3020# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003021 FLAG_MATCH = (1 << RES_MATCH),
3022 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003023# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003024 FLAG_START = (1 << RES_XXXX ),
3025};
3026
3027static const struct reserved_combo* match_reserved_word(o_string *word)
3028{
Eric Andersen25f27032001-04-26 23:22:31 +00003029 /* Mostly a list of accepted follow-up reserved words.
3030 * FLAG_END means we are done with the sequence, and are ready
3031 * to turn the compound list into a command.
3032 * FLAG_START means the word must start a new compound list.
3033 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003034 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003035# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003036 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3037 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3038 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3039 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3040 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3041 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003042# endif
3043# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003044 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3045 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3046 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3047 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3048 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3049 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003050# endif
3051# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003052 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3053 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003054# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003055 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003056 const struct reserved_combo *r;
3057
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003058 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003059 if (strcmp(word->data, r->literal) == 0)
3060 return r;
3061 }
3062 return NULL;
3063}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003064/* Return 0: not a keyword, 1: keyword
3065 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003066static int reserved_word(o_string *word, struct parse_context *ctx)
3067{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003068# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003069 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003070 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003071 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003072# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003073 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003074
Denys Vlasenko38292b62010-09-05 14:49:40 +02003075 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003076 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003077 r = match_reserved_word(word);
3078 if (!r)
3079 return 0;
3080
3081 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003082# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003083 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3084 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003085 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003086 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003087# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003088 if (r->flag == 0) { /* '!' */
3089 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003090 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003091 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003092 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003093 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003094 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003095 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003096 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003097 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003098
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003099 old = xmalloc(sizeof(*old));
3100 debug_printf_parse("push stack %p\n", old);
3101 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003102 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003103 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003104 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003105 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003106 ctx->ctx_res_w = RES_SNTX;
3107 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003108 } else {
3109 /* "{...} fi" is ok. "{...} if" is not
3110 * Example:
3111 * if { echo foo; } then { echo bar; } fi */
3112 if (ctx->command->group)
3113 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003114 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003115
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003116 ctx->ctx_res_w = r->res;
3117 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003118 word->o_assignment = r->assignment_flag;
3119
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003120 if (ctx->old_flag & FLAG_END) {
3121 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003122
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003123 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003124 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003125 old = ctx->stack;
3126 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003127 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003128# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003129 o_addstr(&old->as_string, ctx->as_string.data);
3130 o_free_unsafe(&ctx->as_string);
3131 old->command->group_as_string = xstrdup(old->as_string.data);
3132 debug_printf_parse("pop, remembering as:'%s'\n",
3133 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003134# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003135 *ctx = *old; /* physical copy */
3136 free(old);
3137 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003138 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003139}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003140#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003141
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003142/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003143 * Normal return is 0. Syntax errors return 1.
3144 * Note: on return, word is reset, but not o_free'd!
3145 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003146static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003147{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003148 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003149
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003150 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003151 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003152 debug_printf_parse("done_word return 0: true null, ignored\n");
3153 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003154 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003155
Eric Andersen25f27032001-04-26 23:22:31 +00003156 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003157 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3158 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003159 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3160 * "2.7 Redirection
3161 * ...the word that follows the redirection operator
3162 * shall be subjected to tilde expansion, parameter expansion,
3163 * command substitution, arithmetic expansion, and quote
3164 * removal. Pathname expansion shall not be performed
3165 * on the word by a non-interactive shell; an interactive
3166 * shell may perform it, but shall do so only when
3167 * the expansion would result in one word."
3168 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003169 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003170 /* Cater for >\file case:
3171 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3172 * Same with heredocs:
3173 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3174 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003175 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3176 unbackslash(ctx->pending_redirect->rd_filename);
3177 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003178 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003179 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3180 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003181 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003182 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003183 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003184 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003185 /* If this word wasn't an assignment, next ones definitely
3186 * can't be assignments. Even if they look like ones. */
3187 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3188 && word->o_assignment != WORD_IS_KEYWORD
3189 ) {
3190 word->o_assignment = NOT_ASSIGNMENT;
3191 } else {
3192 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3193 command->assignment_cnt++;
3194 word->o_assignment = MAYBE_ASSIGNMENT;
3195 }
3196
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003197#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003198# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003199 if (ctx->ctx_dsemicolon
3200 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3201 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003202 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003203 /* ctx->ctx_res_w = RES_MATCH; */
3204 ctx->ctx_dsemicolon = 0;
3205 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003206# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003207 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003208# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003209 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3210 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003211# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003212# if ENABLE_HUSH_CASE
3213 && ctx->ctx_res_w != RES_CASE
3214# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003215 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003216 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003217 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003218 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003219 debug_printf_parse("done_word return %d\n",
3220 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003221 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003222 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003223# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003224 if (strcmp(word->data, "[[") == 0) {
3225 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3226 }
3227 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003228# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003229 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003230#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003231 if (command->group) {
3232 /* "{ echo foo; } echo bar" - bad */
3233 syntax_error_at(word->data);
3234 debug_printf_parse("done_word return 1: syntax error, "
3235 "groups and arglists don't mix\n");
3236 return 1;
3237 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02003238 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003239 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3240 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003241 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003242 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003243 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003244 char *p = word->data;
3245 while (p[0] == SPECIAL_VAR_SYMBOL
3246 && (p[1] & 0x7f) == '@'
3247 && p[2] == SPECIAL_VAR_SYMBOL
3248 ) {
3249 p += 3;
3250 }
3251 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003252 /* saw no "$@", or not only "$@" but some
3253 * real text is there too */
3254 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003255 * e.g. "", $empty"" etc to not disappear */
3256 o_addchr(word, SPECIAL_VAR_SYMBOL);
3257 o_addchr(word, SPECIAL_VAR_SYMBOL);
3258 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003259 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003260 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003261 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003262 }
Eric Andersen25f27032001-04-26 23:22:31 +00003263
Denis Vlasenko06810332007-05-21 23:30:54 +00003264#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003265 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003266 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003267 || !is_well_formed_var_name(command->argv[0], '\0')
3268 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003269 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003270 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003271 return 1;
3272 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003273 /* Force FOR to have just one word (variable name) */
3274 /* NB: basically, this makes hush see "for v in ..."
3275 * syntax as if it is "for v; in ...". FOR and IN become
3276 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003277 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003278 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003279#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003280#if ENABLE_HUSH_CASE
3281 /* Force CASE to have just one word */
3282 if (ctx->ctx_res_w == RES_CASE) {
3283 done_pipe(ctx, PIPE_SEQ);
3284 }
3285#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003286
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003287 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003288
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003289 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003290 return 0;
3291}
3292
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003293
3294/* Peek ahead in the input to find out if we have a "&n" construct,
3295 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003296 * Return:
3297 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3298 * REDIRFD_SYNTAX_ERR if syntax error,
3299 * REDIRFD_TO_FILE if no & was seen,
3300 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003301 */
3302#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003303#define parse_redir_right_fd(as_string, input) \
3304 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003305#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003306static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003307{
3308 int ch, d, ok;
3309
3310 ch = i_peek(input);
3311 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003312 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003313
3314 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003315 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003316 ch = i_peek(input);
3317 if (ch == '-') {
3318 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003319 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003320 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003321 }
3322 d = 0;
3323 ok = 0;
3324 while (ch != EOF && isdigit(ch)) {
3325 d = d*10 + (ch-'0');
3326 ok = 1;
3327 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003328 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003329 ch = i_peek(input);
3330 }
3331 if (ok) return d;
3332
3333//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3334
3335 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003336 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003337}
3338
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003339/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003340 */
3341static int parse_redirect(struct parse_context *ctx,
3342 int fd,
3343 redir_type style,
3344 struct in_str *input)
3345{
3346 struct command *command = ctx->command;
3347 struct redir_struct *redir;
3348 struct redir_struct **redirp;
3349 int dup_num;
3350
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003351 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003352 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003353 /* Check for a '>&1' type redirect */
3354 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3355 if (dup_num == REDIRFD_SYNTAX_ERR)
3356 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003357 } else {
3358 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003359 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003360 if (dup_num) { /* <<-... */
3361 ch = i_getch(input);
3362 nommu_addchr(&ctx->as_string, ch);
3363 ch = i_peek(input);
3364 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003365 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003366
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003367 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003368 int ch = i_peek(input);
3369 if (ch == '|') {
3370 /* >|FILE redirect ("clobbering" >).
3371 * Since we do not support "set -o noclobber" yet,
3372 * >| and > are the same for now. Just eat |.
3373 */
3374 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003375 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003376 }
3377 }
3378
3379 /* Create a new redir_struct and append it to the linked list */
3380 redirp = &command->redirects;
3381 while ((redir = *redirp) != NULL) {
3382 redirp = &(redir->next);
3383 }
3384 *redirp = redir = xzalloc(sizeof(*redir));
3385 /* redir->next = NULL; */
3386 /* redir->rd_filename = NULL; */
3387 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003388 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003389
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003390 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3391 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003392
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003393 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003394 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003395 /* Erik had a check here that the file descriptor in question
3396 * is legit; I postpone that to "run time"
3397 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003398 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3399 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003400 } else {
3401 /* Set ctx->pending_redirect, so we know what to do at the
3402 * end of the next parsed word. */
3403 ctx->pending_redirect = redir;
3404 }
3405 return 0;
3406}
3407
Eric Andersen25f27032001-04-26 23:22:31 +00003408/* If a redirect is immediately preceded by a number, that number is
3409 * supposed to tell which file descriptor to redirect. This routine
3410 * looks for such preceding numbers. In an ideal world this routine
3411 * needs to handle all the following classes of redirects...
3412 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3413 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3414 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3415 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003416 *
3417 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3418 * "2.7 Redirection
3419 * ... If n is quoted, the number shall not be recognized as part of
3420 * the redirection expression. For example:
3421 * echo \2>a
3422 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003423 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003424 *
3425 * A -1 return means no valid number was found,
3426 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003427 */
3428static int redirect_opt_num(o_string *o)
3429{
3430 int num;
3431
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003432 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003433 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003434 num = bb_strtou(o->data, NULL, 10);
3435 if (errno || num < 0)
3436 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003437 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003438 return num;
3439}
3440
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003441#if BB_MMU
3442#define fetch_till_str(as_string, input, word, skip_tabs) \
3443 fetch_till_str(input, word, skip_tabs)
3444#endif
3445static char *fetch_till_str(o_string *as_string,
3446 struct in_str *input,
3447 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003448 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003449{
3450 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003451 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003452 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003453 int ch;
3454
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003455 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003456
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003457 while (1) {
3458 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003459 if (ch != EOF)
3460 nommu_addchr(as_string, ch);
3461 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003462 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3463 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003464 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3465 heredoc.data[past_EOL] = '\0';
3466 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3467 return heredoc.data;
3468 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003469 while (ch == '\n') {
3470 o_addchr(&heredoc, ch);
3471 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003472 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003473 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003474 do {
3475 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003476 if (ch != EOF)
3477 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003478 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003479 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003480 }
3481 if (ch == EOF) {
3482 o_free_unsafe(&heredoc);
3483 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003484 }
3485 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003486 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003487 if (prev == '\\' && ch == '\\')
3488 /* Correctly handle foo\\<eol> (not a line cont.) */
3489 prev = 0; /* not \ */
3490 else
3491 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003492 }
3493}
3494
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003495/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3496 * and load them all. There should be exactly heredoc_cnt of them.
3497 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003498static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3499{
3500 struct pipe *pi = ctx->list_head;
3501
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003502 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003503 int i;
3504 struct command *cmd = pi->cmds;
3505
3506 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3507 pi->num_cmds,
3508 cmd->argv ? cmd->argv[0] : "NONE");
3509 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003510 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003511
3512 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3513 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003514 while (redir) {
3515 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003516 char *p;
3517
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003518 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003519 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003520 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003521 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003522 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003523 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003524 return 1;
3525 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003526 free(redir->rd_filename);
3527 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003528 heredoc_cnt--;
3529 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003530 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003531 }
3532 cmd++;
3533 }
3534 pi = pi->next;
3535 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003536#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003537 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003538 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003539 bb_error_msg_and_die("heredoc BUG 2");
3540#endif
3541 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003542}
3543
3544
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003545static int run_list(struct pipe *pi);
3546#if BB_MMU
3547#define parse_stream(pstring, input, end_trigger) \
3548 parse_stream(input, end_trigger)
3549#endif
3550static struct pipe *parse_stream(char **pstring,
3551 struct in_str *input,
3552 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003553
Eric Andersen25f27032001-04-26 23:22:31 +00003554
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003555#if !ENABLE_HUSH_FUNCTIONS
3556#define parse_group(dest, ctx, input, ch) \
3557 parse_group(ctx, input, ch)
3558#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003559static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003560 struct in_str *input, int ch)
3561{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003562 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003563 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003564 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003565 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003566 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003567 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003568
3569 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003570#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003571 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003572 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003573 if (done_word(dest, ctx))
3574 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003575 if (!command->argv)
3576 goto skip; /* (... */
3577 if (command->argv[1]) { /* word word ... (... */
3578 syntax_error_unexpected_ch('(');
3579 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003580 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003581 /* it is "word(..." or "word (..." */
3582 do
3583 ch = i_getch(input);
3584 while (ch == ' ' || ch == '\t');
3585 if (ch != ')') {
3586 syntax_error_unexpected_ch(ch);
3587 return 1;
3588 }
3589 nommu_addchr(&ctx->as_string, ch);
3590 do
3591 ch = i_getch(input);
3592 while (ch == ' ' || ch == '\t' || ch == '\n');
3593 if (ch != '{') {
3594 syntax_error_unexpected_ch(ch);
3595 return 1;
3596 }
3597 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003598 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003599 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003600 }
3601#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003602
3603#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003604 if (command->argv /* word [word]{... */
3605 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003606 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003607 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003608 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003609 debug_printf_parse("parse_group return 1: "
3610 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003611 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003612 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003613#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003614
3615#if ENABLE_HUSH_FUNCTIONS
3616 skip:
3617#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003618 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003619 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003620 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003621 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003622 } else {
3623 /* bash does not allow "{echo...", requires whitespace */
3624 ch = i_getch(input);
3625 if (ch != ' ' && ch != '\t' && ch != '\n') {
3626 syntax_error_unexpected_ch(ch);
3627 return 1;
3628 }
3629 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003630 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003631
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003632 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003633#if BB_MMU
3634# define as_string NULL
3635#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003636 char *as_string = NULL;
3637#endif
3638 pipe_list = parse_stream(&as_string, input, endch);
3639#if !BB_MMU
3640 if (as_string)
3641 o_addstr(&ctx->as_string, as_string);
3642#endif
3643 /* empty ()/{} or parse error? */
3644 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003645 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003646 if (!BB_MMU)
3647 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003648 debug_printf_parse("parse_group return 1: "
3649 "parse_stream returned %p\n", pipe_list);
3650 return 1;
3651 }
3652 command->group = pipe_list;
3653#if !BB_MMU
3654 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3655 command->group_as_string = as_string;
3656 debug_printf_parse("end of group, remembering as:'%s'\n",
3657 command->group_as_string);
3658#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003659#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003660 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003661 debug_printf_parse("parse_group return 0\n");
3662 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003663 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003664}
3665
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003666#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003667/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003668static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003669/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003670static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003671{
3672 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003673 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003674 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003675 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003676 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003677 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003678 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003679 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003680 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003681 }
3682}
3683/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003684static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003685{
3686 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003687 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003688 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003689 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003690 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003691 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003692 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003693 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003694 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003695 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003696 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003697 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003698 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003699 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003700 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3701 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003702 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003703 continue;
3704 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003705 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003706 }
3707}
3708/* Process `cmd` - copy contents until "`" is seen. Complicated by
3709 * \` quoting.
3710 * "Within the backquoted style of command substitution, backslash
3711 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3712 * The search for the matching backquote shall be satisfied by the first
3713 * backquote found without a preceding backslash; during this search,
3714 * if a non-escaped backquote is encountered within a shell comment,
3715 * a here-document, an embedded command substitution of the $(command)
3716 * form, or a quoted string, undefined results occur. A single-quoted
3717 * or double-quoted string that begins, but does not end, within the
3718 * "`...`" sequence produces undefined results."
3719 * Example Output
3720 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3721 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003722static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003723{
3724 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003725 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003726 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003727 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003728 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003729 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3730 ch = i_getch(input);
3731 if (ch != '`'
3732 && ch != '$'
3733 && ch != '\\'
3734 && (!in_dquote || ch != '"')
3735 ) {
3736 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003737 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003738 }
3739 if (ch == EOF) {
3740 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003741 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003742 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003743 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003744 }
3745}
3746/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3747 * quoting and nested ()s.
3748 * "With the $(command) style of command substitution, all characters
3749 * following the open parenthesis to the matching closing parenthesis
3750 * constitute the command. Any valid shell script can be used for command,
3751 * except a script consisting solely of redirections which produces
3752 * unspecified results."
3753 * Example Output
3754 * echo $(echo '(TEST)' BEST) (TEST) BEST
3755 * echo $(echo 'TEST)' BEST) TEST) BEST
3756 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003757 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003758 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003759 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003760 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3761 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003762 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003763#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003764static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003765{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003766 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003767 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003768# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003769 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003770# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003771 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3772
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003773 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003774 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003775 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003776 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003777 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003778 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003779 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003780 if (!dbl)
3781 break;
3782 /* we look for closing )) of $((EXPR)) */
3783 if (i_peek(input) == end_ch) {
3784 i_getch(input); /* eat second ')' */
3785 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003786 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003787 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003788 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003789 if (ch == '(' || ch == '{') {
3790 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003791 if (!add_till_closing_bracket(dest, input, ch))
3792 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003793 o_addchr(dest, ch);
3794 continue;
3795 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003796 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003797 if (!add_till_single_quote(dest, input))
3798 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003799 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003800 continue;
3801 }
3802 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003803 if (!add_till_double_quote(dest, input))
3804 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003805 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003806 continue;
3807 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003808 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003809 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3810 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003811 o_addchr(dest, ch);
3812 continue;
3813 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003814 if (ch == '\\') {
3815 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003816 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003817 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003818 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003819 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003820 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003821 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003822 continue;
3823 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003824 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003825 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003826}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003827#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003828
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003829/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003830#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003831#define parse_dollar(as_string, dest, input, quote_mask) \
3832 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003833#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003834#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003835static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003836 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003837 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003838{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003839 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003840
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003841 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003842 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003843 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003844 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003845 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003846 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003847 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003848 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003849 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003850 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003851 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003852 if (!isalnum(ch) && ch != '_')
3853 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003854 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003855 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003856 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003857 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003858 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003859 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003860 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003861 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003862 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003863 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003864 o_addchr(dest, ch | quote_mask);
3865 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003866 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003867 case '$': /* pid */
3868 case '!': /* last bg pid */
3869 case '?': /* last exit code */
3870 case '#': /* number of args */
3871 case '*': /* args */
3872 case '@': /* args */
3873 goto make_one_char_var;
3874 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003875 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3876
Denys Vlasenko74369502010-05-21 19:52:01 +02003877 ch = i_getch(input); /* eat '{' */
3878 nommu_addchr(as_string, ch);
3879
3880 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003881 /* It should be ${?}, or ${#var},
3882 * or even ${?+subst} - operator acting on a special variable,
3883 * or the beginning of variable name.
3884 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003885 if (ch == EOF
3886 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3887 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003888 bad_dollar_syntax:
3889 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003890 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3891 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02003892 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003893 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003894 ch |= quote_mask;
3895
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003896 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003897 * However, this regresses some of our testsuite cases
3898 * which check invalid constructs like ${%}.
3899 * Oh well... let's check that the var name part is fine... */
3900
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003901 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003902 unsigned pos;
3903
Denys Vlasenko74369502010-05-21 19:52:01 +02003904 o_addchr(dest, ch);
3905 debug_printf_parse(": '%c'\n", ch);
3906
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003907 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003908 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003909 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003910 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003911
Denys Vlasenko74369502010-05-21 19:52:01 +02003912 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003913 unsigned end_ch;
3914 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003915 /* handle parameter expansions
3916 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3917 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003918 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003919 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003920
3921 /* Eat everything until closing '}' (or ':') */
3922 end_ch = '}';
3923 if (ENABLE_HUSH_BASH_COMPAT
3924 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003925 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003926 ) {
3927 /* It's ${var:N[:M]} thing */
3928 end_ch = '}' * 0x100 + ':';
3929 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003930 if (ENABLE_HUSH_BASH_COMPAT
3931 && ch == '/'
3932 ) {
3933 /* It's ${var/[/]pattern[/repl]} thing */
3934 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3935 i_getch(input);
3936 nommu_addchr(as_string, '/');
3937 ch = '\\';
3938 }
3939 end_ch = '}' * 0x100 + '/';
3940 }
3941 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003942 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003943 if (!BB_MMU)
3944 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003945#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003946 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003947 if (last_ch == 0) /* error? */
3948 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003949#else
3950#error Simple code to only allow ${var} is not implemented
3951#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003952 if (as_string) {
3953 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003954 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003955 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003956
3957 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3958 /* close the first block: */
3959 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003960 /* while parsing N from ${var:N[:M]}
3961 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003962 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003963 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003964 end_ch = '}';
3965 goto again;
3966 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003967 /* got '}' */
3968 if (end_ch == '}' * 0x100 + ':') {
3969 /* it's ${var:N} - emulate :999999999 */
3970 o_addstr(dest, "999999999");
3971 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003972 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003973 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003974 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003975 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003976 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3977 break;
3978 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003979#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003980 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003981 unsigned pos;
3982
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003983 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003984 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003985# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003986 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003987 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003988 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003989 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3990 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003991 if (!BB_MMU)
3992 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003993 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
3994 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003995 if (as_string) {
3996 o_addstr(as_string, dest->data + pos);
3997 o_addchr(as_string, ')');
3998 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003999 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004000 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004001 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004002 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004003# endif
4004# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004005 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4006 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004007 if (!BB_MMU)
4008 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004009 if (!add_till_closing_bracket(dest, input, ')'))
4010 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004011 if (as_string) {
4012 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004013 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004014 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004015 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004016# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004017 break;
4018 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004019#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004020 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004021 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004022 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004023 ch = i_peek(input);
4024 if (isalnum(ch)) { /* it's $_name or $_123 */
4025 ch = '_';
4026 goto make_var;
4027 }
4028 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004029 /* TODO: $_ and $-: */
4030 /* $_ Shell or shell script name; or last argument of last command
4031 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4032 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004033 /* $- Option flags set by set builtin or shell options (-i etc) */
4034 default:
4035 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004036 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004037 debug_printf_parse("parse_dollar return 1 (ok)\n");
4038 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004039#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004040}
4041
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004042#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004043# if ENABLE_HUSH_BASH_COMPAT
4044#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4045 encode_string(dest, input, dquote_end, process_bkslash)
4046# else
4047/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4048#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4049 encode_string(dest, input, dquote_end)
4050# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004051#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004052
4053#else /* !MMU */
4054
4055# if ENABLE_HUSH_BASH_COMPAT
4056/* all parameters are needed, no macro tricks */
4057# else
4058#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4059 encode_string(as_string, dest, input, dquote_end)
4060# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004061#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004062static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004063 o_string *dest,
4064 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004065 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004066 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004067{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004068#if !ENABLE_HUSH_BASH_COMPAT
4069 const int process_bkslash = 1;
4070#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004071 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004072 int next;
4073
4074 again:
4075 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004076 if (ch != EOF)
4077 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004078 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004079 debug_printf_parse("encode_string return 1 (ok)\n");
4080 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004081 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004082 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004083 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004084 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004085 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004086 }
4087 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004088 if (ch != '\n') {
4089 next = i_peek(input);
4090 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004091 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004092 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004093 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004094 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004095 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004096 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004097 }
4098 /* bash:
4099 * "The backslash retains its special meaning [in "..."]
4100 * only when followed by one of the following characters:
4101 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004102 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004103 * NB: in (unquoted) heredoc, above does not apply to ",
4104 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004105 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004106 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004107 ch = i_getch(input); /* eat next */
4108 if (ch == '\n')
4109 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004110 } /* else: ch remains == '\\', and we double it below: */
4111 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004112 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004113 goto again;
4114 }
4115 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004116 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4117 debug_printf_parse("encode_string return 0: "
4118 "parse_dollar returned 0 (error)\n");
4119 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004120 }
4121 goto again;
4122 }
4123#if ENABLE_HUSH_TICK
4124 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004125 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004126 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4127 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004128 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4129 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004130 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4131 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004132 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004133 }
4134#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004135 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004136 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004137#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004138}
4139
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004140/*
4141 * Scan input until EOF or end_trigger char.
4142 * Return a list of pipes to execute, or NULL on EOF
4143 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004144 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004145 * reset parsing machinery and start parsing anew,
4146 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004147 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004148static struct pipe *parse_stream(char **pstring,
4149 struct in_str *input,
4150 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004151{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004152 struct parse_context ctx;
4153 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004154 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004155
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004156 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004157 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004158 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004159 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004160 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004161 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004162
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004163 /* If very first arg is "" or '', dest.data may end up NULL.
4164 * Preventing this: */
4165 o_addchr(&dest, '\0');
4166 dest.length = 0;
4167
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004168 /* We used to separate words on $IFS here. This was wrong.
4169 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004170 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004171 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004172
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004173 if (MAYBE_ASSIGNMENT != 0)
4174 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004175 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004176 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004177 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004178 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004179 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004180 int ch;
4181 int next;
4182 int redir_fd;
4183 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004184
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004185 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004186 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004187 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004188 if (ch == EOF) {
4189 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004190
4191 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004192 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004193 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004194 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004195 /* end_trigger == '}' case errors out earlier,
4196 * checking only ')' */
4197 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004198 syntax_error_unterm_ch('(');
4199 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004200 }
4201
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004202 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004203 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004204 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004205 o_free(&dest);
4206 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004207 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004208 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004209 /* (this makes bare "&" cmd a no-op.
4210 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004211 if (pi->num_cmds == 0
4212 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4213 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004214 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004215 pi = NULL;
4216 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004217#if !BB_MMU
4218 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4219 if (pstring)
4220 *pstring = ctx.as_string.data;
4221 else
4222 o_free_unsafe(&ctx.as_string);
4223#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004224 debug_leave();
4225 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004226 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004227 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004228 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004229
4230 next = '\0';
4231 if (ch != '\n')
4232 next = i_peek(input);
4233
4234 is_special = "{}<>;&|()#'" /* special outside of "str" */
4235 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4236 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004237 if (ctx.command->argv /* word [word]{... - non-special */
4238 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004239 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004240 || (next != ';' /* }; - special */
4241 && next != ')' /* }) - special */
4242 && next != '&' /* }& and }&& ... - special */
4243 && next != '|' /* }|| ... - special */
4244 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004245 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004246 ) {
4247 /* They are not special, skip "{}" */
4248 is_special += 2;
4249 }
4250 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004251 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004252
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004253 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004254 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004255 o_addQchr(&dest, ch);
4256 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4257 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004258 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004259 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004260 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004261 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004262 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004263 continue;
4264 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004265
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004266 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004267 if (done_word(&dest, &ctx)) {
4268 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004269 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004270 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004271 /* Is this a case when newline is simply ignored?
4272 * Some examples:
4273 * "cmd | <newline> cmd ..."
4274 * "case ... in <newline> word) ..."
4275 */
4276 if (IS_NULL_CMD(ctx.command)
4277 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004278 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004279 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004280 * Without check #1, interactive shell
4281 * ignores even bare <newline>,
4282 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004283 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004284 * ps2> _ <=== wrong, should be ps1
4285 * Without check #2, "cmd & <newline>"
4286 * is similarly mistreated.
4287 * (BTW, this makes "cmd & cmd"
4288 * and "cmd && cmd" non-orthogonal.
4289 * Really, ask yourself, why
4290 * "cmd && <newline>" doesn't start
4291 * cmd but waits for more input?
4292 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004293 */
4294 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004295 if (pi->num_cmds != 0 /* check #1 */
4296 && pi->followup != PIPE_BG /* check #2 */
4297 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004298 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004299 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004300 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004301 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004302 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004303 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4304 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004305 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004306 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004307 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004308 heredoc_cnt = 0;
4309 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004310 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004311 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004312 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004313 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004314 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004315 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004316
4317 /* "cmd}" or "cmd }..." without semicolon or &:
4318 * } is an ordinary char in this case, even inside { cmd; }
4319 * Pathological example: { ""}; } should exec "}" cmd
4320 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004321 if (ch == '}') {
4322 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4323 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004324 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004325 ) {
4326 goto ordinary_char;
4327 }
4328 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4329 goto skip_end_trigger;
4330 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004331 }
4332
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004333 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004334 && (ch != ';' || heredoc_cnt == 0)
4335#if ENABLE_HUSH_CASE
4336 && (ch != ')'
4337 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004338 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004339 )
4340#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004341 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004342 if (heredoc_cnt) {
4343 /* This is technically valid:
4344 * { cat <<HERE; }; echo Ok
4345 * heredoc
4346 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004347 * HERE
4348 * but we don't support this.
4349 * We require heredoc to be in enclosing {}/(),
4350 * if any.
4351 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004352 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004353 goto parse_error;
4354 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004355 if (done_word(&dest, &ctx)) {
4356 goto parse_error;
4357 }
4358 done_pipe(&ctx, PIPE_SEQ);
4359 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004360 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004361 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004362 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004363 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004364 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004365#if !BB_MMU
4366 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4367 if (pstring)
4368 *pstring = ctx.as_string.data;
4369 else
4370 o_free_unsafe(&ctx.as_string);
4371#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004372 debug_leave();
4373 debug_printf_parse("parse_stream return %p: "
4374 "end_trigger char found\n",
4375 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004376 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004377 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004378 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004379 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004380 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004381 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004382
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004383 /* Catch <, > before deciding whether this word is
4384 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4385 switch (ch) {
4386 case '>':
4387 redir_fd = redirect_opt_num(&dest);
4388 if (done_word(&dest, &ctx)) {
4389 goto parse_error;
4390 }
4391 redir_style = REDIRECT_OVERWRITE;
4392 if (next == '>') {
4393 redir_style = REDIRECT_APPEND;
4394 ch = i_getch(input);
4395 nommu_addchr(&ctx.as_string, ch);
4396 }
4397#if 0
4398 else if (next == '(') {
4399 syntax_error(">(process) not supported");
4400 goto parse_error;
4401 }
4402#endif
4403 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4404 goto parse_error;
4405 continue; /* back to top of while (1) */
4406 case '<':
4407 redir_fd = redirect_opt_num(&dest);
4408 if (done_word(&dest, &ctx)) {
4409 goto parse_error;
4410 }
4411 redir_style = REDIRECT_INPUT;
4412 if (next == '<') {
4413 redir_style = REDIRECT_HEREDOC;
4414 heredoc_cnt++;
4415 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4416 ch = i_getch(input);
4417 nommu_addchr(&ctx.as_string, ch);
4418 } else if (next == '>') {
4419 redir_style = REDIRECT_IO;
4420 ch = i_getch(input);
4421 nommu_addchr(&ctx.as_string, ch);
4422 }
4423#if 0
4424 else if (next == '(') {
4425 syntax_error("<(process) not supported");
4426 goto parse_error;
4427 }
4428#endif
4429 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4430 goto parse_error;
4431 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004432 case '#':
4433 if (dest.length == 0 && !dest.has_quoted_part) {
4434 /* skip "#comment" */
4435 while (1) {
4436 ch = i_peek(input);
4437 if (ch == EOF || ch == '\n')
4438 break;
4439 i_getch(input);
4440 /* note: we do not add it to &ctx.as_string */
4441 }
4442 nommu_addchr(&ctx.as_string, '\n');
4443 continue; /* back to top of while (1) */
4444 }
4445 break;
4446 case '\\':
4447 if (next == '\n') {
4448 /* It's "\<newline>" */
4449#if !BB_MMU
4450 /* Remove trailing '\' from ctx.as_string */
4451 ctx.as_string.data[--ctx.as_string.length] = '\0';
4452#endif
4453 ch = i_getch(input); /* eat it */
4454 continue; /* back to top of while (1) */
4455 }
4456 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004457 }
4458
4459 if (dest.o_assignment == MAYBE_ASSIGNMENT
4460 /* check that we are not in word in "a=1 2>word b=1": */
4461 && !ctx.pending_redirect
4462 ) {
4463 /* ch is a special char and thus this word
4464 * cannot be an assignment */
4465 dest.o_assignment = NOT_ASSIGNMENT;
4466 }
4467
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004468 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4469
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004470 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004471 case '#': /* non-comment #: "echo a#b" etc */
4472 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004473 break;
4474 case '\\':
4475 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004476 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004477 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004478 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004479 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004480 /* note: ch != '\n' (that case does not reach this place) */
4481 o_addchr(&dest, '\\');
4482 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4483 o_addchr(&dest, ch);
4484 nommu_addchr(&ctx.as_string, ch);
4485 /* Example: echo Hello \2>file
4486 * we need to know that word 2 is quoted */
4487 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004488 break;
4489 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004490 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004491 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004492 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004493 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004494 }
Eric Andersen25f27032001-04-26 23:22:31 +00004495 break;
4496 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004497 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004498 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004499 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004500 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004501 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004502 goto parse_error;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004503 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004504 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004505 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004506 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004507 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004508 }
Eric Andersen25f27032001-04-26 23:22:31 +00004509 break;
4510 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004511 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004512 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004513 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004514 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004515 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004516 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004517 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004518#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004519 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004520 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004521
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004522 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4523 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004524 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004525 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4526 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004527# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004528 o_addstr(&ctx.as_string, dest.data + pos);
4529 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004530# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004531 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4532 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004533 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004534 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004535#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004536 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004537#if ENABLE_HUSH_CASE
4538 case_semi:
4539#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004540 if (done_word(&dest, &ctx)) {
4541 goto parse_error;
4542 }
4543 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004544#if ENABLE_HUSH_CASE
4545 /* Eat multiple semicolons, detect
4546 * whether it means something special */
4547 while (1) {
4548 ch = i_peek(input);
4549 if (ch != ';')
4550 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004551 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004552 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004553 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004554 ctx.ctx_dsemicolon = 1;
4555 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004556 break;
4557 }
4558 }
4559#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004560 new_cmd:
4561 /* We just finished a cmd. New one may start
4562 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004563 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004564 break;
4565 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004566 if (done_word(&dest, &ctx)) {
4567 goto parse_error;
4568 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004569 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004570 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004571 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004572 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004573 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004574 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004575 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004576 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004577 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004578 if (done_word(&dest, &ctx)) {
4579 goto parse_error;
4580 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004581#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004582 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004583 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004584#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004585 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004586 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004587 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004588 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004589 } else {
4590 /* we could pick up a file descriptor choice here
4591 * with redirect_opt_num(), but bash doesn't do it.
4592 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004593 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004594#if !BB_MMU
4595 o_reset_to_empty_unquoted(&ctx.as_string);
4596#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004597 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004598 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004599 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004600#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004601 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004602 if (ctx.ctx_res_w == RES_MATCH
4603 && ctx.command->argv == NULL /* not (word|(... */
4604 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004605 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004606 ) {
4607 continue;
4608 }
4609#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004610 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004611 if (parse_group(&dest, &ctx, input, ch) != 0) {
4612 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004613 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004614 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004615 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004616#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004617 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004618 goto case_semi;
4619#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004620 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004621 /* proper use of this character is caught by end_trigger:
4622 * if we see {, we call parse_group(..., end_trigger='}')
4623 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004624 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004625 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004626 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004627 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004628 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004629 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004630 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004631
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004632 parse_error:
4633 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004634 struct parse_context *pctx;
4635 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004636
4637 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004638 * Sample for finding leaks on syntax error recovery path.
4639 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004640 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004641 * Samples to catch leaks at execution:
4642 * while if (true | {true;}); then echo ok; fi; do break; done
4643 * 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 +00004644 */
4645 pctx = &ctx;
4646 do {
4647 /* Update pipe/command counts,
4648 * otherwise freeing may miss some */
4649 done_pipe(pctx, PIPE_SEQ);
4650 debug_printf_clean("freeing list %p from ctx %p\n",
4651 pctx->list_head, pctx);
4652 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004653 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004654 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004655#if !BB_MMU
4656 o_free_unsafe(&pctx->as_string);
4657#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004658 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004659 if (pctx != &ctx) {
4660 free(pctx);
4661 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004662 IF_HAS_KEYWORDS(pctx = p2;)
4663 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004664
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004665 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004666 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004667#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004668 if (pstring)
4669 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004670#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004671 debug_leave();
4672 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004673 }
Eric Andersen25f27032001-04-26 23:22:31 +00004674}
4675
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004676
4677/*** Execution routines ***/
4678
4679/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004680#if !ENABLE_HUSH_BASH_COMPAT
4681/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4682#define expand_string_to_string(str, do_unbackslash) \
4683 expand_string_to_string(str)
4684#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004685static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004686#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004687static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004688#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004689
4690/* expand_strvec_to_strvec() takes a list of strings, expands
4691 * all variable references within and returns a pointer to
4692 * a list of expanded strings, possibly with larger number
4693 * of strings. (Think VAR="a b"; echo $VAR).
4694 * This new list is allocated as a single malloc block.
4695 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004696 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004697 * Caller can deallocate entire list by single free(list). */
4698
Denys Vlasenko238081f2010-10-03 14:26:26 +02004699/* A horde of its helpers come first: */
4700
4701static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4702{
4703 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004704 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004705
Denys Vlasenko9e800222010-10-03 14:28:04 +02004706#if ENABLE_HUSH_BRACE_EXPANSION
4707 if (c == '{' || c == '}') {
4708 /* { -> \{, } -> \} */
4709 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004710 /* And now we want to add { or } and continue:
4711 * o_addchr(o, c);
4712 * continue;
4713 * luckily, just falling throught achieves this.
4714 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004715 }
4716#endif
4717 o_addchr(o, c);
4718 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004719 /* \z -> \\\z; \<eol> -> \\<eol> */
4720 o_addchr(o, '\\');
4721 if (len) {
4722 len--;
4723 o_addchr(o, '\\');
4724 o_addchr(o, *str++);
4725 }
4726 }
4727 }
4728}
4729
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004730/* Store given string, finalizing the word and starting new one whenever
4731 * we encounter IFS char(s). This is used for expanding variable values.
4732 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4733static int expand_on_ifs(o_string *output, int n, const char *str)
4734{
4735 while (1) {
4736 int word_len = strcspn(str, G.ifs);
4737 if (word_len) {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004738 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004739 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004740 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004741 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004742 * Example: "v='\*'; echo b$v" prints "b\*"
4743 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004744 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004745 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004746 /*/ Why can't we do it easier? */
4747 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4748 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4749 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004750 str += word_len;
4751 }
4752 if (!*str) /* EOL - do not finalize word */
4753 break;
4754 o_addchr(output, '\0');
4755 debug_print_list("expand_on_ifs", output, n);
4756 n = o_save_ptr(output, n);
4757 str += strspn(str, G.ifs); /* skip ifs chars */
4758 }
4759 debug_print_list("expand_on_ifs[1]", output, n);
4760 return n;
4761}
4762
4763/* Helper to expand $((...)) and heredoc body. These act as if
4764 * they are in double quotes, with the exception that they are not :).
4765 * Just the rules are similar: "expand only $var and `cmd`"
4766 *
4767 * Returns malloced string.
4768 * As an optimization, we return NULL if expansion is not needed.
4769 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004770#if !ENABLE_HUSH_BASH_COMPAT
4771/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4772#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4773 encode_then_expand_string(str)
4774#endif
4775static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004776{
4777 char *exp_str;
4778 struct in_str input;
4779 o_string dest = NULL_O_STRING;
4780
4781 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004782 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004783#if ENABLE_HUSH_TICK
4784 && !strchr(str, '`')
4785#endif
4786 ) {
4787 return NULL;
4788 }
4789
4790 /* We need to expand. Example:
4791 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4792 */
4793 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004794 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004795//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004796 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004797 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004798 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4799 o_free_unsafe(&dest);
4800 return exp_str;
4801}
4802
4803#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004804static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004805{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004806 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004807 arith_t res;
4808 char *exp_str;
4809
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004810 math_state.lookupvar = get_local_var_value;
4811 math_state.setvar = set_local_var_from_halves;
4812 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004813 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004814 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004815 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004816 if (errmsg_p)
4817 *errmsg_p = math_state.errmsg;
4818 if (math_state.errmsg)
4819 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004820 return res;
4821}
4822#endif
4823
4824#if ENABLE_HUSH_BASH_COMPAT
4825/* ${var/[/]pattern[/repl]} helpers */
4826static char *strstr_pattern(char *val, const char *pattern, int *size)
4827{
4828 while (1) {
4829 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4830 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4831 if (end) {
4832 *size = end - val;
4833 return val;
4834 }
4835 if (*val == '\0')
4836 return NULL;
4837 /* Optimization: if "*pat" did not match the start of "string",
4838 * we know that "tring", "ring" etc will not match too:
4839 */
4840 if (pattern[0] == '*')
4841 return NULL;
4842 val++;
4843 }
4844}
4845static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4846{
4847 char *result = NULL;
4848 unsigned res_len = 0;
4849 unsigned repl_len = strlen(repl);
4850
4851 while (1) {
4852 int size;
4853 char *s = strstr_pattern(val, pattern, &size);
4854 if (!s)
4855 break;
4856
4857 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4858 memcpy(result + res_len, val, s - val);
4859 res_len += s - val;
4860 strcpy(result + res_len, repl);
4861 res_len += repl_len;
4862 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4863
4864 val = s + size;
4865 if (exp_op == '/')
4866 break;
4867 }
4868 if (val[0] && result) {
4869 result = xrealloc(result, res_len + strlen(val) + 1);
4870 strcpy(result + res_len, val);
4871 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4872 }
4873 debug_printf_varexp("result:'%s'\n", result);
4874 return result;
4875}
4876#endif
4877
4878/* Helper:
4879 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4880 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004881static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004882{
4883 const char *val = NULL;
4884 char *to_be_freed = NULL;
4885 char *p = *pp;
4886 char *var;
4887 char first_char;
4888 char exp_op;
4889 char exp_save = exp_save; /* for compiler */
4890 char *exp_saveptr; /* points to expansion operator */
4891 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004892 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004893
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004894 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004895 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004896 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004897 arg0 = arg[0];
4898 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004899 exp_op = 0;
4900
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004901 if (first_char == '#' /* ${#... */
4902 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4903 ) {
4904 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004905 var++;
4906 exp_op = 'L';
4907 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004908 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004909 if (exp_saveptr /* if 2nd char is one of expansion operators */
4910 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4911 ) {
4912 /* ${?:0}, ${#[:]%0} etc */
4913 exp_saveptr = var + 1;
4914 } else {
4915 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4916 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4917 }
4918 exp_op = exp_save = *exp_saveptr;
4919 if (exp_op) {
4920 exp_word = exp_saveptr + 1;
4921 if (exp_op == ':') {
4922 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004923//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004924 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004925 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004926 ) {
4927 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4928 exp_op = ':';
4929 exp_word--;
4930 }
4931 }
4932 *exp_saveptr = '\0';
4933 } /* else: it's not an expansion op, but bare ${var} */
4934 }
4935
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004936 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004937 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004938 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004939 int n = xatoi_positive(var);
4940 if (n < G.global_argc)
4941 val = G.global_argv[n];
4942 /* else val remains NULL: $N with too big N */
4943 } else {
4944 switch (var[0]) {
4945 case '$': /* pid */
4946 val = utoa(G.root_pid);
4947 break;
4948 case '!': /* bg pid */
4949 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4950 break;
4951 case '?': /* exitcode */
4952 val = utoa(G.last_exitcode);
4953 break;
4954 case '#': /* argc */
4955 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4956 break;
4957 default:
4958 val = get_local_var_value(var);
4959 }
4960 }
4961
4962 /* Handle any expansions */
4963 if (exp_op == 'L') {
4964 debug_printf_expand("expand: length(%s)=", val);
4965 val = utoa(val ? strlen(val) : 0);
4966 debug_printf_expand("%s\n", val);
4967 } else if (exp_op) {
4968 if (exp_op == '%' || exp_op == '#') {
4969 /* Standard-mandated substring removal ops:
4970 * ${parameter%word} - remove smallest suffix pattern
4971 * ${parameter%%word} - remove largest suffix pattern
4972 * ${parameter#word} - remove smallest prefix pattern
4973 * ${parameter##word} - remove largest prefix pattern
4974 *
4975 * Word is expanded to produce a glob pattern.
4976 * Then var's value is matched to it and matching part removed.
4977 */
4978 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004979 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004980 char *exp_exp_word;
4981 char *loc;
4982 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02004983 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004984 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004985 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004986 if (exp_exp_word)
4987 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02004988 /* HACK ALERT. We depend here on the fact that
4989 * G.global_argv and results of utoa and get_local_var_value
4990 * are actually in writable memory:
4991 * scan_and_match momentarily stores NULs there. */
4992 t = (char*)val;
4993 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004994 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02004995 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004996 free(exp_exp_word);
4997 if (loc) { /* match was found */
4998 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004999 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005000 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005001 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005002 }
5003 }
5004 }
5005#if ENABLE_HUSH_BASH_COMPAT
5006 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005007 /* It's ${var/[/]pattern[/repl]} thing.
5008 * Note that in encoded form it has TWO parts:
5009 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005010 * and if // is used, it is encoded as \:
5011 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005012 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005013 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005014 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005015 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005016 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005017 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005018 * by the usual expansion rules:
5019 * >az; >bz;
5020 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5021 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5022 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5023 * v='a bz'; echo ${v/a*z/\z} prints "z"
5024 * (note that a*z _pattern_ is never globbed!)
5025 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005026 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005027 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005028 if (!pattern)
5029 pattern = xstrdup(exp_word);
5030 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5031 *p++ = SPECIAL_VAR_SYMBOL;
5032 exp_word = p;
5033 p = strchr(p, SPECIAL_VAR_SYMBOL);
5034 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005035 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005036 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5037 /* HACK ALERT. We depend here on the fact that
5038 * G.global_argv and results of utoa and get_local_var_value
5039 * are actually in writable memory:
5040 * replace_pattern momentarily stores NULs there. */
5041 t = (char*)val;
5042 to_be_freed = replace_pattern(t,
5043 pattern,
5044 (repl ? repl : exp_word),
5045 exp_op);
5046 if (to_be_freed) /* at least one replace happened */
5047 val = to_be_freed;
5048 free(pattern);
5049 free(repl);
5050 }
5051 }
5052#endif
5053 else if (exp_op == ':') {
5054#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5055 /* It's ${var:N[:M]} bashism.
5056 * Note that in encoded form it has TWO parts:
5057 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5058 */
5059 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005060 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005061
Denys Vlasenko063847d2010-09-15 13:33:02 +02005062 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5063 if (errmsg)
5064 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005065 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5066 *p++ = SPECIAL_VAR_SYMBOL;
5067 exp_word = p;
5068 p = strchr(p, SPECIAL_VAR_SYMBOL);
5069 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005070 len = expand_and_evaluate_arith(exp_word, &errmsg);
5071 if (errmsg)
5072 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005073 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005074 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005075 if (beg < 0) /* bash compat */
5076 beg = 0;
5077 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005078 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005079 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005080 val = NULL;
5081 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005082 /* Paranoia. What if user entered 9999999999999
5083 * which fits in arith_t but not int? */
5084 if (len >= INT_MAX)
5085 len = INT_MAX;
5086 val = to_be_freed = xstrndup(val + beg, len);
5087 }
5088 debug_printf_varexp("val:'%s'\n", val);
5089 } else
5090#endif
5091 {
5092 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005093 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005094 }
5095 } else { /* one of "-=+?" */
5096 /* Standard-mandated substitution ops:
5097 * ${var?word} - indicate error if unset
5098 * If var is unset, word (or a message indicating it is unset
5099 * if word is null) is written to standard error
5100 * and the shell exits with a non-zero exit status.
5101 * Otherwise, the value of var is substituted.
5102 * ${var-word} - use default value
5103 * If var is unset, word is substituted.
5104 * ${var=word} - assign and use default value
5105 * If var is unset, word is assigned to var.
5106 * In all cases, final value of var is substituted.
5107 * ${var+word} - use alternative value
5108 * If var is unset, null is substituted.
5109 * Otherwise, word is substituted.
5110 *
5111 * Word is subjected to tilde expansion, parameter expansion,
5112 * command substitution, and arithmetic expansion.
5113 * If word is not needed, it is not expanded.
5114 *
5115 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5116 * but also treat null var as if it is unset.
5117 */
5118 int use_word = (!val || ((exp_save == ':') && !val[0]));
5119 if (exp_op == '+')
5120 use_word = !use_word;
5121 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5122 (exp_save == ':') ? "true" : "false", use_word);
5123 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005124 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005125 if (to_be_freed)
5126 exp_word = to_be_freed;
5127 if (exp_op == '?') {
5128 /* mimic bash message */
5129 die_if_script("%s: %s",
5130 var,
5131 exp_word[0] ? exp_word : "parameter null or not set"
5132 );
5133//TODO: how interactive bash aborts expansion mid-command?
5134 } else {
5135 val = exp_word;
5136 }
5137
5138 if (exp_op == '=') {
5139 /* ${var=[word]} or ${var:=[word]} */
5140 if (isdigit(var[0]) || var[0] == '#') {
5141 /* mimic bash message */
5142 die_if_script("$%s: cannot assign in this way", var);
5143 val = NULL;
5144 } else {
5145 char *new_var = xasprintf("%s=%s", var, val);
5146 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5147 }
5148 }
5149 }
5150 } /* one of "-=+?" */
5151
5152 *exp_saveptr = exp_save;
5153 } /* if (exp_op) */
5154
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005155 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005156
5157 *pp = p;
5158 *to_be_freed_pp = to_be_freed;
5159 return val;
5160}
5161
5162/* Expand all variable references in given string, adding words to list[]
5163 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5164 * to be filled). This routine is extremely tricky: has to deal with
5165 * variables/parameters with whitespace, $* and $@, and constructs like
5166 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005167static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005168{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005169 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005170 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005171 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005172 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005173 char *p;
5174
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005175 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5176 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005177 debug_print_list("expand_vars_to_list", output, n);
5178 n = o_save_ptr(output, n);
5179 debug_print_list("expand_vars_to_list[0]", output, n);
5180
5181 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5182 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005183 char *to_be_freed = NULL;
5184 const char *val = NULL;
5185#if ENABLE_HUSH_TICK
5186 o_string subst_result = NULL_O_STRING;
5187#endif
5188#if ENABLE_SH_MATH_SUPPORT
5189 char arith_buf[sizeof(arith_t)*3 + 2];
5190#endif
5191 o_addblock(output, arg, p - arg);
5192 debug_print_list("expand_vars_to_list[1]", output, n);
5193 arg = ++p;
5194 p = strchr(p, SPECIAL_VAR_SYMBOL);
5195
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005196 /* Fetch special var name (if it is indeed one of them)
5197 * and quote bit, force the bit on if singleword expansion -
5198 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005199 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005200
5201 /* Is this variable quoted and thus expansion can't be null?
5202 * "$@" is special. Even if quoted, it can still
5203 * expand to nothing (not even an empty string),
5204 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005205 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005206 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005207
5208 switch (first_ch & 0x7f) {
5209 /* Highest bit in first_ch indicates that var is double-quoted */
5210 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005211 case '@': {
5212 int i;
5213 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005214 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005215 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005216 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005217 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005218 while (G.global_argv[i]) {
5219 n = expand_on_ifs(output, n, G.global_argv[i]);
5220 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5221 if (G.global_argv[i++][0] && G.global_argv[i]) {
5222 /* this argv[] is not empty and not last:
5223 * put terminating NUL, start new word */
5224 o_addchr(output, '\0');
5225 debug_print_list("expand_vars_to_list[2]", output, n);
5226 n = o_save_ptr(output, n);
5227 debug_print_list("expand_vars_to_list[3]", output, n);
5228 }
5229 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005230 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005231 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005232 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005233 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005234 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005235 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005236 while (1) {
5237 o_addQstr(output, G.global_argv[i]);
5238 if (++i >= G.global_argc)
5239 break;
5240 o_addchr(output, '\0');
5241 debug_print_list("expand_vars_to_list[4]", output, n);
5242 n = o_save_ptr(output, n);
5243 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005244 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005245 while (1) {
5246 o_addQstr(output, G.global_argv[i]);
5247 if (!G.global_argv[++i])
5248 break;
5249 if (G.ifs[0])
5250 o_addchr(output, G.ifs[0]);
5251 }
5252 }
5253 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005254 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005255 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5256 /* "Empty variable", used to make "" etc to not disappear */
5257 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005258 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005259 break;
5260#if ENABLE_HUSH_TICK
5261 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005262 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005263 arg++;
5264 /* Can't just stuff it into output o_string,
5265 * expanded result may need to be globbed
5266 * and $IFS-splitted */
5267 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5268 G.last_exitcode = process_command_subs(&subst_result, arg);
5269 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5270 val = subst_result.data;
5271 goto store_val;
5272#endif
5273#if ENABLE_SH_MATH_SUPPORT
5274 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5275 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005276
5277 arg++; /* skip '+' */
5278 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5279 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005280 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005281 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5282 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005283 val = arith_buf;
5284 break;
5285 }
5286#endif
5287 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005288 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005289 IF_HUSH_TICK(store_val:)
5290 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005291 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5292 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005293 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005294 n = expand_on_ifs(output, n, val);
5295 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005296 }
5297 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005298 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5299 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005300 }
5301 break;
5302
5303 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5304
5305 if (val && val[0]) {
5306 o_addQstr(output, val);
5307 }
5308 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005309
5310 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5311 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005312 if (*p != SPECIAL_VAR_SYMBOL)
5313 *p = SPECIAL_VAR_SYMBOL;
5314
5315#if ENABLE_HUSH_TICK
5316 o_free(&subst_result);
5317#endif
5318 arg = ++p;
5319 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5320
5321 if (arg[0]) {
5322 debug_print_list("expand_vars_to_list[a]", output, n);
5323 /* this part is literal, and it was already pre-quoted
5324 * if needed (much earlier), do not use o_addQstr here! */
5325 o_addstr_with_NUL(output, arg);
5326 debug_print_list("expand_vars_to_list[b]", output, n);
5327 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005328 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005329 ) {
5330 n--;
5331 /* allow to reuse list[n] later without re-growth */
5332 output->has_empty_slot = 1;
5333 } else {
5334 o_addchr(output, '\0');
5335 }
5336
5337 return n;
5338}
5339
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005340static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005341{
5342 int n;
5343 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005344 o_string output = NULL_O_STRING;
5345
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005346 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005347
5348 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005349 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005350 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005351 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005352 }
5353 debug_print_list("expand_variables", &output, n);
5354
5355 /* output.data (malloced in one block) gets returned in "list" */
5356 list = o_finalize_list(&output, n);
5357 debug_print_strings("expand_variables[1]", list);
5358 return list;
5359}
5360
5361static char **expand_strvec_to_strvec(char **argv)
5362{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005363 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005364}
5365
5366#if ENABLE_HUSH_BASH_COMPAT
5367static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5368{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005369 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005370}
5371#endif
5372
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005373/* Used for expansion of right hand of assignments,
5374 * $((...)), heredocs, variable espansion parts.
5375 *
5376 * NB: should NOT do globbing!
5377 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5378 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005379static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005380{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005381#if !ENABLE_HUSH_BASH_COMPAT
5382 const int do_unbackslash = 1;
5383#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005384 char *argv[2], **list;
5385
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005386 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005387 /* This is generally an optimization, but it also
5388 * handles "", which otherwise trips over !list[0] check below.
5389 * (is this ever happens that we actually get str="" here?)
5390 */
5391 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5392 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005393 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005394 return xstrdup(str);
5395 }
5396
5397 argv[0] = (char*)str;
5398 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005399 list = expand_variables(argv, do_unbackslash
5400 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5401 : EXP_FLAG_SINGLEWORD
5402 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005403 if (HUSH_DEBUG)
5404 if (!list[0] || list[1])
5405 bb_error_msg_and_die("BUG in varexp2");
5406 /* actually, just move string 2*sizeof(char*) bytes back */
5407 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005408 if (do_unbackslash)
5409 unbackslash((char*)list);
5410 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005411 return (char*)list;
5412}
5413
5414/* Used for "eval" builtin */
5415static char* expand_strvec_to_string(char **argv)
5416{
5417 char **list;
5418
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005419 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005420 /* Convert all NULs to spaces */
5421 if (list[0]) {
5422 int n = 1;
5423 while (list[n]) {
5424 if (HUSH_DEBUG)
5425 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5426 bb_error_msg_and_die("BUG in varexp3");
5427 /* bash uses ' ' regardless of $IFS contents */
5428 list[n][-1] = ' ';
5429 n++;
5430 }
5431 }
5432 overlapping_strcpy((char*)list, list[0]);
5433 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5434 return (char*)list;
5435}
5436
5437static char **expand_assignments(char **argv, int count)
5438{
5439 int i;
5440 char **p;
5441
5442 G.expanded_assignments = p = NULL;
5443 /* Expand assignments into one string each */
5444 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005445 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005446 }
5447 G.expanded_assignments = NULL;
5448 return p;
5449}
5450
5451
5452#if BB_MMU
5453/* never called */
5454void re_execute_shell(char ***to_free, const char *s,
5455 char *g_argv0, char **g_argv,
5456 char **builtin_argv) NORETURN;
5457
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005458static void switch_off_special_sigs(unsigned mask)
5459{
5460 unsigned sig = 0;
5461 while ((mask >>= 1) != 0) {
5462 sig++;
5463 if (!(mask & 1))
5464 continue;
5465 if (G.traps) {
5466 if (G.traps[sig] && !G.traps[sig][0])
5467 /* trap is '', has to remain SIG_IGN */
5468 continue;
5469 free(G.traps[sig]);
5470 G.traps[sig] = NULL;
5471 }
5472 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005473 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005474 }
5475}
5476
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005477static void reset_traps_to_defaults(void)
5478{
5479 /* This function is always called in a child shell
5480 * after fork (not vfork, NOMMU doesn't use this function).
5481 */
5482 unsigned sig;
5483 unsigned mask;
5484
5485 /* Child shells are not interactive.
5486 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5487 * Testcase: (while :; do :; done) + ^Z should background.
5488 * Same goes for SIGTERM, SIGHUP, SIGINT.
5489 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005490 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5491 if (!G.traps && !mask)
5492 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005493
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005494 /* Switch off special sigs */
5495 switch_off_special_sigs(mask);
5496#if ENABLE_HUSH_JOB
5497 G_fatal_sig_mask = 0;
5498#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005499 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005500 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5501 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005502
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005503 if (!G.traps)
5504 return;
5505
5506 /* Reset all sigs to default except ones with empty traps */
5507 for (sig = 0; sig < NSIG; sig++) {
5508 if (!G.traps[sig])
5509 continue; /* no trap: nothing to do */
5510 if (!G.traps[sig][0])
5511 continue; /* empty trap: has to remain SIG_IGN */
5512 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005513 free(G.traps[sig]);
5514 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005515 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005516 if (sig == 0)
5517 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005518 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005519 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005520}
5521
5522#else /* !BB_MMU */
5523
5524static void re_execute_shell(char ***to_free, const char *s,
5525 char *g_argv0, char **g_argv,
5526 char **builtin_argv) NORETURN;
5527static void re_execute_shell(char ***to_free, const char *s,
5528 char *g_argv0, char **g_argv,
5529 char **builtin_argv)
5530{
5531# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5532 /* delims + 2 * (number of bytes in printed hex numbers) */
5533 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5534 char *heredoc_argv[4];
5535 struct variable *cur;
5536# if ENABLE_HUSH_FUNCTIONS
5537 struct function *funcp;
5538# endif
5539 char **argv, **pp;
5540 unsigned cnt;
5541 unsigned long long empty_trap_mask;
5542
5543 if (!g_argv0) { /* heredoc */
5544 argv = heredoc_argv;
5545 argv[0] = (char *) G.argv0_for_re_execing;
5546 argv[1] = (char *) "-<";
5547 argv[2] = (char *) s;
5548 argv[3] = NULL;
5549 pp = &argv[3]; /* used as pointer to empty environment */
5550 goto do_exec;
5551 }
5552
5553 cnt = 0;
5554 pp = builtin_argv;
5555 if (pp) while (*pp++)
5556 cnt++;
5557
5558 empty_trap_mask = 0;
5559 if (G.traps) {
5560 int sig;
5561 for (sig = 1; sig < NSIG; sig++) {
5562 if (G.traps[sig] && !G.traps[sig][0])
5563 empty_trap_mask |= 1LL << sig;
5564 }
5565 }
5566
5567 sprintf(param_buf, NOMMU_HACK_FMT
5568 , (unsigned) G.root_pid
5569 , (unsigned) G.root_ppid
5570 , (unsigned) G.last_bg_pid
5571 , (unsigned) G.last_exitcode
5572 , cnt
5573 , empty_trap_mask
5574 IF_HUSH_LOOPS(, G.depth_of_loop)
5575 );
5576# undef NOMMU_HACK_FMT
5577 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5578 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5579 */
5580 cnt += 6;
5581 for (cur = G.top_var; cur; cur = cur->next) {
5582 if (!cur->flg_export || cur->flg_read_only)
5583 cnt += 2;
5584 }
5585# if ENABLE_HUSH_FUNCTIONS
5586 for (funcp = G.top_func; funcp; funcp = funcp->next)
5587 cnt += 3;
5588# endif
5589 pp = g_argv;
5590 while (*pp++)
5591 cnt++;
5592 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5593 *pp++ = (char *) G.argv0_for_re_execing;
5594 *pp++ = param_buf;
5595 for (cur = G.top_var; cur; cur = cur->next) {
5596 if (strcmp(cur->varstr, hush_version_str) == 0)
5597 continue;
5598 if (cur->flg_read_only) {
5599 *pp++ = (char *) "-R";
5600 *pp++ = cur->varstr;
5601 } else if (!cur->flg_export) {
5602 *pp++ = (char *) "-V";
5603 *pp++ = cur->varstr;
5604 }
5605 }
5606# if ENABLE_HUSH_FUNCTIONS
5607 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5608 *pp++ = (char *) "-F";
5609 *pp++ = funcp->name;
5610 *pp++ = funcp->body_as_string;
5611 }
5612# endif
5613 /* We can pass activated traps here. Say, -Tnn:trap_string
5614 *
5615 * However, POSIX says that subshells reset signals with traps
5616 * to SIG_DFL.
5617 * I tested bash-3.2 and it not only does that with true subshells
5618 * of the form ( list ), but with any forked children shells.
5619 * I set trap "echo W" WINCH; and then tried:
5620 *
5621 * { echo 1; sleep 20; echo 2; } &
5622 * while true; do echo 1; sleep 20; echo 2; break; done &
5623 * true | { echo 1; sleep 20; echo 2; } | cat
5624 *
5625 * In all these cases sending SIGWINCH to the child shell
5626 * did not run the trap. If I add trap "echo V" WINCH;
5627 * _inside_ group (just before echo 1), it works.
5628 *
5629 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005630 */
5631 *pp++ = (char *) "-c";
5632 *pp++ = (char *) s;
5633 if (builtin_argv) {
5634 while (*++builtin_argv)
5635 *pp++ = *builtin_argv;
5636 *pp++ = (char *) "";
5637 }
5638 *pp++ = g_argv0;
5639 while (*g_argv)
5640 *pp++ = *g_argv++;
5641 /* *pp = NULL; - is already there */
5642 pp = environ;
5643
5644 do_exec:
5645 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02005646 /* Don't propagate SIG_IGN to the child */
5647 if (SPECIAL_JOBSTOP_SIGS != 0)
5648 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005649 execve(bb_busybox_exec_path, argv, pp);
5650 /* Fallback. Useful for init=/bin/hush usage etc */
5651 if (argv[0][0] == '/')
5652 execve(argv[0], argv, pp);
5653 xfunc_error_retval = 127;
5654 bb_error_msg_and_die("can't re-execute the shell");
5655}
5656#endif /* !BB_MMU */
5657
5658
5659static int run_and_free_list(struct pipe *pi);
5660
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005661/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005662 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5663 * end_trigger controls how often we stop parsing
5664 * NUL: parse all, execute, return
5665 * ';': parse till ';' or newline, execute, repeat till EOF
5666 */
5667static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005668{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005669 /* Why we need empty flag?
5670 * An obscure corner case "false; ``; echo $?":
5671 * empty command in `` should still set $? to 0.
5672 * But we can't just set $? to 0 at the start,
5673 * this breaks "false; echo `echo $?`" case.
5674 */
5675 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005676 while (1) {
5677 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005678
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005679#if ENABLE_HUSH_INTERACTIVE
5680 if (end_trigger == ';')
5681 inp->promptmode = 0; /* PS1 */
5682#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005683 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005684 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5685 /* If we are in "big" script
5686 * (not in `cmd` or something similar)...
5687 */
5688 if (pipe_list == ERR_PTR && end_trigger == ';') {
5689 /* Discard cached input (rest of line) */
5690 int ch = inp->last_char;
5691 while (ch != EOF && ch != '\n') {
5692 //bb_error_msg("Discarded:'%c'", ch);
5693 ch = i_getch(inp);
5694 }
5695 /* Force prompt */
5696 inp->p = NULL;
5697 /* This stream isn't empty */
5698 empty = 0;
5699 continue;
5700 }
5701 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01005702 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005703 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005704 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005705 debug_print_tree(pipe_list, 0);
5706 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5707 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005708 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005709#if ENABLE_HUSH_FUNCTIONS
5710 if (G.flag_return_in_progress == 1)
5711 break;
5712#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005713 }
Eric Andersen25f27032001-04-26 23:22:31 +00005714}
5715
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005716static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005717{
5718 struct in_str input;
5719 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005720 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005721}
5722
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005723static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005724{
Eric Andersen25f27032001-04-26 23:22:31 +00005725 struct in_str input;
5726 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005727 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005728}
5729
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005730#if ENABLE_HUSH_TICK
5731static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5732{
5733 pid_t pid;
5734 int channel[2];
5735# if !BB_MMU
5736 char **to_free = NULL;
5737# endif
5738
5739 xpipe(channel);
5740 pid = BB_MMU ? xfork() : xvfork();
5741 if (pid == 0) { /* child */
5742 disable_restore_tty_pgrp_on_exit();
5743 /* Process substitution is not considered to be usual
5744 * 'command execution'.
5745 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5746 */
5747 bb_signals(0
5748 + (1 << SIGTSTP)
5749 + (1 << SIGTTIN)
5750 + (1 << SIGTTOU)
5751 , SIG_IGN);
5752 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5753 close(channel[0]); /* NB: close _first_, then move fd! */
5754 xmove_fd(channel[1], 1);
5755 /* Prevent it from trying to handle ctrl-z etc */
5756 IF_HUSH_JOB(G.run_list_level = 1;)
5757 /* Awful hack for `trap` or $(trap).
5758 *
5759 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5760 * contains an example where "trap" is executed in a subshell:
5761 *
5762 * save_traps=$(trap)
5763 * ...
5764 * eval "$save_traps"
5765 *
5766 * Standard does not say that "trap" in subshell shall print
5767 * parent shell's traps. It only says that its output
5768 * must have suitable form, but then, in the above example
5769 * (which is not supposed to be normative), it implies that.
5770 *
5771 * bash (and probably other shell) does implement it
5772 * (traps are reset to defaults, but "trap" still shows them),
5773 * but as a result, "trap" logic is hopelessly messed up:
5774 *
5775 * # trap
5776 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5777 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5778 * # true | trap <--- trap is in subshell - no output (ditto)
5779 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5780 * trap -- 'echo Ho' SIGWINCH
5781 * # echo `(trap)` <--- in subshell in subshell - output
5782 * trap -- 'echo Ho' SIGWINCH
5783 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5784 * trap -- 'echo Ho' SIGWINCH
5785 *
5786 * The rules when to forget and when to not forget traps
5787 * get really complex and nonsensical.
5788 *
5789 * Our solution: ONLY bare $(trap) or `trap` is special.
5790 */
5791 s = skip_whitespace(s);
5792 if (strncmp(s, "trap", 4) == 0
5793 && skip_whitespace(s + 4)[0] == '\0'
5794 ) {
5795 static const char *const argv[] = { NULL, NULL };
5796 builtin_trap((char**)argv);
5797 exit(0); /* not _exit() - we need to fflush */
5798 }
5799# if BB_MMU
5800 reset_traps_to_defaults();
5801 parse_and_run_string(s);
5802 _exit(G.last_exitcode);
5803# else
5804 /* We re-execute after vfork on NOMMU. This makes this script safe:
5805 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5806 * huge=`cat BIG` # was blocking here forever
5807 * echo OK
5808 */
5809 re_execute_shell(&to_free,
5810 s,
5811 G.global_argv[0],
5812 G.global_argv + 1,
5813 NULL);
5814# endif
5815 }
5816
5817 /* parent */
5818 *pid_p = pid;
5819# if ENABLE_HUSH_FAST
5820 G.count_SIGCHLD++;
5821//bb_error_msg("[%d] fork in generate_stream_from_string:"
5822// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5823// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5824# endif
5825 enable_restore_tty_pgrp_on_exit();
5826# if !BB_MMU
5827 free(to_free);
5828# endif
5829 close(channel[1]);
5830 close_on_exec_on(channel[0]);
5831 return xfdopen_for_read(channel[0]);
5832}
5833
5834/* Return code is exit status of the process that is run. */
5835static int process_command_subs(o_string *dest, const char *s)
5836{
5837 FILE *fp;
5838 struct in_str pipe_str;
5839 pid_t pid;
5840 int status, ch, eol_cnt;
5841
5842 fp = generate_stream_from_string(s, &pid);
5843
5844 /* Now send results of command back into original context */
5845 setup_file_in_str(&pipe_str, fp);
5846 eol_cnt = 0;
5847 while ((ch = i_getch(&pipe_str)) != EOF) {
5848 if (ch == '\n') {
5849 eol_cnt++;
5850 continue;
5851 }
5852 while (eol_cnt) {
5853 o_addchr(dest, '\n');
5854 eol_cnt--;
5855 }
5856 o_addQchr(dest, ch);
5857 }
5858
5859 debug_printf("done reading from `cmd` pipe, closing it\n");
5860 fclose(fp);
5861 /* We need to extract exitcode. Test case
5862 * "true; echo `sleep 1; false` $?"
5863 * should print 1 */
5864 safe_waitpid(pid, &status, 0);
5865 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5866 return WEXITSTATUS(status);
5867}
5868#endif /* ENABLE_HUSH_TICK */
5869
5870
5871static void setup_heredoc(struct redir_struct *redir)
5872{
5873 struct fd_pair pair;
5874 pid_t pid;
5875 int len, written;
5876 /* the _body_ of heredoc (misleading field name) */
5877 const char *heredoc = redir->rd_filename;
5878 char *expanded;
5879#if !BB_MMU
5880 char **to_free;
5881#endif
5882
5883 expanded = NULL;
5884 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005885 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005886 if (expanded)
5887 heredoc = expanded;
5888 }
5889 len = strlen(heredoc);
5890
5891 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5892 xpiped_pair(pair);
5893 xmove_fd(pair.rd, redir->rd_fd);
5894
5895 /* Try writing without forking. Newer kernels have
5896 * dynamically growing pipes. Must use non-blocking write! */
5897 ndelay_on(pair.wr);
5898 while (1) {
5899 written = write(pair.wr, heredoc, len);
5900 if (written <= 0)
5901 break;
5902 len -= written;
5903 if (len == 0) {
5904 close(pair.wr);
5905 free(expanded);
5906 return;
5907 }
5908 heredoc += written;
5909 }
5910 ndelay_off(pair.wr);
5911
5912 /* Okay, pipe buffer was not big enough */
5913 /* Note: we must not create a stray child (bastard? :)
5914 * for the unsuspecting parent process. Child creates a grandchild
5915 * and exits before parent execs the process which consumes heredoc
5916 * (that exec happens after we return from this function) */
5917#if !BB_MMU
5918 to_free = NULL;
5919#endif
5920 pid = xvfork();
5921 if (pid == 0) {
5922 /* child */
5923 disable_restore_tty_pgrp_on_exit();
5924 pid = BB_MMU ? xfork() : xvfork();
5925 if (pid != 0)
5926 _exit(0);
5927 /* grandchild */
5928 close(redir->rd_fd); /* read side of the pipe */
5929#if BB_MMU
5930 full_write(pair.wr, heredoc, len); /* may loop or block */
5931 _exit(0);
5932#else
5933 /* Delegate blocking writes to another process */
5934 xmove_fd(pair.wr, STDOUT_FILENO);
5935 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5936#endif
5937 }
5938 /* parent */
5939#if ENABLE_HUSH_FAST
5940 G.count_SIGCHLD++;
5941//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5942#endif
5943 enable_restore_tty_pgrp_on_exit();
5944#if !BB_MMU
5945 free(to_free);
5946#endif
5947 close(pair.wr);
5948 free(expanded);
5949 wait(NULL); /* wait till child has died */
5950}
5951
5952/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5953 * and stderr if they are redirected. */
5954static int setup_redirects(struct command *prog, int squirrel[])
5955{
5956 int openfd, mode;
5957 struct redir_struct *redir;
5958
5959 for (redir = prog->redirects; redir; redir = redir->next) {
5960 if (redir->rd_type == REDIRECT_HEREDOC2) {
5961 /* rd_fd<<HERE case */
5962 if (squirrel && redir->rd_fd < 3
5963 && squirrel[redir->rd_fd] < 0
5964 ) {
5965 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5966 }
5967 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5968 * of the heredoc */
5969 debug_printf_parse("set heredoc '%s'\n",
5970 redir->rd_filename);
5971 setup_heredoc(redir);
5972 continue;
5973 }
5974
5975 if (redir->rd_dup == REDIRFD_TO_FILE) {
5976 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5977 char *p;
5978 if (redir->rd_filename == NULL) {
5979 /* Something went wrong in the parse.
5980 * Pretend it didn't happen */
5981 bb_error_msg("bug in redirect parse");
5982 continue;
5983 }
5984 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005985 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005986 openfd = open_or_warn(p, mode);
5987 free(p);
5988 if (openfd < 0) {
5989 /* this could get lost if stderr has been redirected, but
5990 * bash and ash both lose it as well (though zsh doesn't!) */
5991//what the above comment tries to say?
5992 return 1;
5993 }
5994 } else {
5995 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5996 openfd = redir->rd_dup;
5997 }
5998
5999 if (openfd != redir->rd_fd) {
6000 if (squirrel && redir->rd_fd < 3
6001 && squirrel[redir->rd_fd] < 0
6002 ) {
6003 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6004 }
6005 if (openfd == REDIRFD_CLOSE) {
6006 /* "n>-" means "close me" */
6007 close(redir->rd_fd);
6008 } else {
6009 xdup2(openfd, redir->rd_fd);
6010 if (redir->rd_dup == REDIRFD_TO_FILE)
6011 close(openfd);
6012 }
6013 }
6014 }
6015 return 0;
6016}
6017
6018static void restore_redirects(int squirrel[])
6019{
6020 int i, fd;
6021 for (i = 0; i < 3; i++) {
6022 fd = squirrel[i];
6023 if (fd != -1) {
6024 /* We simply die on error */
6025 xmove_fd(fd, i);
6026 }
6027 }
6028}
6029
6030static char *find_in_path(const char *arg)
6031{
6032 char *ret = NULL;
6033 const char *PATH = get_local_var_value("PATH");
6034
6035 if (!PATH)
6036 return NULL;
6037
6038 while (1) {
6039 const char *end = strchrnul(PATH, ':');
6040 int sz = end - PATH; /* must be int! */
6041
6042 free(ret);
6043 if (sz != 0) {
6044 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6045 } else {
6046 /* We have xxx::yyyy in $PATH,
6047 * it means "use current dir" */
6048 ret = xstrdup(arg);
6049 }
6050 if (access(ret, F_OK) == 0)
6051 break;
6052
6053 if (*end == '\0') {
6054 free(ret);
6055 return NULL;
6056 }
6057 PATH = end + 1;
6058 }
6059
6060 return ret;
6061}
6062
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006063static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006064 const struct built_in_command *x,
6065 const struct built_in_command *end)
6066{
6067 while (x != end) {
6068 if (strcmp(name, x->b_cmd) != 0) {
6069 x++;
6070 continue;
6071 }
6072 debug_printf_exec("found builtin '%s'\n", name);
6073 return x;
6074 }
6075 return NULL;
6076}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006077static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006078{
6079 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6080}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006081static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006082{
6083 const struct built_in_command *x = find_builtin1(name);
6084 if (x)
6085 return x;
6086 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6087}
6088
6089#if ENABLE_HUSH_FUNCTIONS
6090static struct function **find_function_slot(const char *name)
6091{
6092 struct function **funcpp = &G.top_func;
6093 while (*funcpp) {
6094 if (strcmp(name, (*funcpp)->name) == 0) {
6095 break;
6096 }
6097 funcpp = &(*funcpp)->next;
6098 }
6099 return funcpp;
6100}
6101
6102static const struct function *find_function(const char *name)
6103{
6104 const struct function *funcp = *find_function_slot(name);
6105 if (funcp)
6106 debug_printf_exec("found function '%s'\n", name);
6107 return funcp;
6108}
6109
6110/* Note: takes ownership on name ptr */
6111static struct function *new_function(char *name)
6112{
6113 struct function **funcpp = find_function_slot(name);
6114 struct function *funcp = *funcpp;
6115
6116 if (funcp != NULL) {
6117 struct command *cmd = funcp->parent_cmd;
6118 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6119 if (!cmd) {
6120 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6121 free(funcp->name);
6122 /* Note: if !funcp->body, do not free body_as_string!
6123 * This is a special case of "-F name body" function:
6124 * body_as_string was not malloced! */
6125 if (funcp->body) {
6126 free_pipe_list(funcp->body);
6127# if !BB_MMU
6128 free(funcp->body_as_string);
6129# endif
6130 }
6131 } else {
6132 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6133 cmd->argv[0] = funcp->name;
6134 cmd->group = funcp->body;
6135# if !BB_MMU
6136 cmd->group_as_string = funcp->body_as_string;
6137# endif
6138 }
6139 } else {
6140 debug_printf_exec("remembering new function '%s'\n", name);
6141 funcp = *funcpp = xzalloc(sizeof(*funcp));
6142 /*funcp->next = NULL;*/
6143 }
6144
6145 funcp->name = name;
6146 return funcp;
6147}
6148
6149static void unset_func(const char *name)
6150{
6151 struct function **funcpp = find_function_slot(name);
6152 struct function *funcp = *funcpp;
6153
6154 if (funcp != NULL) {
6155 debug_printf_exec("freeing function '%s'\n", funcp->name);
6156 *funcpp = funcp->next;
6157 /* funcp is unlinked now, deleting it.
6158 * Note: if !funcp->body, the function was created by
6159 * "-F name body", do not free ->body_as_string
6160 * and ->name as they were not malloced. */
6161 if (funcp->body) {
6162 free_pipe_list(funcp->body);
6163 free(funcp->name);
6164# if !BB_MMU
6165 free(funcp->body_as_string);
6166# endif
6167 }
6168 free(funcp);
6169 }
6170}
6171
6172# if BB_MMU
6173#define exec_function(to_free, funcp, argv) \
6174 exec_function(funcp, argv)
6175# endif
6176static void exec_function(char ***to_free,
6177 const struct function *funcp,
6178 char **argv) NORETURN;
6179static void exec_function(char ***to_free,
6180 const struct function *funcp,
6181 char **argv)
6182{
6183# if BB_MMU
6184 int n = 1;
6185
6186 argv[0] = G.global_argv[0];
6187 G.global_argv = argv;
6188 while (*++argv)
6189 n++;
6190 G.global_argc = n;
6191 /* On MMU, funcp->body is always non-NULL */
6192 n = run_list(funcp->body);
6193 fflush_all();
6194 _exit(n);
6195# else
6196 re_execute_shell(to_free,
6197 funcp->body_as_string,
6198 G.global_argv[0],
6199 argv + 1,
6200 NULL);
6201# endif
6202}
6203
6204static int run_function(const struct function *funcp, char **argv)
6205{
6206 int rc;
6207 save_arg_t sv;
6208 smallint sv_flg;
6209
6210 save_and_replace_G_args(&sv, argv);
6211
6212 /* "we are in function, ok to use return" */
6213 sv_flg = G.flag_return_in_progress;
6214 G.flag_return_in_progress = -1;
6215# if ENABLE_HUSH_LOCAL
6216 G.func_nest_level++;
6217# endif
6218
6219 /* On MMU, funcp->body is always non-NULL */
6220# if !BB_MMU
6221 if (!funcp->body) {
6222 /* Function defined by -F */
6223 parse_and_run_string(funcp->body_as_string);
6224 rc = G.last_exitcode;
6225 } else
6226# endif
6227 {
6228 rc = run_list(funcp->body);
6229 }
6230
6231# if ENABLE_HUSH_LOCAL
6232 {
6233 struct variable *var;
6234 struct variable **var_pp;
6235
6236 var_pp = &G.top_var;
6237 while ((var = *var_pp) != NULL) {
6238 if (var->func_nest_level < G.func_nest_level) {
6239 var_pp = &var->next;
6240 continue;
6241 }
6242 /* Unexport */
6243 if (var->flg_export)
6244 bb_unsetenv(var->varstr);
6245 /* Remove from global list */
6246 *var_pp = var->next;
6247 /* Free */
6248 if (!var->max_len)
6249 free(var->varstr);
6250 free(var);
6251 }
6252 G.func_nest_level--;
6253 }
6254# endif
6255 G.flag_return_in_progress = sv_flg;
6256
6257 restore_G_args(&sv, argv);
6258
6259 return rc;
6260}
6261#endif /* ENABLE_HUSH_FUNCTIONS */
6262
6263
6264#if BB_MMU
6265#define exec_builtin(to_free, x, argv) \
6266 exec_builtin(x, argv)
6267#else
6268#define exec_builtin(to_free, x, argv) \
6269 exec_builtin(to_free, argv)
6270#endif
6271static void exec_builtin(char ***to_free,
6272 const struct built_in_command *x,
6273 char **argv) NORETURN;
6274static void exec_builtin(char ***to_free,
6275 const struct built_in_command *x,
6276 char **argv)
6277{
6278#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006279 int rcode;
6280 fflush_all();
6281 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006282 fflush_all();
6283 _exit(rcode);
6284#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006285 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006286 /* On NOMMU, we must never block!
6287 * Example: { sleep 99 | read line; } & echo Ok
6288 */
6289 re_execute_shell(to_free,
6290 argv[0],
6291 G.global_argv[0],
6292 G.global_argv + 1,
6293 argv);
6294#endif
6295}
6296
6297
6298static void execvp_or_die(char **argv) NORETURN;
6299static void execvp_or_die(char **argv)
6300{
6301 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006302 /* Don't propagate SIG_IGN to the child */
6303 if (SPECIAL_JOBSTOP_SIGS != 0)
6304 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006305 execvp(argv[0], argv);
6306 bb_perror_msg("can't execute '%s'", argv[0]);
6307 _exit(127); /* bash compat */
6308}
6309
6310#if ENABLE_HUSH_MODE_X
6311static void dump_cmd_in_x_mode(char **argv)
6312{
6313 if (G_x_mode && argv) {
6314 /* We want to output the line in one write op */
6315 char *buf, *p;
6316 int len;
6317 int n;
6318
6319 len = 3;
6320 n = 0;
6321 while (argv[n])
6322 len += strlen(argv[n++]) + 1;
6323 buf = xmalloc(len);
6324 buf[0] = '+';
6325 p = buf + 1;
6326 n = 0;
6327 while (argv[n])
6328 p += sprintf(p, " %s", argv[n++]);
6329 *p++ = '\n';
6330 *p = '\0';
6331 fputs(buf, stderr);
6332 free(buf);
6333 }
6334}
6335#else
6336# define dump_cmd_in_x_mode(argv) ((void)0)
6337#endif
6338
6339#if BB_MMU
6340#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6341 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6342#define pseudo_exec(nommu_save, command, argv_expanded) \
6343 pseudo_exec(command, argv_expanded)
6344#endif
6345
6346/* Called after [v]fork() in run_pipe, or from builtin_exec.
6347 * Never returns.
6348 * Don't exit() here. If you don't exec, use _exit instead.
6349 * The at_exit handlers apparently confuse the calling process,
6350 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6351static void pseudo_exec_argv(nommu_save_t *nommu_save,
6352 char **argv, int assignment_cnt,
6353 char **argv_expanded) NORETURN;
6354static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6355 char **argv, int assignment_cnt,
6356 char **argv_expanded)
6357{
6358 char **new_env;
6359
6360 new_env = expand_assignments(argv, assignment_cnt);
6361 dump_cmd_in_x_mode(new_env);
6362
6363 if (!argv[assignment_cnt]) {
6364 /* Case when we are here: ... | var=val | ...
6365 * (note that we do not exit early, i.e., do not optimize out
6366 * expand_assignments(): think about ... | var=`sleep 1` | ...
6367 */
6368 free_strings(new_env);
6369 _exit(EXIT_SUCCESS);
6370 }
6371
6372#if BB_MMU
6373 set_vars_and_save_old(new_env);
6374 free(new_env); /* optional */
6375 /* we can also destroy set_vars_and_save_old's return value,
6376 * to save memory */
6377#else
6378 nommu_save->new_env = new_env;
6379 nommu_save->old_vars = set_vars_and_save_old(new_env);
6380#endif
6381
6382 if (argv_expanded) {
6383 argv = argv_expanded;
6384 } else {
6385 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6386#if !BB_MMU
6387 nommu_save->argv = argv;
6388#endif
6389 }
6390 dump_cmd_in_x_mode(argv);
6391
6392#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6393 if (strchr(argv[0], '/') != NULL)
6394 goto skip;
6395#endif
6396
6397 /* Check if the command matches any of the builtins.
6398 * Depending on context, this might be redundant. But it's
6399 * easier to waste a few CPU cycles than it is to figure out
6400 * if this is one of those cases.
6401 */
6402 {
6403 /* On NOMMU, it is more expensive to re-execute shell
6404 * just in order to run echo or test builtin.
6405 * It's better to skip it here and run corresponding
6406 * non-builtin later. */
6407 const struct built_in_command *x;
6408 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6409 if (x) {
6410 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6411 }
6412 }
6413#if ENABLE_HUSH_FUNCTIONS
6414 /* Check if the command matches any functions */
6415 {
6416 const struct function *funcp = find_function(argv[0]);
6417 if (funcp) {
6418 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6419 }
6420 }
6421#endif
6422
6423#if ENABLE_FEATURE_SH_STANDALONE
6424 /* Check if the command matches any busybox applets */
6425 {
6426 int a = find_applet_by_name(argv[0]);
6427 if (a >= 0) {
6428# if BB_MMU /* see above why on NOMMU it is not allowed */
6429 if (APPLET_IS_NOEXEC(a)) {
6430 debug_printf_exec("running applet '%s'\n", argv[0]);
6431 run_applet_no_and_exit(a, argv);
6432 }
6433# endif
6434 /* Re-exec ourselves */
6435 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006436 /* Don't propagate SIG_IGN to the child */
6437 if (SPECIAL_JOBSTOP_SIGS != 0)
6438 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006439 execv(bb_busybox_exec_path, argv);
6440 /* If they called chroot or otherwise made the binary no longer
6441 * executable, fall through */
6442 }
6443 }
6444#endif
6445
6446#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6447 skip:
6448#endif
6449 execvp_or_die(argv);
6450}
6451
6452/* Called after [v]fork() in run_pipe
6453 */
6454static void pseudo_exec(nommu_save_t *nommu_save,
6455 struct command *command,
6456 char **argv_expanded) NORETURN;
6457static void pseudo_exec(nommu_save_t *nommu_save,
6458 struct command *command,
6459 char **argv_expanded)
6460{
6461 if (command->argv) {
6462 pseudo_exec_argv(nommu_save, command->argv,
6463 command->assignment_cnt, argv_expanded);
6464 }
6465
6466 if (command->group) {
6467 /* Cases when we are here:
6468 * ( list )
6469 * { list } &
6470 * ... | ( list ) | ...
6471 * ... | { list } | ...
6472 */
6473#if BB_MMU
6474 int rcode;
6475 debug_printf_exec("pseudo_exec: run_list\n");
6476 reset_traps_to_defaults();
6477 rcode = run_list(command->group);
6478 /* OK to leak memory by not calling free_pipe_list,
6479 * since this process is about to exit */
6480 _exit(rcode);
6481#else
6482 re_execute_shell(&nommu_save->argv_from_re_execing,
6483 command->group_as_string,
6484 G.global_argv[0],
6485 G.global_argv + 1,
6486 NULL);
6487#endif
6488 }
6489
6490 /* Case when we are here: ... | >file */
6491 debug_printf_exec("pseudo_exec'ed null command\n");
6492 _exit(EXIT_SUCCESS);
6493}
6494
6495#if ENABLE_HUSH_JOB
6496static const char *get_cmdtext(struct pipe *pi)
6497{
6498 char **argv;
6499 char *p;
6500 int len;
6501
6502 /* This is subtle. ->cmdtext is created only on first backgrounding.
6503 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6504 * On subsequent bg argv is trashed, but we won't use it */
6505 if (pi->cmdtext)
6506 return pi->cmdtext;
6507 argv = pi->cmds[0].argv;
6508 if (!argv || !argv[0]) {
6509 pi->cmdtext = xzalloc(1);
6510 return pi->cmdtext;
6511 }
6512
6513 len = 0;
6514 do {
6515 len += strlen(*argv) + 1;
6516 } while (*++argv);
6517 p = xmalloc(len);
6518 pi->cmdtext = p;
6519 argv = pi->cmds[0].argv;
6520 do {
6521 len = strlen(*argv);
6522 memcpy(p, *argv, len);
6523 p += len;
6524 *p++ = ' ';
6525 } while (*++argv);
6526 p[-1] = '\0';
6527 return pi->cmdtext;
6528}
6529
6530static void insert_bg_job(struct pipe *pi)
6531{
6532 struct pipe *job, **jobp;
6533 int i;
6534
6535 /* Linear search for the ID of the job to use */
6536 pi->jobid = 1;
6537 for (job = G.job_list; job; job = job->next)
6538 if (job->jobid >= pi->jobid)
6539 pi->jobid = job->jobid + 1;
6540
6541 /* Add job to the list of running jobs */
6542 jobp = &G.job_list;
6543 while ((job = *jobp) != NULL)
6544 jobp = &job->next;
6545 job = *jobp = xmalloc(sizeof(*job));
6546
6547 *job = *pi; /* physical copy */
6548 job->next = NULL;
6549 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6550 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6551 for (i = 0; i < pi->num_cmds; i++) {
6552 job->cmds[i].pid = pi->cmds[i].pid;
6553 /* all other fields are not used and stay zero */
6554 }
6555 job->cmdtext = xstrdup(get_cmdtext(pi));
6556
6557 if (G_interactive_fd)
6558 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6559 G.last_jobid = job->jobid;
6560}
6561
6562static void remove_bg_job(struct pipe *pi)
6563{
6564 struct pipe *prev_pipe;
6565
6566 if (pi == G.job_list) {
6567 G.job_list = pi->next;
6568 } else {
6569 prev_pipe = G.job_list;
6570 while (prev_pipe->next != pi)
6571 prev_pipe = prev_pipe->next;
6572 prev_pipe->next = pi->next;
6573 }
6574 if (G.job_list)
6575 G.last_jobid = G.job_list->jobid;
6576 else
6577 G.last_jobid = 0;
6578}
6579
6580/* Remove a backgrounded job */
6581static void delete_finished_bg_job(struct pipe *pi)
6582{
6583 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006584 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006585}
6586#endif /* JOB */
6587
6588/* Check to see if any processes have exited -- if they
6589 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006590static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006591{
6592 int attributes;
6593 int status;
6594#if ENABLE_HUSH_JOB
6595 struct pipe *pi;
6596#endif
6597 pid_t childpid;
6598 int rcode = 0;
6599
6600 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6601
6602 attributes = WUNTRACED;
6603 if (fg_pipe == NULL)
6604 attributes |= WNOHANG;
6605
6606 errno = 0;
6607#if ENABLE_HUSH_FAST
6608 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6609//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6610//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6611 /* There was neither fork nor SIGCHLD since last waitpid */
6612 /* Avoid doing waitpid syscall if possible */
6613 if (!G.we_have_children) {
6614 errno = ECHILD;
6615 return -1;
6616 }
6617 if (fg_pipe == NULL) { /* is WNOHANG set? */
6618 /* We have children, but they did not exit
6619 * or stop yet (we saw no SIGCHLD) */
6620 return 0;
6621 }
6622 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6623 }
6624#endif
6625
6626/* Do we do this right?
6627 * bash-3.00# sleep 20 | false
6628 * <ctrl-Z pressed>
6629 * [3]+ Stopped sleep 20 | false
6630 * bash-3.00# echo $?
6631 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6632 * [hush 1.14.0: yes we do it right]
6633 */
6634 wait_more:
6635 while (1) {
6636 int i;
6637 int dead;
6638
6639#if ENABLE_HUSH_FAST
6640 i = G.count_SIGCHLD;
6641#endif
6642 childpid = waitpid(-1, &status, attributes);
6643 if (childpid <= 0) {
6644 if (childpid && errno != ECHILD)
6645 bb_perror_msg("waitpid");
6646#if ENABLE_HUSH_FAST
6647 else { /* Until next SIGCHLD, waitpid's are useless */
6648 G.we_have_children = (childpid == 0);
6649 G.handled_SIGCHLD = i;
6650//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6651 }
6652#endif
6653 break;
6654 }
6655 dead = WIFEXITED(status) || WIFSIGNALED(status);
6656
6657#if DEBUG_JOBS
6658 if (WIFSTOPPED(status))
6659 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6660 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6661 if (WIFSIGNALED(status))
6662 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6663 childpid, WTERMSIG(status), WEXITSTATUS(status));
6664 if (WIFEXITED(status))
6665 debug_printf_jobs("pid %d exited, exitcode %d\n",
6666 childpid, WEXITSTATUS(status));
6667#endif
6668 /* Were we asked to wait for fg pipe? */
6669 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006670 i = fg_pipe->num_cmds;
6671 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006672 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6673 if (fg_pipe->cmds[i].pid != childpid)
6674 continue;
6675 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006676 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006677 fg_pipe->cmds[i].pid = 0;
6678 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006679 ex = WEXITSTATUS(status);
6680 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006681 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006682 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6683 */
6684 if (WIFSIGNALED(status)) {
6685 int sig = WTERMSIG(status);
6686 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006687 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6688 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6689 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006690 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6691 * Maybe we need to use sig | 128? */
6692 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006693 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006694 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006695 } else {
6696 fg_pipe->cmds[i].is_stopped = 1;
6697 fg_pipe->stopped_cmds++;
6698 }
6699 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6700 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006701 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006702 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006703 i = fg_pipe->num_cmds;
6704 while (--i >= 0) {
6705 rcode = fg_pipe->cmds[i].cmd_exitcode;
6706 /* usually last process gives overall exitstatus,
6707 * but with "set -o pipefail", last *failed* process does */
6708 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6709 break;
6710 }
6711 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006712/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6713 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6714 * and "killall -STOP cat" */
6715 if (G_interactive_fd) {
6716#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006717 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006718 insert_bg_job(fg_pipe);
6719#endif
6720 return rcode;
6721 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006722 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006723 return rcode;
6724 }
6725 /* There are still running processes in the fg pipe */
6726 goto wait_more; /* do waitpid again */
6727 }
6728 /* it wasnt fg_pipe, look for process in bg pipes */
6729 }
6730
6731#if ENABLE_HUSH_JOB
6732 /* We asked to wait for bg or orphaned children */
6733 /* No need to remember exitcode in this case */
6734 for (pi = G.job_list; pi; pi = pi->next) {
6735 for (i = 0; i < pi->num_cmds; i++) {
6736 if (pi->cmds[i].pid == childpid)
6737 goto found_pi_and_prognum;
6738 }
6739 }
6740 /* Happens when shell is used as init process (init=/bin/sh) */
6741 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6742 continue; /* do waitpid again */
6743
6744 found_pi_and_prognum:
6745 if (dead) {
6746 /* child exited */
6747 pi->cmds[i].pid = 0;
6748 pi->alive_cmds--;
6749 if (!pi->alive_cmds) {
6750 if (G_interactive_fd)
6751 printf(JOB_STATUS_FORMAT, pi->jobid,
6752 "Done", pi->cmdtext);
6753 delete_finished_bg_job(pi);
6754 }
6755 } else {
6756 /* child stopped */
6757 pi->cmds[i].is_stopped = 1;
6758 pi->stopped_cmds++;
6759 }
6760#endif
6761 } /* while (waitpid succeeds)... */
6762
6763 return rcode;
6764}
6765
6766#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006767static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006768{
6769 pid_t p;
6770 int rcode = checkjobs(fg_pipe);
6771 if (G_saved_tty_pgrp) {
6772 /* Job finished, move the shell to the foreground */
6773 p = getpgrp(); /* our process group id */
6774 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6775 tcsetpgrp(G_interactive_fd, p);
6776 }
6777 return rcode;
6778}
6779#endif
6780
6781/* Start all the jobs, but don't wait for anything to finish.
6782 * See checkjobs().
6783 *
6784 * Return code is normally -1, when the caller has to wait for children
6785 * to finish to determine the exit status of the pipe. If the pipe
6786 * is a simple builtin command, however, the action is done by the
6787 * time run_pipe returns, and the exit code is provided as the
6788 * return value.
6789 *
6790 * Returns -1 only if started some children. IOW: we have to
6791 * mask out retvals of builtins etc with 0xff!
6792 *
6793 * The only case when we do not need to [v]fork is when the pipe
6794 * is single, non-backgrounded, non-subshell command. Examples:
6795 * cmd ; ... { list } ; ...
6796 * cmd && ... { list } && ...
6797 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006798 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006799 * or (if SH_STANDALONE) an applet, and we can run the { list }
6800 * with run_list. If it isn't one of these, we fork and exec cmd.
6801 *
6802 * Cases when we must fork:
6803 * non-single: cmd | cmd
6804 * backgrounded: cmd & { list } &
6805 * subshell: ( list ) [&]
6806 */
6807#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006808#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006809 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6810#endif
6811static int redirect_and_varexp_helper(char ***new_env_p,
6812 struct variable **old_vars_p,
6813 struct command *command,
6814 int squirrel[3],
6815 char **argv_expanded)
6816{
6817 /* setup_redirects acts on file descriptors, not FILEs.
6818 * This is perfect for work that comes after exec().
6819 * Is it really safe for inline use? Experimentally,
6820 * things seem to work. */
6821 int rcode = setup_redirects(command, squirrel);
6822 if (rcode == 0) {
6823 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6824 *new_env_p = new_env;
6825 dump_cmd_in_x_mode(new_env);
6826 dump_cmd_in_x_mode(argv_expanded);
6827 if (old_vars_p)
6828 *old_vars_p = set_vars_and_save_old(new_env);
6829 }
6830 return rcode;
6831}
6832static NOINLINE int run_pipe(struct pipe *pi)
6833{
6834 static const char *const null_ptr = NULL;
6835
6836 int cmd_no;
6837 int next_infd;
6838 struct command *command;
6839 char **argv_expanded;
6840 char **argv;
6841 /* it is not always needed, but we aim to smaller code */
6842 int squirrel[] = { -1, -1, -1 };
6843 int rcode;
6844
6845 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6846 debug_enter();
6847
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006848 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6849 * Result should be 3 lines: q w e, qwe, q w e
6850 */
6851 G.ifs = get_local_var_value("IFS");
6852 if (!G.ifs)
6853 G.ifs = defifs;
6854
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006855 IF_HUSH_JOB(pi->pgrp = -1;)
6856 pi->stopped_cmds = 0;
6857 command = &pi->cmds[0];
6858 argv_expanded = NULL;
6859
6860 if (pi->num_cmds != 1
6861 || pi->followup == PIPE_BG
6862 || command->cmd_type == CMD_SUBSHELL
6863 ) {
6864 goto must_fork;
6865 }
6866
6867 pi->alive_cmds = 1;
6868
6869 debug_printf_exec(": group:%p argv:'%s'\n",
6870 command->group, command->argv ? command->argv[0] : "NONE");
6871
6872 if (command->group) {
6873#if ENABLE_HUSH_FUNCTIONS
6874 if (command->cmd_type == CMD_FUNCDEF) {
6875 /* "executing" func () { list } */
6876 struct function *funcp;
6877
6878 funcp = new_function(command->argv[0]);
6879 /* funcp->name is already set to argv[0] */
6880 funcp->body = command->group;
6881# if !BB_MMU
6882 funcp->body_as_string = command->group_as_string;
6883 command->group_as_string = NULL;
6884# endif
6885 command->group = NULL;
6886 command->argv[0] = NULL;
6887 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6888 funcp->parent_cmd = command;
6889 command->child_func = funcp;
6890
6891 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6892 debug_leave();
6893 return EXIT_SUCCESS;
6894 }
6895#endif
6896 /* { list } */
6897 debug_printf("non-subshell group\n");
6898 rcode = 1; /* exitcode if redir failed */
6899 if (setup_redirects(command, squirrel) == 0) {
6900 debug_printf_exec(": run_list\n");
6901 rcode = run_list(command->group) & 0xff;
6902 }
6903 restore_redirects(squirrel);
6904 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6905 debug_leave();
6906 debug_printf_exec("run_pipe: return %d\n", rcode);
6907 return rcode;
6908 }
6909
6910 argv = command->argv ? command->argv : (char **) &null_ptr;
6911 {
6912 const struct built_in_command *x;
6913#if ENABLE_HUSH_FUNCTIONS
6914 const struct function *funcp;
6915#else
6916 enum { funcp = 0 };
6917#endif
6918 char **new_env = NULL;
6919 struct variable *old_vars = NULL;
6920
6921 if (argv[command->assignment_cnt] == NULL) {
6922 /* Assignments, but no command */
6923 /* Ensure redirects take effect (that is, create files).
6924 * Try "a=t >file" */
6925#if 0 /* A few cases in testsuite fail with this code. FIXME */
6926 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6927 /* Set shell variables */
6928 if (new_env) {
6929 argv = new_env;
6930 while (*argv) {
6931 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6932 /* Do we need to flag set_local_var() errors?
6933 * "assignment to readonly var" and "putenv error"
6934 */
6935 argv++;
6936 }
6937 }
6938 /* Redirect error sets $? to 1. Otherwise,
6939 * if evaluating assignment value set $?, retain it.
6940 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6941 if (rcode == 0)
6942 rcode = G.last_exitcode;
6943 /* Exit, _skipping_ variable restoring code: */
6944 goto clean_up_and_ret0;
6945
6946#else /* Older, bigger, but more correct code */
6947
6948 rcode = setup_redirects(command, squirrel);
6949 restore_redirects(squirrel);
6950 /* Set shell variables */
6951 if (G_x_mode)
6952 bb_putchar_stderr('+');
6953 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006954 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006955 if (G_x_mode)
6956 fprintf(stderr, " %s", p);
6957 debug_printf_exec("set shell var:'%s'->'%s'\n",
6958 *argv, p);
6959 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6960 /* Do we need to flag set_local_var() errors?
6961 * "assignment to readonly var" and "putenv error"
6962 */
6963 argv++;
6964 }
6965 if (G_x_mode)
6966 bb_putchar_stderr('\n');
6967 /* Redirect error sets $? to 1. Otherwise,
6968 * if evaluating assignment value set $?, retain it.
6969 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6970 if (rcode == 0)
6971 rcode = G.last_exitcode;
6972 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6973 debug_leave();
6974 debug_printf_exec("run_pipe: return %d\n", rcode);
6975 return rcode;
6976#endif
6977 }
6978
6979 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006980#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006981 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006982 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006983 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006984#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006985 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006986 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6987 }
6988
6989 /* if someone gives us an empty string: `cmd with empty output` */
6990 if (!argv_expanded[0]) {
6991 free(argv_expanded);
6992 debug_leave();
6993 return G.last_exitcode;
6994 }
6995
6996 x = find_builtin(argv_expanded[0]);
6997#if ENABLE_HUSH_FUNCTIONS
6998 funcp = NULL;
6999 if (!x)
7000 funcp = find_function(argv_expanded[0]);
7001#endif
7002 if (x || funcp) {
7003 if (!funcp) {
7004 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7005 debug_printf("exec with redirects only\n");
7006 rcode = setup_redirects(command, NULL);
7007 goto clean_up_and_ret1;
7008 }
7009 }
7010 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7011 if (rcode == 0) {
7012 if (!funcp) {
7013 debug_printf_exec(": builtin '%s' '%s'...\n",
7014 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007015 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007016 rcode = x->b_function(argv_expanded) & 0xff;
7017 fflush_all();
7018 }
7019#if ENABLE_HUSH_FUNCTIONS
7020 else {
7021# if ENABLE_HUSH_LOCAL
7022 struct variable **sv;
7023 sv = G.shadowed_vars_pp;
7024 G.shadowed_vars_pp = &old_vars;
7025# endif
7026 debug_printf_exec(": function '%s' '%s'...\n",
7027 funcp->name, argv_expanded[1]);
7028 rcode = run_function(funcp, argv_expanded) & 0xff;
7029# if ENABLE_HUSH_LOCAL
7030 G.shadowed_vars_pp = sv;
7031# endif
7032 }
7033#endif
7034 }
7035 clean_up_and_ret:
7036 unset_vars(new_env);
7037 add_vars(old_vars);
7038/* clean_up_and_ret0: */
7039 restore_redirects(squirrel);
7040 clean_up_and_ret1:
7041 free(argv_expanded);
7042 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7043 debug_leave();
7044 debug_printf_exec("run_pipe return %d\n", rcode);
7045 return rcode;
7046 }
7047
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007048 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007049 int n = find_applet_by_name(argv_expanded[0]);
7050 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7051 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7052 if (rcode == 0) {
7053 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7054 argv_expanded[0], argv_expanded[1]);
7055 rcode = run_nofork_applet(n, argv_expanded);
7056 }
7057 goto clean_up_and_ret;
7058 }
7059 }
7060 /* It is neither builtin nor applet. We must fork. */
7061 }
7062
7063 must_fork:
7064 /* NB: argv_expanded may already be created, and that
7065 * might include `cmd` runs! Do not rerun it! We *must*
7066 * use argv_expanded if it's non-NULL */
7067
7068 /* Going to fork a child per each pipe member */
7069 pi->alive_cmds = 0;
7070 next_infd = 0;
7071
7072 cmd_no = 0;
7073 while (cmd_no < pi->num_cmds) {
7074 struct fd_pair pipefds;
7075#if !BB_MMU
7076 volatile nommu_save_t nommu_save;
7077 nommu_save.new_env = NULL;
7078 nommu_save.old_vars = NULL;
7079 nommu_save.argv = NULL;
7080 nommu_save.argv_from_re_execing = NULL;
7081#endif
7082 command = &pi->cmds[cmd_no];
7083 cmd_no++;
7084 if (command->argv) {
7085 debug_printf_exec(": pipe member '%s' '%s'...\n",
7086 command->argv[0], command->argv[1]);
7087 } else {
7088 debug_printf_exec(": pipe member with no argv\n");
7089 }
7090
7091 /* pipes are inserted between pairs of commands */
7092 pipefds.rd = 0;
7093 pipefds.wr = 1;
7094 if (cmd_no < pi->num_cmds)
7095 xpiped_pair(pipefds);
7096
7097 command->pid = BB_MMU ? fork() : vfork();
7098 if (!command->pid) { /* child */
7099#if ENABLE_HUSH_JOB
7100 disable_restore_tty_pgrp_on_exit();
7101 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7102
7103 /* Every child adds itself to new process group
7104 * with pgid == pid_of_first_child_in_pipe */
7105 if (G.run_list_level == 1 && G_interactive_fd) {
7106 pid_t pgrp;
7107 pgrp = pi->pgrp;
7108 if (pgrp < 0) /* true for 1st process only */
7109 pgrp = getpid();
7110 if (setpgid(0, pgrp) == 0
7111 && pi->followup != PIPE_BG
7112 && G_saved_tty_pgrp /* we have ctty */
7113 ) {
7114 /* We do it in *every* child, not just first,
7115 * to avoid races */
7116 tcsetpgrp(G_interactive_fd, pgrp);
7117 }
7118 }
7119#endif
7120 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7121 /* 1st cmd in backgrounded pipe
7122 * should have its stdin /dev/null'ed */
7123 close(0);
7124 if (open(bb_dev_null, O_RDONLY))
7125 xopen("/", O_RDONLY);
7126 } else {
7127 xmove_fd(next_infd, 0);
7128 }
7129 xmove_fd(pipefds.wr, 1);
7130 if (pipefds.rd > 1)
7131 close(pipefds.rd);
7132 /* Like bash, explicit redirects override pipes,
7133 * and the pipe fd is available for dup'ing. */
7134 if (setup_redirects(command, NULL))
7135 _exit(1);
7136
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007137 /* Stores to nommu_save list of env vars putenv'ed
7138 * (NOMMU, on MMU we don't need that) */
7139 /* cast away volatility... */
7140 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7141 /* pseudo_exec() does not return */
7142 }
7143
7144 /* parent or error */
7145#if ENABLE_HUSH_FAST
7146 G.count_SIGCHLD++;
7147//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7148#endif
7149 enable_restore_tty_pgrp_on_exit();
7150#if !BB_MMU
7151 /* Clean up after vforked child */
7152 free(nommu_save.argv);
7153 free(nommu_save.argv_from_re_execing);
7154 unset_vars(nommu_save.new_env);
7155 add_vars(nommu_save.old_vars);
7156#endif
7157 free(argv_expanded);
7158 argv_expanded = NULL;
7159 if (command->pid < 0) { /* [v]fork failed */
7160 /* Clearly indicate, was it fork or vfork */
7161 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7162 } else {
7163 pi->alive_cmds++;
7164#if ENABLE_HUSH_JOB
7165 /* Second and next children need to know pid of first one */
7166 if (pi->pgrp < 0)
7167 pi->pgrp = command->pid;
7168#endif
7169 }
7170
7171 if (cmd_no > 1)
7172 close(next_infd);
7173 if (cmd_no < pi->num_cmds)
7174 close(pipefds.wr);
7175 /* Pass read (output) pipe end to next iteration */
7176 next_infd = pipefds.rd;
7177 }
7178
7179 if (!pi->alive_cmds) {
7180 debug_leave();
7181 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7182 return 1;
7183 }
7184
7185 debug_leave();
7186 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7187 return -1;
7188}
7189
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007190/* NB: called by pseudo_exec, and therefore must not modify any
7191 * global data until exec/_exit (we can be a child after vfork!) */
7192static int run_list(struct pipe *pi)
7193{
7194#if ENABLE_HUSH_CASE
7195 char *case_word = NULL;
7196#endif
7197#if ENABLE_HUSH_LOOPS
7198 struct pipe *loop_top = NULL;
7199 char **for_lcur = NULL;
7200 char **for_list = NULL;
7201#endif
7202 smallint last_followup;
7203 smalluint rcode;
7204#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7205 smalluint cond_code = 0;
7206#else
7207 enum { cond_code = 0 };
7208#endif
7209#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007210 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007211 smallint last_rword; /* ditto */
7212#endif
7213
7214 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7215 debug_enter();
7216
7217#if ENABLE_HUSH_LOOPS
7218 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007219 {
7220 struct pipe *cpipe;
7221 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7222 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7223 continue;
7224 /* current word is FOR or IN (BOLD in comments below) */
7225 if (cpipe->next == NULL) {
7226 syntax_error("malformed for");
7227 debug_leave();
7228 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7229 return 1;
7230 }
7231 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7232 if (cpipe->next->res_word == RES_DO)
7233 continue;
7234 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7235 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7236 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7237 ) {
7238 syntax_error("malformed for");
7239 debug_leave();
7240 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7241 return 1;
7242 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007243 }
7244 }
7245#endif
7246
7247 /* Past this point, all code paths should jump to ret: label
7248 * in order to return, no direct "return" statements please.
7249 * This helps to ensure that no memory is leaked. */
7250
7251#if ENABLE_HUSH_JOB
7252 G.run_list_level++;
7253#endif
7254
7255#if HAS_KEYWORDS
7256 rword = RES_NONE;
7257 last_rword = RES_XXXX;
7258#endif
7259 last_followup = PIPE_SEQ;
7260 rcode = G.last_exitcode;
7261
7262 /* Go through list of pipes, (maybe) executing them. */
7263 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7264 if (G.flag_SIGINT)
7265 break;
7266
7267 IF_HAS_KEYWORDS(rword = pi->res_word;)
7268 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7269 rword, cond_code, last_rword);
7270#if ENABLE_HUSH_LOOPS
7271 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7272 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7273 ) {
7274 /* start of a loop: remember where loop starts */
7275 loop_top = pi;
7276 G.depth_of_loop++;
7277 }
7278#endif
7279 /* Still in the same "if...", "then..." or "do..." branch? */
7280 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7281 if ((rcode == 0 && last_followup == PIPE_OR)
7282 || (rcode != 0 && last_followup == PIPE_AND)
7283 ) {
7284 /* It is "<true> || CMD" or "<false> && CMD"
7285 * and we should not execute CMD */
7286 debug_printf_exec("skipped cmd because of || or &&\n");
7287 last_followup = pi->followup;
7288 continue;
7289 }
7290 }
7291 last_followup = pi->followup;
7292 IF_HAS_KEYWORDS(last_rword = rword;)
7293#if ENABLE_HUSH_IF
7294 if (cond_code) {
7295 if (rword == RES_THEN) {
7296 /* if false; then ... fi has exitcode 0! */
7297 G.last_exitcode = rcode = EXIT_SUCCESS;
7298 /* "if <false> THEN cmd": skip cmd */
7299 continue;
7300 }
7301 } else {
7302 if (rword == RES_ELSE || rword == RES_ELIF) {
7303 /* "if <true> then ... ELSE/ELIF cmd":
7304 * skip cmd and all following ones */
7305 break;
7306 }
7307 }
7308#endif
7309#if ENABLE_HUSH_LOOPS
7310 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7311 if (!for_lcur) {
7312 /* first loop through for */
7313
7314 static const char encoded_dollar_at[] ALIGN1 = {
7315 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7316 }; /* encoded representation of "$@" */
7317 static const char *const encoded_dollar_at_argv[] = {
7318 encoded_dollar_at, NULL
7319 }; /* argv list with one element: "$@" */
7320 char **vals;
7321
7322 vals = (char**)encoded_dollar_at_argv;
7323 if (pi->next->res_word == RES_IN) {
7324 /* if no variable values after "in" we skip "for" */
7325 if (!pi->next->cmds[0].argv) {
7326 G.last_exitcode = rcode = EXIT_SUCCESS;
7327 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7328 break;
7329 }
7330 vals = pi->next->cmds[0].argv;
7331 } /* else: "for var; do..." -> assume "$@" list */
7332 /* create list of variable values */
7333 debug_print_strings("for_list made from", vals);
7334 for_list = expand_strvec_to_strvec(vals);
7335 for_lcur = for_list;
7336 debug_print_strings("for_list", for_list);
7337 }
7338 if (!*for_lcur) {
7339 /* "for" loop is over, clean up */
7340 free(for_list);
7341 for_list = NULL;
7342 for_lcur = NULL;
7343 break;
7344 }
7345 /* Insert next value from for_lcur */
7346 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7347 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7348 continue;
7349 }
7350 if (rword == RES_IN) {
7351 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7352 }
7353 if (rword == RES_DONE) {
7354 continue; /* "done" has no cmds too */
7355 }
7356#endif
7357#if ENABLE_HUSH_CASE
7358 if (rword == RES_CASE) {
7359 case_word = expand_strvec_to_string(pi->cmds->argv);
7360 continue;
7361 }
7362 if (rword == RES_MATCH) {
7363 char **argv;
7364
7365 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7366 break;
7367 /* all prev words didn't match, does this one match? */
7368 argv = pi->cmds->argv;
7369 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007370 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007371 /* TODO: which FNM_xxx flags to use? */
7372 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7373 free(pattern);
7374 if (cond_code == 0) { /* match! we will execute this branch */
7375 free(case_word); /* make future "word)" stop */
7376 case_word = NULL;
7377 break;
7378 }
7379 argv++;
7380 }
7381 continue;
7382 }
7383 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7384 if (cond_code != 0)
7385 continue; /* not matched yet, skip this pipe */
7386 }
7387#endif
7388 /* Just pressing <enter> in shell should check for jobs.
7389 * OTOH, in non-interactive shell this is useless
7390 * and only leads to extra job checks */
7391 if (pi->num_cmds == 0) {
7392 if (G_interactive_fd)
7393 goto check_jobs_and_continue;
7394 continue;
7395 }
7396
7397 /* After analyzing all keywords and conditions, we decided
7398 * to execute this pipe. NB: have to do checkjobs(NULL)
7399 * after run_pipe to collect any background children,
7400 * even if list execution is to be stopped. */
7401 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7402 {
7403 int r;
7404#if ENABLE_HUSH_LOOPS
7405 G.flag_break_continue = 0;
7406#endif
7407 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7408 if (r != -1) {
7409 /* We ran a builtin, function, or group.
7410 * rcode is already known
7411 * and we don't need to wait for anything. */
7412 G.last_exitcode = rcode;
7413 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007414 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007415#if ENABLE_HUSH_LOOPS
7416 /* Was it "break" or "continue"? */
7417 if (G.flag_break_continue) {
7418 smallint fbc = G.flag_break_continue;
7419 /* We might fall into outer *loop*,
7420 * don't want to break it too */
7421 if (loop_top) {
7422 G.depth_break_continue--;
7423 if (G.depth_break_continue == 0)
7424 G.flag_break_continue = 0;
7425 /* else: e.g. "continue 2" should *break* once, *then* continue */
7426 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7427 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7428 goto check_jobs_and_break;
7429 /* "continue": simulate end of loop */
7430 rword = RES_DONE;
7431 continue;
7432 }
7433#endif
7434#if ENABLE_HUSH_FUNCTIONS
7435 if (G.flag_return_in_progress == 1) {
7436 /* same as "goto check_jobs_and_break" */
7437 checkjobs(NULL);
7438 break;
7439 }
7440#endif
7441 } else if (pi->followup == PIPE_BG) {
7442 /* What does bash do with attempts to background builtins? */
7443 /* even bash 3.2 doesn't do that well with nested bg:
7444 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7445 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007446 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007447#if ENABLE_HUSH_JOB
7448 if (G.run_list_level == 1)
7449 insert_bg_job(pi);
7450#endif
7451 /* Last command's pid goes to $! */
7452 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7453 G.last_exitcode = rcode = EXIT_SUCCESS;
7454 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7455 } else {
7456#if ENABLE_HUSH_JOB
7457 if (G.run_list_level == 1 && G_interactive_fd) {
7458 /* Waits for completion, then fg's main shell */
7459 rcode = checkjobs_and_fg_shell(pi);
7460 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007461 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007462 } else
7463#endif
7464 { /* This one just waits for completion */
7465 rcode = checkjobs(pi);
7466 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007467 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007468 }
7469 G.last_exitcode = rcode;
7470 }
7471 }
7472
7473 /* Analyze how result affects subsequent commands */
7474#if ENABLE_HUSH_IF
7475 if (rword == RES_IF || rword == RES_ELIF)
7476 cond_code = rcode;
7477#endif
7478#if ENABLE_HUSH_LOOPS
7479 /* Beware of "while false; true; do ..."! */
7480 if (pi->next && pi->next->res_word == RES_DO) {
7481 if (rword == RES_WHILE) {
7482 if (rcode) {
7483 /* "while false; do...done" - exitcode 0 */
7484 G.last_exitcode = rcode = EXIT_SUCCESS;
7485 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7486 goto check_jobs_and_break;
7487 }
7488 }
7489 if (rword == RES_UNTIL) {
7490 if (!rcode) {
7491 debug_printf_exec(": until expr is true: breaking\n");
7492 check_jobs_and_break:
7493 checkjobs(NULL);
7494 break;
7495 }
7496 }
7497 }
7498#endif
7499
7500 check_jobs_and_continue:
7501 checkjobs(NULL);
7502 } /* for (pi) */
7503
7504#if ENABLE_HUSH_JOB
7505 G.run_list_level--;
7506#endif
7507#if ENABLE_HUSH_LOOPS
7508 if (loop_top)
7509 G.depth_of_loop--;
7510 free(for_list);
7511#endif
7512#if ENABLE_HUSH_CASE
7513 free(case_word);
7514#endif
7515 debug_leave();
7516 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7517 return rcode;
7518}
7519
7520/* Select which version we will use */
7521static int run_and_free_list(struct pipe *pi)
7522{
7523 int rcode = 0;
7524 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007525 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007526 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7527 rcode = run_list(pi);
7528 }
7529 /* free_pipe_list has the side effect of clearing memory.
7530 * In the long run that function can be merged with run_list,
7531 * but doing that now would hobble the debugging effort. */
7532 free_pipe_list(pi);
7533 debug_printf_exec("run_and_free_list return %d\n", rcode);
7534 return rcode;
7535}
7536
7537
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007538static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007539{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007540 sighandler_t old_handler;
7541 unsigned sig = 0;
7542 while ((mask >>= 1) != 0) {
7543 sig++;
7544 if (!(mask & 1))
7545 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007546 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007547 /* POSIX allows shell to re-enable SIGCHLD
7548 * even if it was SIG_IGN on entry.
7549 * Therefore we skip IGN check for it:
7550 */
7551 if (sig == SIGCHLD)
7552 continue;
7553 if (old_handler == SIG_IGN) {
7554 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007555 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007556 if (!G.traps)
7557 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7558 free(G.traps[sig]);
7559 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7560 }
7561 }
7562}
7563
7564/* Called a few times only (or even once if "sh -c") */
7565static void install_special_sighandlers(void)
7566{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007567 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007568
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007569 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007570 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007571 if (G_interactive_fd) {
7572 mask |= SPECIAL_INTERACTIVE_SIGS;
7573 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007574 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007575 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007576 /* Careful, do not re-install handlers we already installed */
7577 if (G.special_sig_mask != mask) {
7578 unsigned diff = mask & ~G.special_sig_mask;
7579 G.special_sig_mask = mask;
7580 install_sighandlers(diff);
7581 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007582}
7583
7584#if ENABLE_HUSH_JOB
7585/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007586/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007587static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007588{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007589 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007590
7591 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007592 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007593 + (1 << SIGILL ) * HUSH_DEBUG
7594 + (1 << SIGFPE ) * HUSH_DEBUG
7595 + (1 << SIGBUS ) * HUSH_DEBUG
7596 + (1 << SIGSEGV) * HUSH_DEBUG
7597 + (1 << SIGTRAP) * HUSH_DEBUG
7598 + (1 << SIGABRT)
7599 /* bash 3.2 seems to handle these just like 'fatal' ones */
7600 + (1 << SIGPIPE)
7601 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007602 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007603 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007604 * we never want to restore pgrp on exit, and this fn is not called
7605 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007606 /*+ (1 << SIGHUP )*/
7607 /*+ (1 << SIGTERM)*/
7608 /*+ (1 << SIGINT )*/
7609 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007610 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007611
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007612 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007613}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007614#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007615
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007616static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007617{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007618 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007619 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007620 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007621 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007622 break;
7623 case 'x':
7624 IF_HUSH_MODE_X(G_x_mode = state;)
7625 break;
7626 case 'o':
7627 if (!o_opt) {
7628 /* "set -+o" without parameter.
7629 * in bash, set -o produces this output:
7630 * pipefail off
7631 * and set +o:
7632 * set +o pipefail
7633 * We always use the second form.
7634 */
7635 const char *p = o_opt_strings;
7636 idx = 0;
7637 while (*p) {
7638 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7639 idx++;
7640 p += strlen(p) + 1;
7641 }
7642 break;
7643 }
7644 idx = index_in_strings(o_opt_strings, o_opt);
7645 if (idx >= 0) {
7646 G.o_opt[idx] = state;
7647 break;
7648 }
7649 default:
7650 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007651 }
7652 return EXIT_SUCCESS;
7653}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007654
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007655int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007656int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007657{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007658 enum {
7659 OPT_login = (1 << 0),
7660 };
7661 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00007662 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007663 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007664 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007665 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007666 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007667
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007668 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02007669 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007670 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenko10c01312011-05-11 11:49:21 +02007671#if ENABLE_HUSH_FAST
7672 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7673#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007674#if !BB_MMU
7675 G.argv0_for_re_execing = argv[0];
7676#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007677 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007678 shell_ver = xzalloc(sizeof(*shell_ver));
7679 shell_ver->flg_export = 1;
7680 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007681 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007682 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007683 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007684 /* Create shell local variables from the values
7685 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007686 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007687 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007688 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007689 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007690 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007691 if (e) while (*e) {
7692 char *value = strchr(*e, '=');
7693 if (value) { /* paranoia */
7694 cur_var->next = xzalloc(sizeof(*cur_var));
7695 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007696 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007697 cur_var->max_len = strlen(*e);
7698 cur_var->flg_export = 1;
7699 }
7700 e++;
7701 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007702 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007703 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7704 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007705
7706 /* Export PWD */
7707 set_pwd_var(/*exp:*/ 1);
7708 /* bash also exports SHLVL and _,
7709 * and sets (but doesn't export) the following variables:
7710 * BASH=/bin/bash
7711 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7712 * BASH_VERSION='3.2.0(1)-release'
7713 * HOSTTYPE=i386
7714 * MACHTYPE=i386-pc-linux-gnu
7715 * OSTYPE=linux-gnu
7716 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007717 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007718 * EUID=<NNNNN>
7719 * UID=<NNNNN>
7720 * GROUPS=()
7721 * LINES=<NNN>
7722 * COLUMNS=<NNN>
7723 * BASH_ARGC=()
7724 * BASH_ARGV=()
7725 * BASH_LINENO=()
7726 * BASH_SOURCE=()
7727 * DIRSTACK=()
7728 * PIPESTATUS=([0]="0")
7729 * HISTFILE=/<xxx>/.bash_history
7730 * HISTFILESIZE=500
7731 * HISTSIZE=500
7732 * MAILCHECK=60
7733 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7734 * SHELL=/bin/bash
7735 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7736 * TERM=dumb
7737 * OPTERR=1
7738 * OPTIND=1
7739 * IFS=$' \t\n'
7740 * PS1='\s-\v\$ '
7741 * PS2='> '
7742 * PS4='+ '
7743 */
7744
Denis Vlasenko38f63192007-01-22 09:03:07 +00007745#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007746 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007747# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7748 {
7749 const char *hp = get_local_var_value("HISTFILE");
7750 if (!hp) {
7751 hp = get_local_var_value("HOME");
7752 if (hp) {
7753 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7754 //set_local_var(xasprintf("HISTFILE=%s", ...));
7755 }
7756 }
Denys Vlasenko2c4de5b2011-03-31 13:16:52 +02007757# if ENABLE_FEATURE_SH_HISTFILESIZE
7758 hp = get_local_var_value("HISTFILESIZE");
7759 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
7760# endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007761 }
7762# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007763#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007764
Eric Andersen94ac2442001-05-22 19:05:18 +00007765 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007766 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007767
Denis Vlasenkoed782372009-04-10 00:45:02 +00007768 if (setjmp(die_jmp)) {
7769 /* xfunc has failed! die die die */
7770 /* no EXIT traps, this is an escape hatch! */
7771 G.exiting = 1;
7772 hush_exit(xfunc_error_retval);
7773 }
7774
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007775 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007776 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007777 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007778 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007779 * in order to intercept (more) signals.
7780 */
7781
7782 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007783 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007784 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007785 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007786 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007787 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007788#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007789 "<:$:R:V:"
7790# if ENABLE_HUSH_FUNCTIONS
7791 "F:"
7792# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007793#endif
7794 );
7795 if (opt <= 0)
7796 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007797 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007798 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007799 /* Possibilities:
7800 * sh ... -c 'script'
7801 * sh ... -c 'script' ARG0 [ARG1...]
7802 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007803 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007804 * "" needs to be replaced with NULL
7805 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007806 * Note: the form without ARG0 never happens:
7807 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007808 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007809 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007810 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007811 G.root_ppid = getppid();
7812 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007813 G.global_argv = argv + optind;
7814 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007815 if (builtin_argc) {
7816 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7817 const struct built_in_command *x;
7818
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007819 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007820 x = find_builtin(optarg);
7821 if (x) { /* paranoia */
7822 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7823 G.global_argv += builtin_argc;
7824 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007825 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007826 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007827 }
7828 goto final_return;
7829 }
7830 if (!G.global_argv[0]) {
7831 /* -c 'script' (no params): prevent empty $0 */
7832 G.global_argv--; /* points to argv[i] of 'script' */
7833 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007834 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007835 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007836 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007837 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007838 goto final_return;
7839 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007840 /* Well, we cannot just declare interactiveness,
7841 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007842 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007843 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007844 case 's':
7845 /* "-s" means "read from stdin", but this is how we always
7846 * operate, so simply do nothing here. */
7847 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007848 case 'l':
7849 flags |= OPT_login;
7850 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007851#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007852 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007853 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007854 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007855 case '$': {
7856 unsigned long long empty_trap_mask;
7857
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007858 G.root_pid = bb_strtou(optarg, &optarg, 16);
7859 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007860 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7861 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007862 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7863 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007864 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007865 optarg++;
7866 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007867 optarg++;
7868 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7869 if (empty_trap_mask != 0) {
7870 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007871 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007872 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7873 for (sig = 1; sig < NSIG; sig++) {
7874 if (empty_trap_mask & (1LL << sig)) {
7875 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007876 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007877 }
7878 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007879 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007880# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007881 optarg++;
7882 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007883# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007884 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007885 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007886 case 'R':
7887 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007888 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007889 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007890# if ENABLE_HUSH_FUNCTIONS
7891 case 'F': {
7892 struct function *funcp = new_function(optarg);
7893 /* funcp->name is already set to optarg */
7894 /* funcp->body is set to NULL. It's a special case. */
7895 funcp->body_as_string = argv[optind];
7896 optind++;
7897 break;
7898 }
7899# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007900#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007901 case 'n':
7902 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007903 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007904 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007905 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007906#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007907 fprintf(stderr, "Usage: sh [FILE]...\n"
7908 " or: sh -c command [args]...\n\n");
7909 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007910#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007911 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007912#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007913 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007914 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007915
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007916 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7917 G.global_argc = argc - (optind - 1);
7918 G.global_argv = argv + (optind - 1);
7919 G.global_argv[0] = argv[0];
7920
Denys Vlasenkodea47882009-10-09 15:40:49 +02007921 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007922 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007923 G.root_ppid = getppid();
7924 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007925
7926 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007927 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007928 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007929 debug_printf("sourcing /etc/profile\n");
7930 input = fopen_for_read("/etc/profile");
7931 if (input != NULL) {
7932 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007933 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007934 parse_and_run_file(input);
7935 fclose(input);
7936 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007937 /* bash: after sourcing /etc/profile,
7938 * tries to source (in the given order):
7939 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007940 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007941 * bash also sources ~/.bash_logout on exit.
7942 * If called as sh, skips .bash_XXX files.
7943 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007944 }
7945
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007946 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007947 FILE *input;
7948 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007949 * "bash <script>" (which is never interactive (unless -i?))
7950 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007951 * If called as sh, does the same but with $ENV.
7952 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007953 G.global_argc--;
7954 G.global_argv++;
7955 debug_printf("running script '%s'\n", G.global_argv[0]);
7956 input = xfopen_for_read(G.global_argv[0]);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007957 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007958 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007959 parse_and_run_file(input);
7960#if ENABLE_FEATURE_CLEAN_UP
7961 fclose(input);
7962#endif
7963 goto final_return;
7964 }
7965
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007966 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007967 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007968 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007969
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007970 /* A shell is interactive if the '-i' flag was given,
7971 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007972 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007973 * no arguments remaining or the -s flag given
7974 * standard input is a terminal
7975 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007976 * Refer to Posix.2, the description of the 'sh' utility.
7977 */
7978#if ENABLE_HUSH_JOB
7979 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007980 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7981 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7982 if (G_saved_tty_pgrp < 0)
7983 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007984
7985 /* try to dup stdin to high fd#, >= 255 */
7986 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7987 if (G_interactive_fd < 0) {
7988 /* try to dup to any fd */
7989 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007990 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007991 /* give up */
7992 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007993 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007994 }
7995 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007996// TODO: track & disallow any attempts of user
7997// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007998 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007999 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008000 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008001 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008002
Mike Frysinger38478a62009-05-20 04:48:06 -04008003 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008004 /* If we were run as 'hush &', sleep until we are
8005 * in the foreground (tty pgrp == our pgrp).
8006 * If we get started under a job aware app (like bash),
8007 * make sure we are now in charge so we don't fight over
8008 * who gets the foreground */
8009 while (1) {
8010 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008011 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8012 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008013 break;
8014 /* send TTIN to ourself (should stop us) */
8015 kill(- shell_pgrp, SIGTTIN);
8016 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008017 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008018
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008019 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008020 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008021
Mike Frysinger38478a62009-05-20 04:48:06 -04008022 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008023 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008024 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008025 /* Put ourselves in our own process group
8026 * (bash, too, does this only if ctty is available) */
8027 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8028 /* Grab control of the terminal */
8029 tcsetpgrp(G_interactive_fd, getpid());
8030 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00008031 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00008032 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00008033 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008034 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008035 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008036 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008037#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008038 /* No job control compiled in, only prompt/line editing */
8039 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008040 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8041 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008042 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008043 G_interactive_fd = dup(STDIN_FILENO);
8044 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008045 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008046 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008047 }
8048 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008049 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008050 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008051 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008052 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008053#else
8054 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008055 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008056#endif
8057 /* bash:
8058 * if interactive but not a login shell, sources ~/.bashrc
8059 * (--norc turns this off, --rcfile <file> overrides)
8060 */
8061
8062 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008063 /* note: ash and hush share this string */
8064 printf("\n\n%s %s\n"
8065 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8066 "\n",
8067 bb_banner,
8068 "hush - the humble shell"
8069 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008070 }
8071
Denis Vlasenkof9375282009-04-05 19:13:39 +00008072 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008073
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008074 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008075 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008076}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008077
8078
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008079#if ENABLE_MSH
8080int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8081int msh_main(int argc, char **argv)
8082{
8083 //bb_error_msg("msh is deprecated, please use hush instead");
8084 return hush_main(argc, argv);
8085}
8086#endif
8087
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008088
8089/*
8090 * Built-ins
8091 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008092static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008093{
8094 return 0;
8095}
8096
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008097static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008098{
8099 int argc = 0;
8100 while (*argv) {
8101 argc++;
8102 argv++;
8103 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008104 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008105}
8106
8107static int FAST_FUNC builtin_test(char **argv)
8108{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008109 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008110}
8111
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008112static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008113{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008114 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008115}
8116
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008117#if ENABLE_PRINTF
8118static int FAST_FUNC builtin_printf(char **argv)
8119{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008120 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008121}
8122#endif
8123
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008124static char **skip_dash_dash(char **argv)
8125{
8126 argv++;
8127 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8128 argv++;
8129 return argv;
8130}
8131
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008132static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008133{
8134 int rcode = EXIT_SUCCESS;
8135
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008136 argv = skip_dash_dash(argv);
8137 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008138 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008139 /* bash:
8140 * eval "echo Hi; done" ("done" is syntax error):
8141 * "echo Hi" will not execute too.
8142 */
8143 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008144 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008145 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008146 }
8147 return rcode;
8148}
8149
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008150static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008151{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008152 const char *newdir;
8153
8154 argv = skip_dash_dash(argv);
8155 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008156 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008157 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008158 * bash says "bash: cd: HOME not set" and does nothing
8159 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008160 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008161 const char *home = get_local_var_value("HOME");
8162 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008163 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008164 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008165 /* Mimic bash message exactly */
8166 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008167 return EXIT_FAILURE;
8168 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008169 /* Read current dir (get_cwd(1) is inside) and set PWD.
8170 * Note: do not enforce exporting. If PWD was unset or unexported,
8171 * set it again, but do not export. bash does the same.
8172 */
8173 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008174 return EXIT_SUCCESS;
8175}
8176
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008177static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008178{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008179 argv = skip_dash_dash(argv);
8180 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008181 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008182
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008183 /* Careful: we can end up here after [v]fork. Do not restore
8184 * tty pgrp then, only top-level shell process does that */
8185 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8186 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8187
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008188 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008189 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008190 * and tcsetpgrp, and this is inherently racy.
8191 */
8192 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008193}
8194
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008195static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008196{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008197 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008198
8199 /* interactive bash:
8200 * # trap "echo EEE" EXIT
8201 * # exit
8202 * exit
8203 * There are stopped jobs.
8204 * (if there are _stopped_ jobs, running ones don't count)
8205 * # exit
8206 * exit
8207 # EEE (then bash exits)
8208 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008209 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008210 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008211
8212 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008213 argv = skip_dash_dash(argv);
8214 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008215 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008216 /* mimic bash: exit 123abc == exit 255 + error msg */
8217 xfunc_error_retval = 255;
8218 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008219 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008220}
8221
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008222static void print_escaped(const char *s)
8223{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008224 if (*s == '\'')
8225 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008226 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008227 const char *p = strchrnul(s, '\'');
8228 /* print 'xxxx', possibly just '' */
8229 printf("'%.*s'", (int)(p - s), s);
8230 if (*p == '\0')
8231 break;
8232 s = p;
8233 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008234 /* s points to '; print "'''...'''" */
8235 putchar('"');
8236 do putchar('\''); while (*++s == '\'');
8237 putchar('"');
8238 } while (*s);
8239}
8240
Denys Vlasenko295fef82009-06-03 12:47:26 +02008241#if !ENABLE_HUSH_LOCAL
8242#define helper_export_local(argv, exp, lvl) \
8243 helper_export_local(argv, exp)
8244#endif
8245static void helper_export_local(char **argv, int exp, int lvl)
8246{
8247 do {
8248 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008249 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008250
8251 /* So far we do not check that name is valid (TODO?) */
8252
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008253 if (*name_end == '\0') {
8254 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008255
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008256 vpp = get_ptr_to_local_var(name, name_end - name);
8257 var = vpp ? *vpp : NULL;
8258
Denys Vlasenko295fef82009-06-03 12:47:26 +02008259 if (exp == -1) { /* unexporting? */
8260 /* export -n NAME (without =VALUE) */
8261 if (var) {
8262 var->flg_export = 0;
8263 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8264 unsetenv(name);
8265 } /* else: export -n NOT_EXISTING_VAR: no-op */
8266 continue;
8267 }
8268 if (exp == 1) { /* exporting? */
8269 /* export NAME (without =VALUE) */
8270 if (var) {
8271 var->flg_export = 1;
8272 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8273 putenv(var->varstr);
8274 continue;
8275 }
8276 }
8277 /* Exporting non-existing variable.
8278 * bash does not put it in environment,
8279 * but remembers that it is exported,
8280 * and does put it in env when it is set later.
8281 * We just set it to "" and export. */
8282 /* Or, it's "local NAME" (without =VALUE).
8283 * bash sets the value to "". */
8284 name = xasprintf("%s=", name);
8285 } else {
8286 /* (Un)exporting/making local NAME=VALUE */
8287 name = xstrdup(name);
8288 }
8289 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8290 } while (*++argv);
8291}
8292
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008293static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008294{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008295 unsigned opt_unexport;
8296
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008297#if ENABLE_HUSH_EXPORT_N
8298 /* "!": do not abort on errors */
8299 opt_unexport = getopt32(argv, "!n");
8300 if (opt_unexport == (uint32_t)-1)
8301 return EXIT_FAILURE;
8302 argv += optind;
8303#else
8304 opt_unexport = 0;
8305 argv++;
8306#endif
8307
8308 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008309 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008310 if (e) {
8311 while (*e) {
8312#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008313 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008314#else
8315 /* ash emits: export VAR='VAL'
8316 * bash: declare -x VAR="VAL"
8317 * we follow ash example */
8318 const char *s = *e++;
8319 const char *p = strchr(s, '=');
8320
8321 if (!p) /* wtf? take next variable */
8322 continue;
8323 /* export var= */
8324 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008325 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008326 putchar('\n');
8327#endif
8328 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008329 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008330 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008331 return EXIT_SUCCESS;
8332 }
8333
Denys Vlasenko295fef82009-06-03 12:47:26 +02008334 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008335
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008336 return EXIT_SUCCESS;
8337}
8338
Denys Vlasenko295fef82009-06-03 12:47:26 +02008339#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008340static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008341{
8342 if (G.func_nest_level == 0) {
8343 bb_error_msg("%s: not in a function", argv[0]);
8344 return EXIT_FAILURE; /* bash compat */
8345 }
8346 helper_export_local(argv, 0, G.func_nest_level);
8347 return EXIT_SUCCESS;
8348}
8349#endif
8350
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008351static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008352{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008353 int sig;
8354 char *new_cmd;
8355
8356 if (!G.traps)
8357 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8358
8359 argv++;
8360 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008361 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008362 /* No args: print all trapped */
8363 for (i = 0; i < NSIG; ++i) {
8364 if (G.traps[i]) {
8365 printf("trap -- ");
8366 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008367 /* note: bash adds "SIG", but only if invoked
8368 * as "bash". If called as "sh", or if set -o posix,
8369 * then it prints short signal names.
8370 * We are printing short names: */
8371 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008372 }
8373 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008374 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008375 return EXIT_SUCCESS;
8376 }
8377
8378 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008379 /* If first arg is a number: reset all specified signals */
8380 sig = bb_strtou(*argv, NULL, 10);
8381 if (errno == 0) {
8382 int ret;
8383 process_sig_list:
8384 ret = EXIT_SUCCESS;
8385 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008386 sighandler_t handler;
8387
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008388 sig = get_signum(*argv++);
8389 if (sig < 0 || sig >= NSIG) {
8390 ret = EXIT_FAILURE;
8391 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008392 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008393 continue;
8394 }
8395
8396 free(G.traps[sig]);
8397 G.traps[sig] = xstrdup(new_cmd);
8398
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008399 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008400 get_signame(sig), sig, G.traps[sig]);
8401
8402 /* There is no signal for 0 (EXIT) */
8403 if (sig == 0)
8404 continue;
8405
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008406 if (new_cmd)
8407 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8408 else
8409 /* We are removing trap handler */
8410 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02008411 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008412 }
8413 return ret;
8414 }
8415
8416 if (!argv[1]) { /* no second arg */
8417 bb_error_msg("trap: invalid arguments");
8418 return EXIT_FAILURE;
8419 }
8420
8421 /* First arg is "-": reset all specified to default */
8422 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8423 /* Everything else: set arg as signal handler
8424 * (includes "" case, which ignores signal) */
8425 if (argv[0][0] == '-') {
8426 if (argv[0][1] == '\0') { /* "-" */
8427 /* new_cmd remains NULL: "reset these sigs" */
8428 goto reset_traps;
8429 }
8430 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8431 argv++;
8432 }
8433 /* else: "-something", no special meaning */
8434 }
8435 new_cmd = *argv;
8436 reset_traps:
8437 argv++;
8438 goto process_sig_list;
8439}
8440
Mike Frysinger93cadc22009-05-27 17:06:25 -04008441/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008442static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008443{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008444 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008445
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008446 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008447 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008448 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008449
8450 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008451 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008452 type = "an alias";*/
8453#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008454 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008455 type = "a function";
8456#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008457 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008458 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008459 else if ((path = find_in_path(*argv)) != NULL)
8460 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008461 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008462 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008463 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008464 continue;
8465 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008466
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008467 printf("%s is %s\n", *argv, type);
8468 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008469 }
8470
8471 return ret;
8472}
8473
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008474#if ENABLE_HUSH_JOB
8475/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008476static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008477{
8478 int i, jobnum;
8479 struct pipe *pi;
8480
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008481 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008482 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008483
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008484 /* If they gave us no args, assume they want the last backgrounded task */
8485 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008486 for (pi = G.job_list; pi; pi = pi->next) {
8487 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008488 goto found;
8489 }
8490 }
8491 bb_error_msg("%s: no current job", argv[0]);
8492 return EXIT_FAILURE;
8493 }
8494 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8495 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8496 return EXIT_FAILURE;
8497 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008498 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008499 if (pi->jobid == jobnum) {
8500 goto found;
8501 }
8502 }
8503 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8504 return EXIT_FAILURE;
8505 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008506 /* TODO: bash prints a string representation
8507 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008508 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008509 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008510 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008511 }
8512
8513 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008514 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8515 for (i = 0; i < pi->num_cmds; i++) {
8516 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8517 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008518 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008519 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008520
8521 i = kill(- pi->pgrp, SIGCONT);
8522 if (i < 0) {
8523 if (errno == ESRCH) {
8524 delete_finished_bg_job(pi);
8525 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008526 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008527 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008528 }
8529
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008530 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008531 remove_bg_job(pi);
8532 return checkjobs_and_fg_shell(pi);
8533 }
8534 return EXIT_SUCCESS;
8535}
8536#endif
8537
8538#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008539static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008540{
8541 const struct built_in_command *x;
8542
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008543 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008544 "Built-in commands:\n"
8545 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008546 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008547 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008548 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008549 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008550 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008551 return EXIT_SUCCESS;
8552}
8553#endif
8554
8555#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008556static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008557{
8558 struct pipe *job;
8559 const char *status_string;
8560
Denis Vlasenko87a86552008-07-29 19:43:10 +00008561 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008562 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008563 status_string = "Stopped";
8564 else
8565 status_string = "Running";
8566
8567 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8568 }
8569 return EXIT_SUCCESS;
8570}
8571#endif
8572
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008573#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008574static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008575{
8576 void *p;
8577 unsigned long l;
8578
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008579# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008580 /* Optional. Reduces probability of false positives */
8581 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008582# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008583 /* Crude attempt to find where "free memory" starts,
8584 * sans fragmentation. */
8585 p = malloc(240);
8586 l = (unsigned long)p;
8587 free(p);
8588 p = malloc(3400);
8589 if (l < (unsigned long)p) l = (unsigned long)p;
8590 free(p);
8591
8592 if (!G.memleak_value)
8593 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008594
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008595 l -= G.memleak_value;
8596 if ((long)l < 0)
8597 l = 0;
8598 l /= 1024;
8599 if (l > 127)
8600 l = 127;
8601
8602 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8603 return l;
8604}
8605#endif
8606
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008607static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008608{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008609 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008610 return EXIT_SUCCESS;
8611}
8612
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008613/* Interruptibility of read builtin in bash
8614 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8615 *
8616 * Empty trap makes read ignore corresponding signal, for any signal.
8617 *
8618 * SIGINT:
8619 * - terminates non-interactive shell;
8620 * - interrupts read in interactive shell;
8621 * if it has non-empty trap:
8622 * - executes trap and returns to command prompt in interactive shell;
8623 * - executes trap and returns to read in non-interactive shell;
8624 * SIGTERM:
8625 * - is ignored (does not interrupt) read in interactive shell;
8626 * - terminates non-interactive shell;
8627 * if it has non-empty trap:
8628 * - executes trap and returns to read;
8629 * SIGHUP:
8630 * - terminates shell (regardless of interactivity);
8631 * if it has non-empty trap:
8632 * - executes trap and returns to read;
8633 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008634static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008635{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008636 const char *r;
8637 char *opt_n = NULL;
8638 char *opt_p = NULL;
8639 char *opt_t = NULL;
8640 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008641 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01008642 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008643
Denys Vlasenko03dad222010-01-12 23:29:57 +01008644 /* "!": do not abort on errors.
8645 * Option string must start with "sr" to match BUILTIN_READ_xxx
8646 */
8647 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8648 if (read_flags == (uint32_t)-1)
8649 return EXIT_FAILURE;
8650 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008651 ifs = get_local_var_value("IFS"); /* can be NULL */
8652
8653 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01008654 r = shell_builtin_read(set_local_var_from_halves,
8655 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008656 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01008657 read_flags,
8658 opt_n,
8659 opt_p,
8660 opt_t,
8661 opt_u
8662 );
8663
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008664 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008665 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008666 if (sig && sig != SIGINT)
8667 goto again;
8668 }
8669
Denys Vlasenko03dad222010-01-12 23:29:57 +01008670 if ((uintptr_t)r > 1) {
8671 bb_error_msg("%s", r);
8672 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008673 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008674
Denys Vlasenko03dad222010-01-12 23:29:57 +01008675 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008676}
8677
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008678/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8679 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008680 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008681 * set [-abCefhmnuvx] [-o option] [argument...]
8682 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008683 * set -- [argument...]
8684 * set -o
8685 * set +o
8686 * Implementations shall support the options in both their hyphen and
8687 * plus-sign forms. These options can also be specified as options to sh.
8688 * Examples:
8689 * Write out all variables and their values: set
8690 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8691 * Turn on the -x and -v options: set -xv
8692 * Unset all positional parameters: set --
8693 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8694 * Set the positional parameters to the expansion of x, even if x expands
8695 * with a leading '-' or '+': set -- $x
8696 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008697 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008698 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008699static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008700{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008701 int n;
8702 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008703 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008704
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008705 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008706 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008707 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008708 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008709 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008710 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008711
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008712 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008713 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008714 ++argv;
8715 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008716 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008717 if (arg[0] != '+' && arg[0] != '-')
8718 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008719 for (n = 1; arg[n]; ++n) {
8720 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008721 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008722 if (arg[n] == 'o' && argv[1])
8723 argv++;
8724 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008725 } while ((arg = *++argv) != NULL);
8726 /* Now argv[0] is 1st argument */
8727
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008728 if (arg == NULL)
8729 return EXIT_SUCCESS;
8730 set_argv:
8731
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008732 /* NB: G.global_argv[0] ($0) is never freed/changed */
8733 g_argv = G.global_argv;
8734 if (G.global_args_malloced) {
8735 pp = g_argv;
8736 while (*++pp)
8737 free(*pp);
8738 g_argv[1] = NULL;
8739 } else {
8740 G.global_args_malloced = 1;
8741 pp = xzalloc(sizeof(pp[0]) * 2);
8742 pp[0] = g_argv[0]; /* retain $0 */
8743 g_argv = pp;
8744 }
8745 /* This realloc's G.global_argv */
8746 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8747
8748 n = 1;
8749 while (*++pp)
8750 n++;
8751 G.global_argc = n;
8752
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008753 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008754
8755 /* Nothing known, so abort */
8756 error:
8757 bb_error_msg("set: %s: invalid option", arg);
8758 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008759}
8760
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008761static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008762{
8763 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008764 argv = skip_dash_dash(argv);
8765 if (argv[0]) {
8766 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008767 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008768 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008769 if (G.global_args_malloced) {
8770 int m = 1;
8771 while (m <= n)
8772 free(G.global_argv[m++]);
8773 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008774 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008775 memmove(&G.global_argv[1], &G.global_argv[n+1],
8776 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008777 return EXIT_SUCCESS;
8778 }
8779 return EXIT_FAILURE;
8780}
8781
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008782static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008783{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008784 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008785 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008786 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008787#if ENABLE_HUSH_FUNCTIONS
8788 smallint sv_flg;
8789#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008790
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008791 argv = skip_dash_dash(argv);
8792 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008793 if (!filename) {
8794 /* bash says: "bash: .: filename argument required" */
8795 return 2; /* bash compat */
8796 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008797 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008798 if (!strchr(filename, '/')) {
8799 arg_path = find_in_path(filename);
8800 if (arg_path)
8801 filename = arg_path;
8802 }
8803 input = fopen_or_warn(filename, "r");
8804 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008805 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008806 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008807 return EXIT_FAILURE;
8808 }
8809 close_on_exec_on(fileno(input));
8810
Mike Frysinger885b6f22009-04-18 21:04:25 +00008811#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008812 sv_flg = G.flag_return_in_progress;
8813 /* "we are inside sourced file, ok to use return" */
8814 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008815#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008816 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008817
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008818 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008819 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008820
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008821 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008822#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008823 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008824#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008825
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008826 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008827}
8828
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008829static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008830{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008831 int rc;
8832 mode_t mask;
8833
8834 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008835 argv = skip_dash_dash(argv);
8836 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008837 mode_t old_mask = mask;
8838
8839 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008840 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008841 mask ^= 0777;
8842 if (rc == 0) {
8843 mask = old_mask;
8844 /* bash messages:
8845 * bash: umask: 'q': invalid symbolic mode operator
8846 * bash: umask: 999: octal number out of range
8847 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008848 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008849 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008850 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008851 rc = 1;
8852 /* Mimic bash */
8853 printf("%04o\n", (unsigned) mask);
8854 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008855 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008856 umask(mask);
8857
8858 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008859}
8860
Mike Frysingerd690f682009-03-30 06:50:54 +00008861/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008862static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008863{
Mike Frysingerd690f682009-03-30 06:50:54 +00008864 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008865 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008866
Denis Vlasenko28e67962009-04-26 23:22:40 +00008867 /* "!": do not abort on errors */
8868 /* "+": stop at 1st non-option */
8869 opts = getopt32(argv, "!+vf");
8870 if (opts == (unsigned)-1)
8871 return EXIT_FAILURE;
8872 if (opts == 3) {
8873 bb_error_msg("unset: -v and -f are exclusive");
8874 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008875 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008876 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008877
8878 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008879 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008880 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008881 if (unset_local_var(*argv)) {
8882 /* unset <nonexistent_var> doesn't fail.
8883 * Error is when one tries to unset RO var.
8884 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008885 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008886 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008887 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008888#if ENABLE_HUSH_FUNCTIONS
8889 else {
8890 unset_func(*argv);
8891 }
8892#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008893 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008894 }
8895 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008896}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008897
Mike Frysinger56bdea12009-03-28 20:01:58 +00008898/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008899static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008900{
8901 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008902 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008903
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008904 argv = skip_dash_dash(argv);
8905 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008906 /* Don't care about wait results */
8907 /* Note 1: must wait until there are no more children */
8908 /* Note 2: must be interruptible */
8909 /* Examples:
8910 * $ sleep 3 & sleep 6 & wait
8911 * [1] 30934 sleep 3
8912 * [2] 30935 sleep 6
8913 * [1] Done sleep 3
8914 * [2] Done sleep 6
8915 * $ sleep 3 & sleep 6 & wait
8916 * [1] 30936 sleep 3
8917 * [2] 30937 sleep 6
8918 * [1] Done sleep 3
8919 * ^C <-- after ~4 sec from keyboard
8920 * $
8921 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008922 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008923 int sig;
8924 sigset_t oldset, allsigs;
8925
8926 /* waitpid is not interruptible by SA_RESTARTed
8927 * signals which we use. Thus, this ugly dance:
8928 */
8929
8930 /* Make sure possible SIGCHLD is stored in kernel's
8931 * pending signal mask before we call waitpid.
8932 * Or else we may race with SIGCHLD, lose it,
8933 * and get stuck in sigwaitinfo...
8934 */
8935 sigfillset(&allsigs);
8936 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
8937
8938 if (!sigisemptyset(&G.pending_set)) {
8939 /* Crap! we raced with some signal! */
8940 // sig = 0;
8941 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008942 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008943
8944 checkjobs(NULL); /* waitpid(WNOHANG) inside */
8945 if (errno == ECHILD) {
8946 sigprocmask(SIG_SETMASK, &oldset, NULL);
8947 break;
8948 }
8949
8950 /* Wait for SIGCHLD or any other signal */
8951 //sig = sigwaitinfo(&allsigs, NULL);
8952 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
8953 /* Note: sigsuspend invokes signal handler */
8954 sigsuspend(&oldset);
8955 restore:
8956 sigprocmask(SIG_SETMASK, &oldset, NULL);
8957
8958 /* So, did we get a signal? */
8959 //if (sig > 0)
8960 // raise(sig); /* run handler */
8961 sig = check_and_run_traps();
8962 if (sig /*&& sig != SIGCHLD - always true */) {
8963 /* see note 2 */
8964 ret = 128 + sig;
8965 break;
8966 }
8967 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008968 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008969 return ret;
8970 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008971
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008972 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008973 while (*argv) {
8974 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008975 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008976 /* mimic bash message */
8977 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008978 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008979 }
8980 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008981 if (WIFSIGNALED(status))
8982 ret = 128 + WTERMSIG(status);
8983 else if (WIFEXITED(status))
8984 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008985 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008986 ret = EXIT_FAILURE;
8987 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008988 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008989 ret = 127;
8990 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008991 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008992 }
8993
8994 return ret;
8995}
8996
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008997#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8998static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8999{
9000 if (argv[1]) {
9001 def = bb_strtou(argv[1], NULL, 10);
9002 if (errno || def < def_min || argv[2]) {
9003 bb_error_msg("%s: bad arguments", argv[0]);
9004 def = UINT_MAX;
9005 }
9006 }
9007 return def;
9008}
9009#endif
9010
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009011#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009012static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009013{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009014 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009015 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009016 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009017 return EXIT_SUCCESS; /* bash compat */
9018 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009019 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009020
9021 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9022 if (depth == UINT_MAX)
9023 G.flag_break_continue = BC_BREAK;
9024 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009025 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009026
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009027 return EXIT_SUCCESS;
9028}
9029
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009030static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009031{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009032 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9033 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009034}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009035#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009036
9037#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009038static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009039{
9040 int rc;
9041
9042 if (G.flag_return_in_progress != -1) {
9043 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9044 return EXIT_FAILURE; /* bash compat */
9045 }
9046
9047 G.flag_return_in_progress = 1;
9048
9049 /* bash:
9050 * out of range: wraps around at 256, does not error out
9051 * non-numeric param:
9052 * f() { false; return qwe; }; f; echo $?
9053 * bash: return: qwe: numeric argument required <== we do this
9054 * 255 <== we also do this
9055 */
9056 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9057 return rc;
9058}
9059#endif