blob: 503cb770bedc8874f7624e1f4b0ebbe67c572d76 [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
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200452#ifndef debug_printf_parse
453static const char *const assignment_flag[] = {
454 "MAYBE_ASSIGNMENT",
455 "DEFINITELY_ASSIGNMENT",
456 "NOT_ASSIGNMENT",
457 "WORD_IS_KEYWORD",
458};
459#endif
460
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000461typedef struct in_str {
462 const char *p;
463 /* eof_flag=1: last char in ->p is really an EOF */
464 char eof_flag; /* meaningless if ->p == NULL */
465 char peek_buf[2];
466#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000467 smallint promptmode; /* 0: PS1, 1: PS2 */
468#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200469 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000470 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200471 int (*get) (struct in_str *) FAST_FUNC;
472 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000473} in_str;
474#define i_getch(input) ((input)->get(input))
475#define i_peek(input) ((input)->peek(input))
476
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200477/* The descrip member of this structure is only used to make
478 * debugging output pretty */
479static const struct {
480 int mode;
481 signed char default_fd;
482 char descrip[3];
483} redir_table[] = {
484 { O_RDONLY, 0, "<" },
485 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
486 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
487 { O_CREAT|O_RDWR, 1, "<>" },
488 { O_RDONLY, 0, "<<" },
489/* Should not be needed. Bogus default_fd helps in debugging */
490/* { O_RDONLY, 77, "<<" }, */
491};
492
Eric Andersen25f27032001-04-26 23:22:31 +0000493struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000494 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000495 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000496 int rd_fd; /* fd to redirect */
497 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
498 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000499 smallint rd_type; /* (enum redir_type) */
500 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000501 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200502 * bit 0: do we need to trim leading tabs?
503 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000504 */
Eric Andersen25f27032001-04-26 23:22:31 +0000505};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000506typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200507 REDIRECT_INPUT = 0,
508 REDIRECT_OVERWRITE = 1,
509 REDIRECT_APPEND = 2,
510 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000511 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200512 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000513
514 REDIRFD_CLOSE = -3,
515 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000516 REDIRFD_TO_FILE = -1,
517 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000518
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000519 HEREDOC_SKIPTABS = 1,
520 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000521} redir_type;
522
Eric Andersen25f27032001-04-26 23:22:31 +0000523
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000524struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000525 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000526 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000527 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200528 smallint cmd_type; /* CMD_xxx */
529#define CMD_NORMAL 0
530#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200531#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200532/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200533# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000534#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200535#if ENABLE_HUSH_FUNCTIONS
536# define CMD_FUNCDEF 3
537#endif
538
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100539 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200540 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
541 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000542#if !BB_MMU
543 char *group_as_string;
544#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000545#if ENABLE_HUSH_FUNCTIONS
546 struct function *child_func;
547/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200548 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000549 * When we execute "f1() {a;}" cmd, we create new function and clear
550 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200551 * When we execute "f1() {b;}", we notice that f1 exists,
552 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000553 * we put those fields back into cmd->xxx
554 * (struct function has ->parent_cmd ptr to facilitate that).
555 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
556 * Without this trick, loop would execute a;b;b;b;...
557 * instead of correct sequence a;b;a;b;...
558 * When command is freed, it severs the link
559 * (sets ->child_func->parent_cmd to NULL).
560 */
561#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000562 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000563/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
564 * and on execution these are substituted with their values.
565 * Substitution can make _several_ words out of one argv[n]!
566 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000567 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000568 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000569 struct redir_struct *redirects; /* I/O redirections */
570};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000571/* Is there anything in this command at all? */
572#define IS_NULL_CMD(cmd) \
573 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
574
Eric Andersen25f27032001-04-26 23:22:31 +0000575struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000576 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000577 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000578 int alive_cmds; /* number of commands running (not exited) */
579 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000580#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000581 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000582 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000583 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000584#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000585 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000586 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000587 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
588 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000589};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000590typedef enum pipe_style {
591 PIPE_SEQ = 1,
592 PIPE_AND = 2,
593 PIPE_OR = 3,
594 PIPE_BG = 4,
595} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000596/* Is there anything in this pipe at all? */
597#define IS_NULL_PIPE(pi) \
598 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000599
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000600/* This holds pointers to the various results of parsing */
601struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000602 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000603 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000604 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000605 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000606 /* last command in pipe (being constructed right now) */
607 struct command *command;
608 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000609 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000610#if !BB_MMU
611 o_string as_string;
612#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000613#if HAS_KEYWORDS
614 smallint ctx_res_w;
615 smallint ctx_inverted; /* "! cmd | cmd" */
616#if ENABLE_HUSH_CASE
617 smallint ctx_dsemicolon; /* ";;" seen */
618#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000619 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
620 int old_flag;
621 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000622 * example: "if pipe1; pipe2; then pipe3; fi"
623 * when we see "if" or "then", we malloc and copy current context,
624 * and make ->stack point to it. then we parse pipeN.
625 * when closing "then" / fi" / whatever is found,
626 * we move list_head into ->stack->command->group,
627 * copy ->stack into current context, and delete ->stack.
628 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000629 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000630 struct parse_context *stack;
631#endif
632};
633
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000634/* On program start, environ points to initial environment.
635 * putenv adds new pointers into it, unsetenv removes them.
636 * Neither of these (de)allocates the strings.
637 * setenv allocates new strings in malloc space and does putenv,
638 * and thus setenv is unusable (leaky) for shell's purposes */
639#define setenv(...) setenv_is_leaky_dont_use()
640struct variable {
641 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000642 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200643#if ENABLE_HUSH_LOCAL
644 unsigned func_nest_level;
645#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000646 int max_len; /* if > 0, name is part of initial env; else name is malloced */
647 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000648 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000649};
650
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000651enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000652 BC_BREAK = 1,
653 BC_CONTINUE = 2,
654};
655
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000656#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000657struct function {
658 struct function *next;
659 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000660 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000661 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200662# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000663 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200664# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000665};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000666#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000667
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000668
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100669/* set -/+o OPT support. (TODO: make it optional)
670 * bash supports the following opts:
671 * allexport off
672 * braceexpand on
673 * emacs on
674 * errexit off
675 * errtrace off
676 * functrace off
677 * hashall on
678 * histexpand off
679 * history on
680 * ignoreeof off
681 * interactive-comments on
682 * keyword off
683 * monitor on
684 * noclobber off
685 * noexec off
686 * noglob off
687 * nolog off
688 * notify off
689 * nounset off
690 * onecmd off
691 * physical off
692 * pipefail off
693 * posix off
694 * privileged off
695 * verbose off
696 * vi off
697 * xtrace off
698 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800699static const char o_opt_strings[] ALIGN1 =
700 "pipefail\0"
701 "noexec\0"
702#if ENABLE_HUSH_MODE_X
703 "xtrace\0"
704#endif
705 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100706enum {
707 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800708 OPT_O_NOEXEC,
709#if ENABLE_HUSH_MODE_X
710 OPT_O_XTRACE,
711#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100712 NUM_OPT_O
713};
714
715
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000716/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000717/* Sorted roughly by size (smaller offsets == smaller code) */
718struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000719 /* interactive_fd != 0 means we are an interactive shell.
720 * If we are, then saved_tty_pgrp can also be != 0, meaning
721 * that controlling tty is available. With saved_tty_pgrp == 0,
722 * job control still works, but terminal signals
723 * (^C, ^Z, ^Y, ^\) won't work at all, and background
724 * process groups can only be created with "cmd &".
725 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
726 * to give tty to the foreground process group,
727 * and will take it back when the group is stopped (^Z)
728 * or killed (^C).
729 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000730#if ENABLE_HUSH_INTERACTIVE
731 /* 'interactive_fd' is a fd# open to ctty, if we have one
732 * _AND_ if we decided to act interactively */
733 int interactive_fd;
734 const char *PS1;
735 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000736# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000737#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000738# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000739#endif
740#if ENABLE_FEATURE_EDITING
741 line_input_t *line_input_state;
742#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000743 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200744 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000745 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200746#if ENABLE_HUSH_RANDOM_SUPPORT
747 random_t random_gen;
748#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000749#if ENABLE_HUSH_JOB
750 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000751 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000752 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000753 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400754# define G_saved_tty_pgrp (G.saved_tty_pgrp)
755#else
756# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000757#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100758 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100759#if ENABLE_HUSH_MODE_X
760# define G_x_mode (G.o_opt[OPT_O_XTRACE])
761#else
762# define G_x_mode 0
763#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000764 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000765#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000766 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000767#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000768#if ENABLE_HUSH_FUNCTIONS
769 /* 0: outside of a function (or sourced file)
770 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000771 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000772 */
773 smallint flag_return_in_progress;
774#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000775 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000776 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000777 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000778 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000779 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000780 /* how many non-NULL argv's we have. NB: $# + 1 */
781 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000782 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000783#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000784 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000785#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000786#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000787 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000788 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000789#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000790 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000791 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200792 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200793 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000794#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000795 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200796# if ENABLE_HUSH_LOCAL
797 struct variable **shadowed_vars_pp;
798 unsigned func_nest_level;
799# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000800#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000801 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200802#if ENABLE_HUSH_FAST
803 unsigned count_SIGCHLD;
804 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200805 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200806#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +0200807 /* Which signals have non-DFL handler (even with no traps set)?
808 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200809 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200810 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200811 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200812 * Other than these two times, never modified.
813 */
814 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200815#if ENABLE_HUSH_JOB
816 unsigned fatal_sig_mask;
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200817# define G_fatal_sig_mask G.fatal_sig_mask
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200818#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200819# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200820#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000821 char **traps; /* char *traps[NSIG] */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200822 sigset_t pending_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000823#if HUSH_DEBUG
824 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000825 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000826#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200827 struct sigaction sa;
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200828 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000829};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000830#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000831/* Not #defining name to G.name - this quickly gets unwieldy
832 * (too many defines). Also, I actually prefer to see when a variable
833 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000834#define INIT_G() do { \
835 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200836 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
837 sigfillset(&G.sa.sa_mask); \
838 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000839} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000840
841
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000842/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200843static int builtin_cd(char **argv) FAST_FUNC;
844static int builtin_echo(char **argv) FAST_FUNC;
845static int builtin_eval(char **argv) FAST_FUNC;
846static int builtin_exec(char **argv) FAST_FUNC;
847static int builtin_exit(char **argv) FAST_FUNC;
848static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000849#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200850static int builtin_fg_bg(char **argv) FAST_FUNC;
851static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000852#endif
853#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200854static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000855#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200856#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200857static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200858#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000859#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200860static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000861#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400862#if ENABLE_PRINTF
863static int builtin_printf(char **argv) FAST_FUNC;
864#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200865static int builtin_pwd(char **argv) FAST_FUNC;
866static int builtin_read(char **argv) FAST_FUNC;
867static int builtin_set(char **argv) FAST_FUNC;
868static int builtin_shift(char **argv) FAST_FUNC;
869static int builtin_source(char **argv) FAST_FUNC;
870static int builtin_test(char **argv) FAST_FUNC;
871static int builtin_trap(char **argv) FAST_FUNC;
872static int builtin_type(char **argv) FAST_FUNC;
873static int builtin_true(char **argv) FAST_FUNC;
874static int builtin_umask(char **argv) FAST_FUNC;
875static int builtin_unset(char **argv) FAST_FUNC;
876static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000877#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200878static int builtin_break(char **argv) FAST_FUNC;
879static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000880#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000881#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200882static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000883#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000884
885/* Table of built-in functions. They can be forked or not, depending on
886 * context: within pipes, they fork. As simple commands, they do not.
887 * When used in non-forking context, they can change global variables
888 * in the parent shell process. If forked, of course they cannot.
889 * For example, 'unset foo | whatever' will parse and run, but foo will
890 * still be set at the end. */
891struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100892 const char *b_cmd;
893 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000894#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100895 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200896# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000897#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200898# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000899#endif
900};
901
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200902static const struct built_in_command bltins1[] = {
903 BLTIN("." , builtin_source , "Run commands in a file"),
904 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000905#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200906 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000907#endif
908#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200909 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000910#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200911 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000912#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200913 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000914#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200915 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
916 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
917 BLTIN("exit" , builtin_exit , "Exit"),
918 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000919#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200920 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000921#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000922#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200923 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000924#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000925#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200926 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000927#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200928#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200929 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200930#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000931#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200932 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000933#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200934 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000935#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200936 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000937#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200938 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
939 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200940#if ENABLE_HUSH_BASH_COMPAT
941 BLTIN("source" , builtin_source , "Run commands in a file"),
942#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200943 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100944 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100945 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200946 BLTIN("umask" , builtin_umask , "Set file creation mask"),
947 BLTIN("unset" , builtin_unset , "Unset variables"),
948 BLTIN("wait" , builtin_wait , "Wait for process"),
949};
950/* For now, echo and test are unconditionally enabled.
951 * Maybe make it configurable? */
952static const struct built_in_command bltins2[] = {
953 BLTIN("[" , builtin_test , NULL),
954 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400955#if ENABLE_PRINTF
956 BLTIN("printf" , builtin_printf , NULL),
957#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200958 BLTIN("pwd" , builtin_pwd , NULL),
959 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000960};
961
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000962
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000963/* Debug printouts.
964 */
965#if HUSH_DEBUG
966/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100967# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000968# define debug_enter() (G.debug_indent++)
969# define debug_leave() (G.debug_indent--)
970#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200971# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000972# define debug_enter() ((void)0)
973# define debug_leave() ((void)0)
974#endif
975
976#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100977# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000978#endif
979
980#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100981# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000982#endif
983
984#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100985#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000986#endif
987
988#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100989# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000990#endif
991
992#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100993# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000994# define DEBUG_JOBS 1
995#else
996# define DEBUG_JOBS 0
997#endif
998
999#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001000# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001001# define DEBUG_EXPAND 1
1002#else
1003# define DEBUG_EXPAND 0
1004#endif
1005
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001006#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001007# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001008#endif
1009
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001010#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001011# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001012# define DEBUG_GLOB 1
1013#else
1014# define DEBUG_GLOB 0
1015#endif
1016
1017#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001018# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001019#endif
1020
1021#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001022# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001023#endif
1024
1025#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001026# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001027# define DEBUG_CLEAN 1
1028#else
1029# define DEBUG_CLEAN 0
1030#endif
1031
1032#if DEBUG_EXPAND
1033static void debug_print_strings(const char *prefix, char **vv)
1034{
1035 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001036 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001037 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001038 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001039}
1040#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001041# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001042#endif
1043
1044
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001045/* Leak hunting. Use hush_leaktool.sh for post-processing.
1046 */
1047#if LEAK_HUNTING
1048static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001049{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001050 void *ptr = xmalloc((size + 0xff) & ~0xff);
1051 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1052 return ptr;
1053}
1054static void *xxrealloc(int lineno, void *ptr, size_t size)
1055{
1056 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1057 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1058 return ptr;
1059}
1060static char *xxstrdup(int lineno, const char *str)
1061{
1062 char *ptr = xstrdup(str);
1063 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1064 return ptr;
1065}
1066static void xxfree(void *ptr)
1067{
1068 fdprintf(2, "free %p\n", ptr);
1069 free(ptr);
1070}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001071# define xmalloc(s) xxmalloc(__LINE__, s)
1072# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1073# define xstrdup(s) xxstrdup(__LINE__, s)
1074# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001075#endif
1076
1077
1078/* Syntax and runtime errors. They always abort scripts.
1079 * In interactive use they usually discard unparsed and/or unexecuted commands
1080 * and return to the prompt.
1081 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1082 */
1083#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001084# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001085# define syntax_error(lineno, msg) syntax_error(msg)
1086# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1087# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1088# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1089# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001090#endif
1091
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001092static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001093{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001094 va_list p;
1095
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001096#if HUSH_DEBUG >= 2
1097 bb_error_msg("hush.c:%u", lineno);
1098#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001099 va_start(p, fmt);
1100 bb_verror_msg(fmt, p, NULL);
1101 va_end(p);
1102 if (!G_interactive_fd)
1103 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001104}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001105
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001106static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001107{
1108 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001109 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001110 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001111 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001112}
1113
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001114static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001115{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001116 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001117}
1118
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001119static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001120{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001121 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001122}
1123
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001124static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001125{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001126 char msg[2] = { ch, '\0' };
1127 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001128}
1129
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001130static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001131{
1132 char msg[2];
1133 msg[0] = ch;
1134 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001135 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001136}
1137
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001138#if HUSH_DEBUG < 2
1139# undef die_if_script
1140# undef syntax_error
1141# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001142# undef syntax_error_unterm_ch
1143# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001144# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001145#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001146# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001147# define syntax_error(msg) syntax_error(__LINE__, msg)
1148# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1149# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1150# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1151# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001152#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001153
Denis Vlasenko552433b2009-04-04 19:29:21 +00001154
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001155#if ENABLE_HUSH_INTERACTIVE
1156static void cmdedit_update_prompt(void);
1157#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001158# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001159#endif
1160
1161
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001162/* Utility functions
1163 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001164/* Replace each \x with x in place, return ptr past NUL. */
1165static char *unbackslash(char *src)
1166{
Denys Vlasenko71885402009-09-24 01:44:13 +02001167 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001168 while (1) {
1169 if (*src == '\\')
1170 src++;
1171 if ((*dst++ = *src++) == '\0')
1172 break;
1173 }
1174 return dst;
1175}
1176
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001177static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001178{
1179 int i;
1180 unsigned count1;
1181 unsigned count2;
1182 char **v;
1183
1184 v = strings;
1185 count1 = 0;
1186 if (v) {
1187 while (*v) {
1188 count1++;
1189 v++;
1190 }
1191 }
1192 count2 = 0;
1193 v = add;
1194 while (*v) {
1195 count2++;
1196 v++;
1197 }
1198 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1199 v[count1 + count2] = NULL;
1200 i = count2;
1201 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001202 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001203 return v;
1204}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001205#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001206static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1207{
1208 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1209 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1210 return ptr;
1211}
1212#define add_strings_to_strings(strings, add, need_to_dup) \
1213 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1214#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001215
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001216/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001217static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001218{
1219 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001220 v[0] = add;
1221 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001222 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001223}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001224#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001225static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1226{
1227 char **ptr = add_string_to_strings(strings, add);
1228 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1229 return ptr;
1230}
1231#define add_string_to_strings(strings, add) \
1232 xx_add_string_to_strings(__LINE__, strings, add)
1233#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001234
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001235static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001236{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001237 char **v;
1238
1239 if (!strings)
1240 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001241 v = strings;
1242 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001243 free(*v);
1244 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001245 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001246 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001247}
1248
Denis Vlasenko76d50412008-06-10 16:19:39 +00001249
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001250/* Helpers for setting new $n and restoring them back
1251 */
1252typedef struct save_arg_t {
1253 char *sv_argv0;
1254 char **sv_g_argv;
1255 int sv_g_argc;
1256 smallint sv_g_malloced;
1257} save_arg_t;
1258
1259static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1260{
1261 int n;
1262
1263 sv->sv_argv0 = argv[0];
1264 sv->sv_g_argv = G.global_argv;
1265 sv->sv_g_argc = G.global_argc;
1266 sv->sv_g_malloced = G.global_args_malloced;
1267
1268 argv[0] = G.global_argv[0]; /* retain $0 */
1269 G.global_argv = argv;
1270 G.global_args_malloced = 0;
1271
1272 n = 1;
1273 while (*++argv)
1274 n++;
1275 G.global_argc = n;
1276}
1277
1278static void restore_G_args(save_arg_t *sv, char **argv)
1279{
1280 char **pp;
1281
1282 if (G.global_args_malloced) {
1283 /* someone ran "set -- arg1 arg2 ...", undo */
1284 pp = G.global_argv;
1285 while (*++pp) /* note: does not free $0 */
1286 free(*pp);
1287 free(G.global_argv);
1288 }
1289 argv[0] = sv->sv_argv0;
1290 G.global_argv = sv->sv_g_argv;
1291 G.global_argc = sv->sv_g_argc;
1292 G.global_args_malloced = sv->sv_g_malloced;
1293}
1294
1295
Denis Vlasenkod5762932009-03-31 11:22:57 +00001296/* Basic theory of signal handling in shell
1297 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001298 * This does not describe what hush does, rather, it is current understanding
1299 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001300 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1301 *
1302 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1303 * is finished or backgrounded. It is the same in interactive and
1304 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001305 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001306 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001307 * backgrounds (i.e. stops) or kills all members of currently running
1308 * pipe.
1309 *
1310 * Wait builtin in interruptible by signals for which user trap is set
1311 * or by SIGINT in interactive shell.
1312 *
1313 * Trap handlers will execute even within trap handlers. (right?)
1314 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001315 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1316 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001317 *
1318 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001319 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001320 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001321 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001322 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001323 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001324 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001325 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001326 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001327 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001328 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001329 *
1330 * SIGQUIT: ignore
1331 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001332 * SIGHUP (interactive):
1333 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001334 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001335 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1336 * that all pipe members are stopped. Try this in bash:
1337 * while :; do :; done - ^Z does not background it
1338 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001339 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001340 * of the command line, show prompt. NB: ^C does not send SIGINT
1341 * to interactive shell while shell is waiting for a pipe,
1342 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001343 * Example 1: this waits 5 sec, but does not execute ls:
1344 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1345 * Example 2: this does not wait and does not execute ls:
1346 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1347 * Example 3: this does not wait 5 sec, but executes ls:
1348 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001349 * Example 4: this does not wait and does not execute ls:
1350 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001351 *
1352 * (What happens to signals which are IGN on shell start?)
1353 * (What happens with signal mask on shell start?)
1354 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001355 * Old implementation
1356 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001357 * We use in-kernel pending signal mask to determine which signals were sent.
1358 * We block all signals which we don't want to take action immediately,
1359 * i.e. we block all signals which need to have special handling as described
1360 * above, and all signals which have traps set.
1361 * After each pipe execution, we extract any pending signals via sigtimedwait()
1362 * and act on them.
1363 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001364 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001365 * sigset_t blocked_set: current blocked signal set
1366 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001367 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001368 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001369 * "trap 'cmd' SIGxxx":
1370 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001371 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001372 * unblock signals with special interactive handling
1373 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001374 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001375 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001376 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001377 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001378 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001379 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001380 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001381 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001382 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001383 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001384 * Standard says "When a subshell is entered, traps that are not being ignored
1385 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001386 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001387 *
1388 * Problem: the above approach makes it unwieldy to catch signals while
1389 * we are in read builtin, of while we read commands from stdin:
1390 * masked signals are not visible!
1391 *
1392 * New implementation
1393 * ==================
1394 * We record each signal we are interested in by installing signal handler
1395 * for them - a bit like emulating kernel pending signal mask in userspace.
1396 * We are interested in: signals which need to have special handling
1397 * as described above, and all signals which have traps set.
1398 * Signals are rocorded in pending_set.
1399 * After each pipe execution, we extract any pending signals
1400 * and act on them.
1401 *
1402 * unsigned special_sig_mask: a mask of shell-special signals.
1403 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1404 * char *traps[sig] if trap for sig is set (even if it's '').
1405 * sigset_t pending_set: set of sigs we received.
1406 *
1407 * "trap - SIGxxx":
1408 * if sig is in special_sig_mask, set handler back to:
1409 * record_pending_signo, or to IGN if it's a tty stop signal
1410 * if sig is in fatal_sig_mask, set handler back to sigexit.
1411 * else: set handler back to SIG_DFL
1412 * "trap 'cmd' SIGxxx":
1413 * set handler to record_pending_signo.
1414 * "trap '' SIGxxx":
1415 * set handler to SIG_IGN.
1416 * after [v]fork, if we plan to be a shell:
1417 * set signals with special interactive handling to SIG_DFL
1418 * (because child shell is not interactive),
1419 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1420 * after [v]fork, if we plan to exec:
1421 * POSIX says fork clears pending signal mask in child - no need to clear it.
1422 *
1423 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1424 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1425 *
1426 * Note (compat):
1427 * Standard says "When a subshell is entered, traps that are not being ignored
1428 * are set to the default actions". bash interprets it so that traps which
1429 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001430 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001431enum {
1432 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001433 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001434 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001435 | (1 << SIGHUP)
1436 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001437 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001438#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001439 | (1 << SIGTTIN)
1440 | (1 << SIGTTOU)
1441 | (1 << SIGTSTP)
1442#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001443 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001444};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001445
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001446static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001447{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001448 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001449#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001450 if (sig == SIGCHLD) {
1451 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001452//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 +02001453 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001454#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001455}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001456
Denys Vlasenko0806e402011-05-12 23:06:20 +02001457static sighandler_t install_sighandler(int sig, sighandler_t handler)
1458{
1459 struct sigaction old_sa;
1460
1461 /* We could use signal() to install handlers... almost:
1462 * except that we need to mask ALL signals while handlers run.
1463 * I saw signal nesting in strace, race window isn't small.
1464 * SA_RESTART is also needed, but in Linux, signal()
1465 * sets SA_RESTART too.
1466 */
1467 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1468 /* sigfillset(&G.sa.sa_mask); - already done */
1469 /* G.sa.sa_flags = SA_RESTART; - already done */
1470 G.sa.sa_handler = handler;
1471 sigaction(sig, &G.sa, &old_sa);
1472 return old_sa.sa_handler;
1473}
1474
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001475#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001476
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001477/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001478# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001479/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001480# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001481
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001482/* Restores tty foreground process group, and exits.
1483 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001484 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001485 * or called directly with -EXITCODE.
1486 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001487static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001488static void sigexit(int sig)
1489{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001490 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001491 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001492 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1493 /* Disable all signals: job control, SIGPIPE, etc.
1494 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1495 */
1496 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001497 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001498 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001499
1500 /* Not a signal, just exit */
1501 if (sig <= 0)
1502 _exit(- sig);
1503
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001504 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001505}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001506#else
1507
Denys Vlasenko8391c482010-05-22 17:50:43 +02001508# define disable_restore_tty_pgrp_on_exit() ((void)0)
1509# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001510
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001511#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001512
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001513static sighandler_t pick_sighandler(unsigned sig)
1514{
1515 sighandler_t handler = SIG_DFL;
1516 if (sig < sizeof(unsigned)*8) {
1517 unsigned sigmask = (1 << sig);
1518
1519#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001520 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001521 if (G_fatal_sig_mask & sigmask)
1522 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001523 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001524#endif
1525 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001526 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001527 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001528 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001529 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001530 * in an endless loop when we try to do some
1531 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001532 */
1533 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1534 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001535 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001536 }
1537 return handler;
1538}
1539
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001540/* Restores tty foreground process group, and exits. */
1541static void hush_exit(int exitcode) NORETURN;
1542static void hush_exit(int exitcode)
1543{
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001544 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001545 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001546 char *argv[3];
1547 /* argv[0] is unused */
1548 argv[1] = G.traps[0];
1549 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001550 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001551 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001552 * "trap" will still show it, if executed
1553 * in the handler */
1554 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001555 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001556
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001557#if ENABLE_FEATURE_CLEAN_UP
1558 {
1559 struct variable *cur_var;
1560 if (G.cwd != bb_msg_unknown)
1561 free((char*)G.cwd);
1562 cur_var = G.top_var;
1563 while (cur_var) {
1564 struct variable *tmp = cur_var;
1565 if (!cur_var->max_len)
1566 free(cur_var->varstr);
1567 cur_var = cur_var->next;
1568 free(tmp);
1569 }
1570 }
1571#endif
1572
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001573#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001574 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001575 sigexit(- (exitcode & 0xff));
1576#else
1577 exit(exitcode);
1578#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001579}
1580
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001581
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001582//TODO: return a mask of ALL handled sigs?
1583static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001584{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001585 int last_sig = 0;
1586
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001587 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001588 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001589
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001590 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001591 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001592 sig = 0;
1593 do {
1594 sig++;
1595 if (sigismember(&G.pending_set, sig)) {
1596 sigdelset(&G.pending_set, sig);
1597 goto got_sig;
1598 }
1599 } while (sig < NSIG);
1600 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001601 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001602 if (G.traps && G.traps[sig]) {
1603 if (G.traps[sig][0]) {
1604 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001605 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001606 char *argv[3];
1607 /* argv[0] is unused */
1608 argv[1] = G.traps[sig];
1609 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001610 save_rcode = G.last_exitcode;
1611 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001612 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001613 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001614 } /* else: "" trap, ignoring signal */
1615 continue;
1616 }
1617 /* not a trap: special action */
1618 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001619 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001620 /* Builtin was ^C'ed, make it look prettier: */
1621 bb_putchar('\n');
1622 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001623 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001624 break;
1625#if ENABLE_HUSH_JOB
1626 case SIGHUP: {
1627 struct pipe *job;
1628 /* bash is observed to signal whole process groups,
1629 * not individual processes */
1630 for (job = G.job_list; job; job = job->next) {
1631 if (job->pgrp <= 0)
1632 continue;
1633 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1634 if (kill(- job->pgrp, SIGHUP) == 0)
1635 kill(- job->pgrp, SIGCONT);
1636 }
1637 sigexit(SIGHUP);
1638 }
1639#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001640#if ENABLE_HUSH_FAST
1641 case SIGCHLD:
1642 G.count_SIGCHLD++;
1643//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1644 /* Note:
1645 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1646 * This simplifies wait builtin a bit.
1647 */
1648 break;
1649#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001650 default: /* ignored: */
1651 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001652 /* Note:
1653 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1654 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001655 * in interactive shell, because TERM is ignored.
1656 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001657 break;
1658 }
1659 }
1660 return last_sig;
1661}
1662
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001663
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001664static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001665{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001666 if (force || G.cwd == NULL) {
1667 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1668 * we must not try to free(bb_msg_unknown) */
1669 if (G.cwd == bb_msg_unknown)
1670 G.cwd = NULL;
1671 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1672 if (!G.cwd)
1673 G.cwd = bb_msg_unknown;
1674 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001675 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001676}
1677
Denis Vlasenko83506862007-11-23 13:11:42 +00001678
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001679/*
1680 * Shell and environment variable support
1681 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001682static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001683{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001684 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001685 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001686
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001687 pp = &G.top_var;
1688 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001689 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001690 return pp;
1691 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001692 }
1693 return NULL;
1694}
1695
Denys Vlasenko03dad222010-01-12 23:29:57 +01001696static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001697{
Denys Vlasenko29082232010-07-16 13:52:32 +02001698 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001699 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001700
1701 if (G.expanded_assignments) {
1702 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001703 while (*cpp) {
1704 char *cp = *cpp;
1705 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1706 return cp + len + 1;
1707 cpp++;
1708 }
1709 }
1710
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001711 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001712 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001713 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001714
Denys Vlasenkodea47882009-10-09 15:40:49 +02001715 if (strcmp(name, "PPID") == 0)
1716 return utoa(G.root_ppid);
1717 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001718#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001719 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001720 return utoa(next_random(&G.random_gen));
1721#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001722 return NULL;
1723}
1724
1725/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001726 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001727 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001728 * 0: do not change export flag
1729 * (if creating new variable, flag will be 0)
1730 * 1: set export flag and putenv the variable
1731 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001732 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001733 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001734#if !BB_MMU && ENABLE_HUSH_LOCAL
1735/* all params are used */
1736#elif BB_MMU && ENABLE_HUSH_LOCAL
1737#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1738 set_local_var(str, flg_export, local_lvl)
1739#elif BB_MMU && !ENABLE_HUSH_LOCAL
1740#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001741 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001742#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1743#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1744 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001745#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001746static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001747{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001748 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001749 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001750 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001751 int name_len;
1752
Denis Vlasenko950bd722009-04-21 11:23:56 +00001753 eq_sign = strchr(str, '=');
1754 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001755 free(str);
1756 return -1;
1757 }
1758
Denis Vlasenko950bd722009-04-21 11:23:56 +00001759 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001760 var_pp = &G.top_var;
1761 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001762 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001763 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001764 continue;
1765 }
1766 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001767 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001768#if !BB_MMU
1769 if (!flg_read_only)
1770#endif
1771 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001772 free(str);
1773 return -1;
1774 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001775 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001776 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1777 *eq_sign = '\0';
1778 unsetenv(str);
1779 *eq_sign = '=';
1780 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001781#if ENABLE_HUSH_LOCAL
1782 if (cur->func_nest_level < local_lvl) {
1783 /* New variable is declared as local,
1784 * and existing one is global, or local
1785 * from enclosing function.
1786 * Remove and save old one: */
1787 *var_pp = cur->next;
1788 cur->next = *G.shadowed_vars_pp;
1789 *G.shadowed_vars_pp = cur;
1790 /* bash 3.2.33(1) and exported vars:
1791 * # export z=z
1792 * # f() { local z=a; env | grep ^z; }
1793 * # f
1794 * z=a
1795 * # env | grep ^z
1796 * z=z
1797 */
1798 if (cur->flg_export)
1799 flg_export = 1;
1800 break;
1801 }
1802#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001803 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001804 free_and_exp:
1805 free(str);
1806 goto exp;
1807 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001808 if (cur->max_len != 0) {
1809 if (cur->max_len >= strlen(str)) {
1810 /* This one is from startup env, reuse space */
1811 strcpy(cur->varstr, str);
1812 goto free_and_exp;
1813 }
1814 } else {
1815 /* max_len == 0 signifies "malloced" var, which we can
1816 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001817 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001818 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001819 cur->max_len = 0;
1820 goto set_str_and_exp;
1821 }
1822
Denys Vlasenko295fef82009-06-03 12:47:26 +02001823 /* Not found - create new variable struct */
1824 cur = xzalloc(sizeof(*cur));
1825#if ENABLE_HUSH_LOCAL
1826 cur->func_nest_level = local_lvl;
1827#endif
1828 cur->next = *var_pp;
1829 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001830
1831 set_str_and_exp:
1832 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001833#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001834 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001835#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001836 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001837 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001838 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001839 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1840 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001841 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001842 if (flg_export == -1) {
1843 cur->flg_export = 0;
1844 /* unsetenv was already done */
1845 } else {
1846 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1847 return putenv(cur->varstr);
1848 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001849 }
1850 return 0;
1851}
1852
Denys Vlasenko6db47842009-09-05 20:15:17 +02001853/* Used at startup and after each cd */
1854static void set_pwd_var(int exp)
1855{
1856 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1857 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1858}
1859
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001860static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001861{
1862 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001863 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001864
1865 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001866 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001867 var_pp = &G.top_var;
1868 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001869 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1870 if (cur->flg_read_only) {
1871 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001872 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001873 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001874 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001875 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1876 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001877 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1878 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001879 if (!cur->max_len)
1880 free(cur->varstr);
1881 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001882 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001883 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001884 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001885 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001886 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001887}
1888
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001889static int unset_local_var(const char *name)
1890{
1891 return unset_local_var_len(name, strlen(name));
1892}
1893
1894static void unset_vars(char **strings)
1895{
1896 char **v;
1897
1898 if (!strings)
1899 return;
1900 v = strings;
1901 while (*v) {
1902 const char *eq = strchrnul(*v, '=');
1903 unset_local_var_len(*v, (int)(eq - *v));
1904 v++;
1905 }
1906 free(strings);
1907}
1908
Denys Vlasenko03dad222010-01-12 23:29:57 +01001909static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001910{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001911 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001912 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001913}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001914
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001915
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001916/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001917 * Helpers for "var1=val1 var2=val2 cmd" feature
1918 */
1919static void add_vars(struct variable *var)
1920{
1921 struct variable *next;
1922
1923 while (var) {
1924 next = var->next;
1925 var->next = G.top_var;
1926 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001927 if (var->flg_export) {
1928 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001929 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001930 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001931 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001932 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001933 var = next;
1934 }
1935}
1936
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001937static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001938{
1939 char **s;
1940 struct variable *old = NULL;
1941
1942 if (!strings)
1943 return old;
1944 s = strings;
1945 while (*s) {
1946 struct variable *var_p;
1947 struct variable **var_pp;
1948 char *eq;
1949
1950 eq = strchr(*s, '=');
1951 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001952 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001953 if (var_pp) {
1954 /* Remove variable from global linked list */
1955 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001956 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001957 *var_pp = var_p->next;
1958 /* Add it to returned list */
1959 var_p->next = old;
1960 old = var_p;
1961 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001962 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001963 }
1964 s++;
1965 }
1966 return old;
1967}
1968
1969
1970/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001971 * in_str support
1972 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001973static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001974{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001975 int ch = *i->p;
1976 if (ch != '\0') {
1977 i->p++;
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001978 i->last_char = ch;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001979 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001980 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001981 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001982}
1983
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001984static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001985{
1986 return *i->p;
1987}
1988
1989#if ENABLE_HUSH_INTERACTIVE
1990
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001991static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001992{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001993 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001994 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001995 if (G.PS1 == NULL)
1996 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001997 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001998 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001999 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002000 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002001 if (G.PS2 == NULL)
2002 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002003}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002004
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002005static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002006{
2007 const char *prompt_str;
2008 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002009 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2010 /* Set up the prompt */
2011 if (promptmode == 0) { /* PS1 */
2012 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002013 /* bash uses $PWD value, even if it is set by user.
2014 * It uses current dir only if PWD is unset.
2015 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002016 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002017 prompt_str = G.PS1;
2018 } else
2019 prompt_str = G.PS2;
2020 } else
2021 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002022 debug_printf("result '%s'\n", prompt_str);
2023 return prompt_str;
2024}
2025
2026static void get_user_input(struct in_str *i)
2027{
2028 int r;
2029 const char *prompt_str;
2030
2031 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002032# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002033 /* Enable command line editing only while a command line
2034 * is actually being read */
2035 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01002036 /* Unicode support should be activated even if LANG is set
2037 * _during_ shell execution, not only if it was set when
2038 * shell was started. Therefore, re-check LANG every time:
2039 */
2040 reinit_unicode(get_local_var_value("LANG"));
2041
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002042 G.flag_SIGINT = 0;
2043 /* buglet: SIGINT will not make new prompt to appear _at once_,
2044 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002045 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 +00002046 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002047 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002048 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002049 i->eof_flag = (r < 0);
2050 if (i->eof_flag) { /* EOF/error detected */
2051 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2052 G.user_input_buf[1] = '\0';
2053 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02002054# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002055 do {
2056 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002057 if (i->last_char == '\0' || i->last_char == '\n') {
2058 /* Why check_and_run_traps here? Try this interactively:
2059 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2060 * $ <[enter], repeatedly...>
2061 * Without check_and_run_traps, handler never runs.
2062 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002063 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002064 fputs(prompt_str, stdout);
2065 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002066 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002067 G.user_input_buf[0] = r = fgetc(i->file);
2068 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002069 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002070 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002071# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002072 i->p = G.user_input_buf;
2073}
2074
2075#endif /* INTERACTIVE */
2076
2077/* This is the magic location that prints prompts
2078 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002079static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002080{
2081 int ch;
2082
2083 /* If there is data waiting, eat it up */
2084 if (i->p && *i->p) {
2085#if ENABLE_HUSH_INTERACTIVE
2086 take_cached:
2087#endif
2088 ch = *i->p++;
2089 if (i->eof_flag && !*i->p)
2090 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002091 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002092 } else {
2093 /* need to double check i->file because we might be doing something
2094 * more complicated by now, like sourcing or substituting. */
2095#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002096 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002097 do {
2098 get_user_input(i);
2099 } while (!*i->p); /* need non-empty line */
2100 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002101 goto take_cached;
2102 }
2103#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00002104 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002105 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002106 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002107 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002108 return ch;
2109}
2110
Denis Vlasenko913a2012009-04-05 22:17:04 +00002111/* All callers guarantee this routine will never
2112 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002113 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002114static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002115{
2116 int ch;
2117 if (i->p && *i->p) {
2118 if (i->eof_flag && !i->p[1])
2119 return EOF;
2120 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002121 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002122 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002123 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002124 i->eof_flag = (ch == EOF);
2125 i->peek_buf[0] = ch;
2126 i->peek_buf[1] = '\0';
2127 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002128 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002129 return ch;
2130}
2131
2132static void setup_file_in_str(struct in_str *i, FILE *f)
2133{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002134 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002135 i->peek = file_peek;
2136 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002137 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002138 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002139 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002140}
2141
2142static void setup_string_in_str(struct in_str *i, const char *s)
2143{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002144 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002145 i->peek = static_peek;
2146 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002147 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002148 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002149 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002150}
2151
2152
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002153/*
2154 * o_string support
2155 */
2156#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002157
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002158static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002159{
2160 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002161 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002162 if (o->data)
2163 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002164}
2165
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002166static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002167{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002168 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002169 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002170}
2171
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002172static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2173{
2174 free(o->data);
2175}
2176
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002177static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002178{
2179 if (o->length + len > o->maxlen) {
2180 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2181 o->data = xrealloc(o->data, 1 + o->maxlen);
2182 }
2183}
2184
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002185static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002186{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002187 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2188 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002189 o->data[o->length] = ch;
2190 o->length++;
2191 o->data[o->length] = '\0';
2192}
2193
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002194static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002195{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002196 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002197 memcpy(&o->data[o->length], str, len);
2198 o->length += len;
2199 o->data[o->length] = '\0';
2200}
2201
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002202static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002203{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002204 o_addblock(o, str, strlen(str));
2205}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002206
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002207#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002208static void nommu_addchr(o_string *o, int ch)
2209{
2210 if (o)
2211 o_addchr(o, ch);
2212}
2213#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002214# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002215#endif
2216
2217static void o_addstr_with_NUL(o_string *o, const char *str)
2218{
2219 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002220}
2221
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002222/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002223 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002224 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2225 * Apparently, on unquoted $v bash still does globbing
2226 * ("v='*.txt'; echo $v" prints all .txt files),
2227 * but NOT brace expansion! Thus, there should be TWO independent
2228 * quoting mechanisms on $v expansion side: one protects
2229 * $v from brace expansion, and other additionally protects "$v" against globbing.
2230 * We have only second one.
2231 */
2232
Denys Vlasenko9e800222010-10-03 14:28:04 +02002233#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002234# define MAYBE_BRACES "{}"
2235#else
2236# define MAYBE_BRACES ""
2237#endif
2238
Eric Andersen25f27032001-04-26 23:22:31 +00002239/* My analysis of quoting semantics tells me that state information
2240 * is associated with a destination, not a source.
2241 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002242static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002243{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002244 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002245 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002246 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002247 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002248 o_grow_by(o, sz);
2249 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002250 o->data[o->length] = '\\';
2251 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002252 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002253 o->data[o->length] = ch;
2254 o->length++;
2255 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002256}
2257
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002258static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002259{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002260 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002261 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2262 && strchr("*?[\\" MAYBE_BRACES, ch)
2263 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002264 sz++;
2265 o->data[o->length] = '\\';
2266 o->length++;
2267 }
2268 o_grow_by(o, sz);
2269 o->data[o->length] = ch;
2270 o->length++;
2271 o->data[o->length] = '\0';
2272}
2273
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002274static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002275{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002276 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002277 char ch;
2278 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002279 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002280 if (ordinary_cnt > len) /* paranoia */
2281 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002282 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002283 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002284 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002285 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002286 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002287
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002288 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002289 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002290 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002291 sz++;
2292 o->data[o->length] = '\\';
2293 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002294 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002295 o_grow_by(o, sz);
2296 o->data[o->length] = ch;
2297 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002298 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002299 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002300}
2301
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002302static void o_addQblock(o_string *o, const char *str, int len)
2303{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002304 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002305 o_addblock(o, str, len);
2306 return;
2307 }
2308 o_addqblock(o, str, len);
2309}
2310
Denys Vlasenko38292b62010-09-05 14:49:40 +02002311static void o_addQstr(o_string *o, const char *str)
2312{
2313 o_addQblock(o, str, strlen(str));
2314}
2315
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002316/* A special kind of o_string for $VAR and `cmd` expansion.
2317 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002318 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002319 * list[i] contains an INDEX (int!) into this string data.
2320 * It means that if list[] needs to grow, data needs to be moved higher up
2321 * but list[i]'s need not be modified.
2322 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002323 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002324 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2325 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002326#if DEBUG_EXPAND || DEBUG_GLOB
2327static void debug_print_list(const char *prefix, o_string *o, int n)
2328{
2329 char **list = (char**)o->data;
2330 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2331 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002332
2333 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002334 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 +02002335 prefix, list, n, string_start, o->length, o->maxlen,
2336 !!(o->o_expflags & EXP_FLAG_GLOB),
2337 o->has_quoted_part,
2338 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002339 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002340 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002341 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2342 o->data + (int)(uintptr_t)list[i] + string_start,
2343 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002344 i++;
2345 }
2346 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002347 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002348 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002349 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002350 }
2351}
2352#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002353# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002354#endif
2355
2356/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2357 * in list[n] so that it points past last stored byte so far.
2358 * It returns n+1. */
2359static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002360{
2361 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002362 int string_start;
2363 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002364
2365 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002366 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2367 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002368 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002369 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002370 /* list[n] points to string_start, make space for 16 more pointers */
2371 o->maxlen += 0x10 * sizeof(list[0]);
2372 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002373 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002374 memmove(list + n + 0x10, list + n, string_len);
2375 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002376 } else {
2377 debug_printf_list("list[%d]=%d string_start=%d\n",
2378 n, string_len, string_start);
2379 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002380 } else {
2381 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002382 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2383 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002384 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2385 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002386 o->has_empty_slot = 0;
2387 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002388 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002389 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002390 return n + 1;
2391}
2392
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002393/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002394static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002395{
2396 char **list = (char**)o->data;
2397 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2398
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002399 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002400}
2401
Denys Vlasenko9e800222010-10-03 14:28:04 +02002402#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002403/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2404 * first, it processes even {a} (no commas), second,
2405 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002406 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002407 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002408
2409/* Helper */
2410static int glob_needed(const char *s)
2411{
2412 while (*s) {
2413 if (*s == '\\') {
2414 if (!s[1])
2415 return 0;
2416 s += 2;
2417 continue;
2418 }
2419 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2420 return 1;
2421 s++;
2422 }
2423 return 0;
2424}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002425/* Return pointer to next closing brace or to comma */
2426static const char *next_brace_sub(const char *cp)
2427{
2428 unsigned depth = 0;
2429 cp++;
2430 while (*cp != '\0') {
2431 if (*cp == '\\') {
2432 if (*++cp == '\0')
2433 break;
2434 cp++;
2435 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002436 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002437 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002438 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002439 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002440 depth++;
2441 }
2442
2443 return *cp != '\0' ? cp : NULL;
2444}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002445/* Recursive brace globber. Note: may garble pattern[]. */
2446static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002447{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002448 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002449 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002450 const char *next;
2451 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002452 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002453 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002454
2455 debug_printf_glob("glob_brace('%s')\n", pattern);
2456
2457 begin = pattern;
2458 while (1) {
2459 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002460 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002461 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002462 /* Find the first sub-pattern and at the same time
2463 * find the rest after the closing brace */
2464 next = next_brace_sub(begin);
2465 if (next == NULL) {
2466 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002467 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002468 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002469 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002470 /* "{abc}" with no commas - illegal
2471 * brace expr, disregard and skip it */
2472 begin = next + 1;
2473 continue;
2474 }
2475 break;
2476 }
2477 if (*begin == '\\' && begin[1] != '\0')
2478 begin++;
2479 begin++;
2480 }
2481 debug_printf_glob("begin:%s\n", begin);
2482 debug_printf_glob("next:%s\n", next);
2483
2484 /* Now find the end of the whole brace expression */
2485 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002486 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002487 rest = next_brace_sub(rest);
2488 if (rest == NULL) {
2489 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002490 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002491 }
2492 debug_printf_glob("rest:%s\n", rest);
2493 }
2494 rest_len = strlen(++rest) + 1;
2495
2496 /* We are sure the brace expression is well-formed */
2497
2498 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002499 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002500
2501 /* We have a brace expression. BEGIN points to the opening {,
2502 * NEXT points past the terminator of the first element, and REST
2503 * points past the final }. We will accumulate result names from
2504 * recursive runs for each brace alternative in the buffer using
2505 * GLOB_APPEND. */
2506
2507 p = begin + 1;
2508 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002509 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002510 memcpy(
2511 mempcpy(
2512 mempcpy(new_pattern_buf,
2513 /* We know the prefix for all sub-patterns */
2514 pattern, begin - pattern),
2515 p, next - p),
2516 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002517
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002518 /* Note: glob_brace() may garble new_pattern_buf[].
2519 * That's why we re-copy prefix every time (1st memcpy above).
2520 */
2521 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002522 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002523 /* We saw the last entry */
2524 break;
2525 }
2526 p = next + 1;
2527 next = next_brace_sub(next);
2528 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002529 free(new_pattern_buf);
2530 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002531
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002532 simple_glob:
2533 {
2534 int gr;
2535 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002536
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002537 memset(&globdata, 0, sizeof(globdata));
2538 gr = glob(pattern, 0, NULL, &globdata);
2539 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2540 if (gr != 0) {
2541 if (gr == GLOB_NOMATCH) {
2542 globfree(&globdata);
2543 /* NB: garbles parameter */
2544 unbackslash(pattern);
2545 o_addstr_with_NUL(o, pattern);
2546 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2547 return o_save_ptr_helper(o, n);
2548 }
2549 if (gr == GLOB_NOSPACE)
2550 bb_error_msg_and_die(bb_msg_memory_exhausted);
2551 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2552 * but we didn't specify it. Paranoia again. */
2553 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2554 }
2555 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2556 char **argv = globdata.gl_pathv;
2557 while (1) {
2558 o_addstr_with_NUL(o, *argv);
2559 n = o_save_ptr_helper(o, n);
2560 argv++;
2561 if (!*argv)
2562 break;
2563 }
2564 }
2565 globfree(&globdata);
2566 }
2567 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002568}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002569/* Performs globbing on last list[],
2570 * saving each result as a new list[].
2571 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002572static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002573{
2574 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002575
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002576 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002577 if (!o->data)
2578 return o_save_ptr_helper(o, n);
2579 pattern = o->data + o_get_last_ptr(o, n);
2580 debug_printf_glob("glob pattern '%s'\n", pattern);
2581 if (!glob_needed(pattern)) {
2582 /* unbackslash last string in o in place, fix length */
2583 o->length = unbackslash(pattern) - o->data;
2584 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2585 return o_save_ptr_helper(o, n);
2586 }
2587
2588 copy = xstrdup(pattern);
2589 /* "forget" pattern in o */
2590 o->length = pattern - o->data;
2591 n = glob_brace(copy, o, n);
2592 free(copy);
2593 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002594 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002595 return n;
2596}
2597
Denys Vlasenko238081f2010-10-03 14:26:26 +02002598#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002599
2600/* Helper */
2601static int glob_needed(const char *s)
2602{
2603 while (*s) {
2604 if (*s == '\\') {
2605 if (!s[1])
2606 return 0;
2607 s += 2;
2608 continue;
2609 }
2610 if (*s == '*' || *s == '[' || *s == '?')
2611 return 1;
2612 s++;
2613 }
2614 return 0;
2615}
2616/* Performs globbing on last list[],
2617 * saving each result as a new list[].
2618 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002619static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002620{
2621 glob_t globdata;
2622 int gr;
2623 char *pattern;
2624
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002625 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002626 if (!o->data)
2627 return o_save_ptr_helper(o, n);
2628 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002629 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002630 if (!glob_needed(pattern)) {
2631 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002632 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002633 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002634 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002635 return o_save_ptr_helper(o, n);
2636 }
2637
2638 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002639 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2640 * If we glob "*.\*" and don't find anything, we need
2641 * to fall back to using literal "*.*", but GLOB_NOCHECK
2642 * will return "*.\*"!
2643 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002644 gr = glob(pattern, 0, NULL, &globdata);
2645 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002646 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002647 if (gr == GLOB_NOMATCH) {
2648 globfree(&globdata);
2649 goto literal;
2650 }
2651 if (gr == GLOB_NOSPACE)
2652 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002653 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2654 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002655 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002656 }
2657 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2658 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002659 /* "forget" pattern in o */
2660 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002661 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002662 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002663 n = o_save_ptr_helper(o, n);
2664 argv++;
2665 if (!*argv)
2666 break;
2667 }
2668 }
2669 globfree(&globdata);
2670 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002671 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002672 return n;
2673}
2674
Denys Vlasenko238081f2010-10-03 14:26:26 +02002675#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002676
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002677/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002678 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002679static int o_save_ptr(o_string *o, int n)
2680{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002681 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002682 /* If o->has_empty_slot, list[n] was already globbed
2683 * (if it was requested back then when it was filled)
2684 * so don't do that again! */
2685 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002686 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002687 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002688 return o_save_ptr_helper(o, n);
2689}
2690
2691/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002692static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002693{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002694 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002695 int string_start;
2696
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002697 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2698 if (DEBUG_EXPAND)
2699 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002700 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002701 list = (char**)o->data;
2702 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2703 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002704 while (n) {
2705 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002706 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002707 }
2708 return list;
2709}
2710
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002711static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002712
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002713/* Returns pi->next - next pipe in the list */
2714static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002715{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002716 struct pipe *next;
2717 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002718
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002719 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002720 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002721 struct command *command;
2722 struct redir_struct *r, *rnext;
2723
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002724 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002725 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002726 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002727 if (DEBUG_CLEAN) {
2728 int a;
2729 char **p;
2730 for (a = 0, p = command->argv; *p; a++, p++) {
2731 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2732 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002733 }
2734 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002735 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002736 }
2737 /* not "else if": on syntax error, we may have both! */
2738 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002739 debug_printf_clean(" begin group (cmd_type:%d)\n",
2740 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002741 free_pipe_list(command->group);
2742 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002743 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002744 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002745 /* else is crucial here.
2746 * If group != NULL, child_func is meaningless */
2747#if ENABLE_HUSH_FUNCTIONS
2748 else if (command->child_func) {
2749 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2750 command->child_func->parent_cmd = NULL;
2751 }
2752#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002753#if !BB_MMU
2754 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002755 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002756#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002757 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002758 debug_printf_clean(" redirect %d%s",
2759 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002760 /* guard against the case >$FOO, where foo is unset or blank */
2761 if (r->rd_filename) {
2762 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2763 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002764 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002765 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002766 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002767 rnext = r->next;
2768 free(r);
2769 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002770 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002771 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002772 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002773 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002774#if ENABLE_HUSH_JOB
2775 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002776 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002777#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002778
2779 next = pi->next;
2780 free(pi);
2781 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002782}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002783
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002784static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002785{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002786 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002787#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002788 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002789#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002790 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002791 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002792 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002793}
2794
2795
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002796/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002797
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002798#ifndef debug_print_tree
2799static void debug_print_tree(struct pipe *pi, int lvl)
2800{
2801 static const char *const PIPE[] = {
2802 [PIPE_SEQ] = "SEQ",
2803 [PIPE_AND] = "AND",
2804 [PIPE_OR ] = "OR" ,
2805 [PIPE_BG ] = "BG" ,
2806 };
2807 static const char *RES[] = {
2808 [RES_NONE ] = "NONE" ,
2809# if ENABLE_HUSH_IF
2810 [RES_IF ] = "IF" ,
2811 [RES_THEN ] = "THEN" ,
2812 [RES_ELIF ] = "ELIF" ,
2813 [RES_ELSE ] = "ELSE" ,
2814 [RES_FI ] = "FI" ,
2815# endif
2816# if ENABLE_HUSH_LOOPS
2817 [RES_FOR ] = "FOR" ,
2818 [RES_WHILE] = "WHILE",
2819 [RES_UNTIL] = "UNTIL",
2820 [RES_DO ] = "DO" ,
2821 [RES_DONE ] = "DONE" ,
2822# endif
2823# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2824 [RES_IN ] = "IN" ,
2825# endif
2826# if ENABLE_HUSH_CASE
2827 [RES_CASE ] = "CASE" ,
2828 [RES_CASE_IN ] = "CASE_IN" ,
2829 [RES_MATCH] = "MATCH",
2830 [RES_CASE_BODY] = "CASE_BODY",
2831 [RES_ESAC ] = "ESAC" ,
2832# endif
2833 [RES_XXXX ] = "XXXX" ,
2834 [RES_SNTX ] = "SNTX" ,
2835 };
2836 static const char *const CMDTYPE[] = {
2837 "{}",
2838 "()",
2839 "[noglob]",
2840# if ENABLE_HUSH_FUNCTIONS
2841 "func()",
2842# endif
2843 };
2844
2845 int pin, prn;
2846
2847 pin = 0;
2848 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002849 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002850 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2851 prn = 0;
2852 while (prn < pi->num_cmds) {
2853 struct command *command = &pi->cmds[prn];
2854 char **argv = command->argv;
2855
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002856 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002857 lvl*2, "", prn,
2858 command->assignment_cnt);
2859 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002860 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002861 CMDTYPE[command->cmd_type],
2862 argv
2863# if !BB_MMU
2864 , " group_as_string:", command->group_as_string
2865# else
2866 , "", ""
2867# endif
2868 );
2869 debug_print_tree(command->group, lvl+1);
2870 prn++;
2871 continue;
2872 }
2873 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002874 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002875 argv++;
2876 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002877 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002878 prn++;
2879 }
2880 pi = pi->next;
2881 pin++;
2882 }
2883}
2884#endif /* debug_print_tree */
2885
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002886static struct pipe *new_pipe(void)
2887{
Eric Andersen25f27032001-04-26 23:22:31 +00002888 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002889 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002890 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002891 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002892 return pi;
2893}
2894
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002895/* Command (member of a pipe) is complete, or we start a new pipe
2896 * if ctx->command is NULL.
2897 * No errors possible here.
2898 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002899static int done_command(struct parse_context *ctx)
2900{
2901 /* The command is really already in the pipe structure, so
2902 * advance the pipe counter and make a new, null command. */
2903 struct pipe *pi = ctx->pipe;
2904 struct command *command = ctx->command;
2905
2906 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002907 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002908 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002909 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002910 }
2911 pi->num_cmds++;
2912 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002913 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002914 } else {
2915 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2916 }
2917
2918 /* Only real trickiness here is that the uncommitted
2919 * command structure is not counted in pi->num_cmds. */
2920 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002921 ctx->command = command = &pi->cmds[pi->num_cmds];
2922 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002923 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002924 return pi->num_cmds; /* used only for 0/nonzero check */
2925}
2926
2927static void done_pipe(struct parse_context *ctx, pipe_style type)
2928{
2929 int not_null;
2930
2931 debug_printf_parse("done_pipe entered, followup %d\n", type);
2932 /* Close previous command */
2933 not_null = done_command(ctx);
2934 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002935#if HAS_KEYWORDS
2936 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2937 ctx->ctx_inverted = 0;
2938 ctx->pipe->res_word = ctx->ctx_res_w;
2939#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002940
2941 /* Without this check, even just <enter> on command line generates
2942 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002943 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002944 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002945#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002946 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002947#endif
2948#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002949 || ctx->ctx_res_w == RES_DONE
2950 || ctx->ctx_res_w == RES_FOR
2951 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002952#endif
2953#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002954 || ctx->ctx_res_w == RES_ESAC
2955#endif
2956 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002957 struct pipe *new_p;
2958 debug_printf_parse("done_pipe: adding new pipe: "
2959 "not_null:%d ctx->ctx_res_w:%d\n",
2960 not_null, ctx->ctx_res_w);
2961 new_p = new_pipe();
2962 ctx->pipe->next = new_p;
2963 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002964 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002965 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002966 * This is used to control execution.
2967 * RES_FOR and RES_IN are NOT sticky (needed to support
2968 * cases where variable or value happens to match a keyword):
2969 */
2970#if ENABLE_HUSH_LOOPS
2971 if (ctx->ctx_res_w == RES_FOR
2972 || ctx->ctx_res_w == RES_IN)
2973 ctx->ctx_res_w = RES_NONE;
2974#endif
2975#if ENABLE_HUSH_CASE
2976 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002977 ctx->ctx_res_w = RES_CASE_BODY;
2978 if (ctx->ctx_res_w == RES_CASE)
2979 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002980#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002981 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002982 /* Create the memory for command, roughly:
2983 * ctx->pipe->cmds = new struct command;
2984 * ctx->command = &ctx->pipe->cmds[0];
2985 */
2986 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002987 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002988 }
2989 debug_printf_parse("done_pipe return\n");
2990}
2991
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002992static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002993{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002994 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002995 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002996 /* Create the memory for command, roughly:
2997 * ctx->pipe->cmds = new struct command;
2998 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002999 */
3000 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003001}
3002
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003003/* If a reserved word is found and processed, parse context is modified
3004 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003005 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003006#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003007struct reserved_combo {
3008 char literal[6];
3009 unsigned char res;
3010 unsigned char assignment_flag;
3011 int flag;
3012};
3013enum {
3014 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003015# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003016 FLAG_IF = (1 << RES_IF ),
3017 FLAG_THEN = (1 << RES_THEN ),
3018 FLAG_ELIF = (1 << RES_ELIF ),
3019 FLAG_ELSE = (1 << RES_ELSE ),
3020 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003021# endif
3022# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003023 FLAG_FOR = (1 << RES_FOR ),
3024 FLAG_WHILE = (1 << RES_WHILE),
3025 FLAG_UNTIL = (1 << RES_UNTIL),
3026 FLAG_DO = (1 << RES_DO ),
3027 FLAG_DONE = (1 << RES_DONE ),
3028 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003029# endif
3030# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003031 FLAG_MATCH = (1 << RES_MATCH),
3032 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003033# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003034 FLAG_START = (1 << RES_XXXX ),
3035};
3036
3037static const struct reserved_combo* match_reserved_word(o_string *word)
3038{
Eric Andersen25f27032001-04-26 23:22:31 +00003039 /* Mostly a list of accepted follow-up reserved words.
3040 * FLAG_END means we are done with the sequence, and are ready
3041 * to turn the compound list into a command.
3042 * FLAG_START means the word must start a new compound list.
3043 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003044 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003045# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003046 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3047 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3048 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3049 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3050 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3051 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003052# endif
3053# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003054 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3055 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3056 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3057 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3058 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3059 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003060# endif
3061# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003062 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3063 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003064# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003065 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003066 const struct reserved_combo *r;
3067
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003068 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003069 if (strcmp(word->data, r->literal) == 0)
3070 return r;
3071 }
3072 return NULL;
3073}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003074/* Return 0: not a keyword, 1: keyword
3075 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003076static int reserved_word(o_string *word, struct parse_context *ctx)
3077{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003078# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003079 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003080 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003081 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003082# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003083 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003084
Denys Vlasenko38292b62010-09-05 14:49:40 +02003085 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003086 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003087 r = match_reserved_word(word);
3088 if (!r)
3089 return 0;
3090
3091 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003092# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003093 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3094 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003095 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003096 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003097# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003098 if (r->flag == 0) { /* '!' */
3099 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003100 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003101 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003102 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003103 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003104 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003105 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003106 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003107 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003108
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003109 old = xmalloc(sizeof(*old));
3110 debug_printf_parse("push stack %p\n", old);
3111 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003112 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003113 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003114 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003115 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003116 ctx->ctx_res_w = RES_SNTX;
3117 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003118 } else {
3119 /* "{...} fi" is ok. "{...} if" is not
3120 * Example:
3121 * if { echo foo; } then { echo bar; } fi */
3122 if (ctx->command->group)
3123 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003124 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003125
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003126 ctx->ctx_res_w = r->res;
3127 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003128 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003129 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003130
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003131 if (ctx->old_flag & FLAG_END) {
3132 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003133
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003134 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003135 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003136 old = ctx->stack;
3137 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003138 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003139# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003140 o_addstr(&old->as_string, ctx->as_string.data);
3141 o_free_unsafe(&ctx->as_string);
3142 old->command->group_as_string = xstrdup(old->as_string.data);
3143 debug_printf_parse("pop, remembering as:'%s'\n",
3144 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003145# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003146 *ctx = *old; /* physical copy */
3147 free(old);
3148 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003149 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003150}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003151#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003152
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003153/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003154 * Normal return is 0. Syntax errors return 1.
3155 * Note: on return, word is reset, but not o_free'd!
3156 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003157static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003158{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003159 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003160
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003161 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003162 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003163 debug_printf_parse("done_word return 0: true null, ignored\n");
3164 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003165 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003166
Eric Andersen25f27032001-04-26 23:22:31 +00003167 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003168 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3169 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003170 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3171 * "2.7 Redirection
3172 * ...the word that follows the redirection operator
3173 * shall be subjected to tilde expansion, parameter expansion,
3174 * command substitution, arithmetic expansion, and quote
3175 * removal. Pathname expansion shall not be performed
3176 * on the word by a non-interactive shell; an interactive
3177 * shell may perform it, but shall do so only when
3178 * the expansion would result in one word."
3179 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003180 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003181 /* Cater for >\file case:
3182 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3183 * Same with heredocs:
3184 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3185 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003186 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3187 unbackslash(ctx->pending_redirect->rd_filename);
3188 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003189 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003190 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3191 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003192 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003193 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003194 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003195 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003196#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003197# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003198 if (ctx->ctx_dsemicolon
3199 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3200 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003201 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003202 /* ctx->ctx_res_w = RES_MATCH; */
3203 ctx->ctx_dsemicolon = 0;
3204 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003205# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003206 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003207# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003208 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3209 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003210# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003211# if ENABLE_HUSH_CASE
3212 && ctx->ctx_res_w != RES_CASE
3213# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003214 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003215 int reserved = reserved_word(word, ctx);
3216 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3217 if (reserved) {
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 Vlasenko29f9b722011-05-14 11:27:36 +02003238
3239 /* If this word wasn't an assignment, next ones definitely
3240 * can't be assignments. Even if they look like ones. */
3241 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3242 && word->o_assignment != WORD_IS_KEYWORD
3243 ) {
3244 word->o_assignment = NOT_ASSIGNMENT;
3245 } else {
3246 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3247 command->assignment_cnt++;
3248 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3249 }
3250 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3251 word->o_assignment = MAYBE_ASSIGNMENT;
3252 }
3253 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3254
Denys Vlasenko38292b62010-09-05 14:49:40 +02003255 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003256 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3257 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003258 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003259 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003260 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003261 char *p = word->data;
3262 while (p[0] == SPECIAL_VAR_SYMBOL
3263 && (p[1] & 0x7f) == '@'
3264 && p[2] == SPECIAL_VAR_SYMBOL
3265 ) {
3266 p += 3;
3267 }
3268 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003269 /* saw no "$@", or not only "$@" but some
3270 * real text is there too */
3271 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003272 * e.g. "", $empty"" etc to not disappear */
3273 o_addchr(word, SPECIAL_VAR_SYMBOL);
3274 o_addchr(word, SPECIAL_VAR_SYMBOL);
3275 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003276 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003277 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003278 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003279 }
Eric Andersen25f27032001-04-26 23:22:31 +00003280
Denis Vlasenko06810332007-05-21 23:30:54 +00003281#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003282 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003283 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003284 || !is_well_formed_var_name(command->argv[0], '\0')
3285 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003286 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003287 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003288 return 1;
3289 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003290 /* Force FOR to have just one word (variable name) */
3291 /* NB: basically, this makes hush see "for v in ..."
3292 * syntax as if it is "for v; in ...". FOR and IN become
3293 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003294 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003295 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003296#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003297#if ENABLE_HUSH_CASE
3298 /* Force CASE to have just one word */
3299 if (ctx->ctx_res_w == RES_CASE) {
3300 done_pipe(ctx, PIPE_SEQ);
3301 }
3302#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003303
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003304 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003305
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003306 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003307 return 0;
3308}
3309
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003310
3311/* Peek ahead in the input to find out if we have a "&n" construct,
3312 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003313 * Return:
3314 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3315 * REDIRFD_SYNTAX_ERR if syntax error,
3316 * REDIRFD_TO_FILE if no & was seen,
3317 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003318 */
3319#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003320#define parse_redir_right_fd(as_string, input) \
3321 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003322#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003323static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003324{
3325 int ch, d, ok;
3326
3327 ch = i_peek(input);
3328 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003329 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003330
3331 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003332 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003333 ch = i_peek(input);
3334 if (ch == '-') {
3335 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003336 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003337 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003338 }
3339 d = 0;
3340 ok = 0;
3341 while (ch != EOF && isdigit(ch)) {
3342 d = d*10 + (ch-'0');
3343 ok = 1;
3344 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003345 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003346 ch = i_peek(input);
3347 }
3348 if (ok) return d;
3349
3350//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3351
3352 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003353 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003354}
3355
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003356/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003357 */
3358static int parse_redirect(struct parse_context *ctx,
3359 int fd,
3360 redir_type style,
3361 struct in_str *input)
3362{
3363 struct command *command = ctx->command;
3364 struct redir_struct *redir;
3365 struct redir_struct **redirp;
3366 int dup_num;
3367
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003368 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003369 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003370 /* Check for a '>&1' type redirect */
3371 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3372 if (dup_num == REDIRFD_SYNTAX_ERR)
3373 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003374 } else {
3375 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003376 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003377 if (dup_num) { /* <<-... */
3378 ch = i_getch(input);
3379 nommu_addchr(&ctx->as_string, ch);
3380 ch = i_peek(input);
3381 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003382 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003383
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003384 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003385 int ch = i_peek(input);
3386 if (ch == '|') {
3387 /* >|FILE redirect ("clobbering" >).
3388 * Since we do not support "set -o noclobber" yet,
3389 * >| and > are the same for now. Just eat |.
3390 */
3391 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003392 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003393 }
3394 }
3395
3396 /* Create a new redir_struct and append it to the linked list */
3397 redirp = &command->redirects;
3398 while ((redir = *redirp) != NULL) {
3399 redirp = &(redir->next);
3400 }
3401 *redirp = redir = xzalloc(sizeof(*redir));
3402 /* redir->next = NULL; */
3403 /* redir->rd_filename = NULL; */
3404 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003405 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003406
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003407 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3408 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003409
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003410 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003411 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003412 /* Erik had a check here that the file descriptor in question
3413 * is legit; I postpone that to "run time"
3414 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003415 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3416 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003417 } else {
3418 /* Set ctx->pending_redirect, so we know what to do at the
3419 * end of the next parsed word. */
3420 ctx->pending_redirect = redir;
3421 }
3422 return 0;
3423}
3424
Eric Andersen25f27032001-04-26 23:22:31 +00003425/* If a redirect is immediately preceded by a number, that number is
3426 * supposed to tell which file descriptor to redirect. This routine
3427 * looks for such preceding numbers. In an ideal world this routine
3428 * needs to handle all the following classes of redirects...
3429 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3430 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3431 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3432 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003433 *
3434 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3435 * "2.7 Redirection
3436 * ... If n is quoted, the number shall not be recognized as part of
3437 * the redirection expression. For example:
3438 * echo \2>a
3439 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003440 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003441 *
3442 * A -1 return means no valid number was found,
3443 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003444 */
3445static int redirect_opt_num(o_string *o)
3446{
3447 int num;
3448
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003449 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003450 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003451 num = bb_strtou(o->data, NULL, 10);
3452 if (errno || num < 0)
3453 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003454 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003455 return num;
3456}
3457
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003458#if BB_MMU
3459#define fetch_till_str(as_string, input, word, skip_tabs) \
3460 fetch_till_str(input, word, skip_tabs)
3461#endif
3462static char *fetch_till_str(o_string *as_string,
3463 struct in_str *input,
3464 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003465 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003466{
3467 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003468 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003469 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003470 int ch;
3471
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003472 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003473
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003474 while (1) {
3475 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003476 if (ch != EOF)
3477 nommu_addchr(as_string, ch);
3478 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003479 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3480 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003481 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3482 heredoc.data[past_EOL] = '\0';
3483 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3484 return heredoc.data;
3485 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003486 while (ch == '\n') {
3487 o_addchr(&heredoc, ch);
3488 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003489 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003490 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003491 do {
3492 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003493 if (ch != EOF)
3494 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003495 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003496 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003497 }
3498 if (ch == EOF) {
3499 o_free_unsafe(&heredoc);
3500 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003501 }
3502 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003503 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003504 if (prev == '\\' && ch == '\\')
3505 /* Correctly handle foo\\<eol> (not a line cont.) */
3506 prev = 0; /* not \ */
3507 else
3508 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003509 }
3510}
3511
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003512/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3513 * and load them all. There should be exactly heredoc_cnt of them.
3514 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003515static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3516{
3517 struct pipe *pi = ctx->list_head;
3518
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003519 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003520 int i;
3521 struct command *cmd = pi->cmds;
3522
3523 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3524 pi->num_cmds,
3525 cmd->argv ? cmd->argv[0] : "NONE");
3526 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003527 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003528
3529 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3530 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003531 while (redir) {
3532 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003533 char *p;
3534
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003535 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003536 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003537 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003538 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003539 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003540 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003541 return 1;
3542 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003543 free(redir->rd_filename);
3544 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003545 heredoc_cnt--;
3546 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003547 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003548 }
3549 cmd++;
3550 }
3551 pi = pi->next;
3552 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003553#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003554 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003555 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003556 bb_error_msg_and_die("heredoc BUG 2");
3557#endif
3558 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003559}
3560
3561
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003562static int run_list(struct pipe *pi);
3563#if BB_MMU
3564#define parse_stream(pstring, input, end_trigger) \
3565 parse_stream(input, end_trigger)
3566#endif
3567static struct pipe *parse_stream(char **pstring,
3568 struct in_str *input,
3569 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003570
Eric Andersen25f27032001-04-26 23:22:31 +00003571
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003572#if !ENABLE_HUSH_FUNCTIONS
3573#define parse_group(dest, ctx, input, ch) \
3574 parse_group(ctx, input, ch)
3575#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003576static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003577 struct in_str *input, int ch)
3578{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003579 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003580 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003581 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003582 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003583 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003584 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003585
3586 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003587#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003588 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003589 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003590 if (done_word(dest, ctx))
3591 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003592 if (!command->argv)
3593 goto skip; /* (... */
3594 if (command->argv[1]) { /* word word ... (... */
3595 syntax_error_unexpected_ch('(');
3596 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003597 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003598 /* it is "word(..." or "word (..." */
3599 do
3600 ch = i_getch(input);
3601 while (ch == ' ' || ch == '\t');
3602 if (ch != ')') {
3603 syntax_error_unexpected_ch(ch);
3604 return 1;
3605 }
3606 nommu_addchr(&ctx->as_string, ch);
3607 do
3608 ch = i_getch(input);
3609 while (ch == ' ' || ch == '\t' || ch == '\n');
3610 if (ch != '{') {
3611 syntax_error_unexpected_ch(ch);
3612 return 1;
3613 }
3614 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003615 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003616 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003617 }
3618#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003619
3620#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003621 if (command->argv /* word [word]{... */
3622 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003623 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003624 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003625 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003626 debug_printf_parse("parse_group return 1: "
3627 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003628 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003629 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003630#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003631
3632#if ENABLE_HUSH_FUNCTIONS
3633 skip:
3634#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003635 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003636 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003637 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003638 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003639 } else {
3640 /* bash does not allow "{echo...", requires whitespace */
3641 ch = i_getch(input);
3642 if (ch != ' ' && ch != '\t' && ch != '\n') {
3643 syntax_error_unexpected_ch(ch);
3644 return 1;
3645 }
3646 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003647 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003648
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003649 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003650#if BB_MMU
3651# define as_string NULL
3652#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003653 char *as_string = NULL;
3654#endif
3655 pipe_list = parse_stream(&as_string, input, endch);
3656#if !BB_MMU
3657 if (as_string)
3658 o_addstr(&ctx->as_string, as_string);
3659#endif
3660 /* empty ()/{} or parse error? */
3661 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003662 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003663 if (!BB_MMU)
3664 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003665 debug_printf_parse("parse_group return 1: "
3666 "parse_stream returned %p\n", pipe_list);
3667 return 1;
3668 }
3669 command->group = pipe_list;
3670#if !BB_MMU
3671 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3672 command->group_as_string = as_string;
3673 debug_printf_parse("end of group, remembering as:'%s'\n",
3674 command->group_as_string);
3675#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003676#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003677 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003678 debug_printf_parse("parse_group return 0\n");
3679 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003680 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003681}
3682
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003683#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003684/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003685static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003686/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003687static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003688{
3689 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003690 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003691 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003692 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003693 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003694 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003695 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003696 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003697 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003698 }
3699}
3700/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003701static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003702{
3703 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003704 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003705 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003706 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003707 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003708 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003709 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003710 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003711 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003712 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003713 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003714 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003715 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003716 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003717 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3718 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003719 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003720 continue;
3721 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003722 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003723 }
3724}
3725/* Process `cmd` - copy contents until "`" is seen. Complicated by
3726 * \` quoting.
3727 * "Within the backquoted style of command substitution, backslash
3728 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3729 * The search for the matching backquote shall be satisfied by the first
3730 * backquote found without a preceding backslash; during this search,
3731 * if a non-escaped backquote is encountered within a shell comment,
3732 * a here-document, an embedded command substitution of the $(command)
3733 * form, or a quoted string, undefined results occur. A single-quoted
3734 * or double-quoted string that begins, but does not end, within the
3735 * "`...`" sequence produces undefined results."
3736 * Example Output
3737 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3738 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003739static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003740{
3741 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003742 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003743 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003744 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003745 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003746 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3747 ch = i_getch(input);
3748 if (ch != '`'
3749 && ch != '$'
3750 && ch != '\\'
3751 && (!in_dquote || ch != '"')
3752 ) {
3753 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003754 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003755 }
3756 if (ch == EOF) {
3757 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003758 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003759 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003760 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003761 }
3762}
3763/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3764 * quoting and nested ()s.
3765 * "With the $(command) style of command substitution, all characters
3766 * following the open parenthesis to the matching closing parenthesis
3767 * constitute the command. Any valid shell script can be used for command,
3768 * except a script consisting solely of redirections which produces
3769 * unspecified results."
3770 * Example Output
3771 * echo $(echo '(TEST)' BEST) (TEST) BEST
3772 * echo $(echo 'TEST)' BEST) TEST) BEST
3773 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003774 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003775 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003776 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003777 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3778 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003779 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003780#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003781static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003782{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003783 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003784 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003785# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003786 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003787# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003788 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3789
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003790 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003791 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003792 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003793 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003794 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003795 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003796 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003797 if (!dbl)
3798 break;
3799 /* we look for closing )) of $((EXPR)) */
3800 if (i_peek(input) == end_ch) {
3801 i_getch(input); /* eat second ')' */
3802 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003803 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003804 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003805 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003806 if (ch == '(' || ch == '{') {
3807 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003808 if (!add_till_closing_bracket(dest, input, ch))
3809 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003810 o_addchr(dest, ch);
3811 continue;
3812 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003813 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003814 if (!add_till_single_quote(dest, input))
3815 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003816 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003817 continue;
3818 }
3819 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003820 if (!add_till_double_quote(dest, input))
3821 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003822 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003823 continue;
3824 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003825 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003826 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3827 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003828 o_addchr(dest, ch);
3829 continue;
3830 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003831 if (ch == '\\') {
3832 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003833 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003834 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003835 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003836 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003837 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003838 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003839 continue;
3840 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003841 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003842 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003843}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003844#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003845
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003846/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003847#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003848#define parse_dollar(as_string, dest, input, quote_mask) \
3849 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003850#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003851#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003852static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003853 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003854 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003855{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003856 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003857
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003858 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003859 if (isalpha(ch)) {
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 Vlasenkod4981312008-07-31 10:34:48 +00003862 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003863 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003864 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003865 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003866 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003867 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003868 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003869 if (!isalnum(ch) && ch != '_')
3870 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003871 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003872 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003873 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003874 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003875 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003876 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003877 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003878 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003879 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003880 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003881 o_addchr(dest, ch | quote_mask);
3882 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003883 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003884 case '$': /* pid */
3885 case '!': /* last bg pid */
3886 case '?': /* last exit code */
3887 case '#': /* number of args */
3888 case '*': /* args */
3889 case '@': /* args */
3890 goto make_one_char_var;
3891 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003892 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3893
Denys Vlasenko74369502010-05-21 19:52:01 +02003894 ch = i_getch(input); /* eat '{' */
3895 nommu_addchr(as_string, ch);
3896
3897 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003898 /* It should be ${?}, or ${#var},
3899 * or even ${?+subst} - operator acting on a special variable,
3900 * or the beginning of variable name.
3901 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003902 if (ch == EOF
3903 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3904 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003905 bad_dollar_syntax:
3906 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003907 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3908 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02003909 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003910 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003911 ch |= quote_mask;
3912
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003913 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003914 * However, this regresses some of our testsuite cases
3915 * which check invalid constructs like ${%}.
3916 * Oh well... let's check that the var name part is fine... */
3917
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003918 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003919 unsigned pos;
3920
Denys Vlasenko74369502010-05-21 19:52:01 +02003921 o_addchr(dest, ch);
3922 debug_printf_parse(": '%c'\n", ch);
3923
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003924 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003925 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003926 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003927 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003928
Denys Vlasenko74369502010-05-21 19:52:01 +02003929 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003930 unsigned end_ch;
3931 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003932 /* handle parameter expansions
3933 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3934 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003935 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003936 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003937
3938 /* Eat everything until closing '}' (or ':') */
3939 end_ch = '}';
3940 if (ENABLE_HUSH_BASH_COMPAT
3941 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003942 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003943 ) {
3944 /* It's ${var:N[:M]} thing */
3945 end_ch = '}' * 0x100 + ':';
3946 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003947 if (ENABLE_HUSH_BASH_COMPAT
3948 && ch == '/'
3949 ) {
3950 /* It's ${var/[/]pattern[/repl]} thing */
3951 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3952 i_getch(input);
3953 nommu_addchr(as_string, '/');
3954 ch = '\\';
3955 }
3956 end_ch = '}' * 0x100 + '/';
3957 }
3958 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003959 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003960 if (!BB_MMU)
3961 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003962#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003963 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003964 if (last_ch == 0) /* error? */
3965 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003966#else
3967#error Simple code to only allow ${var} is not implemented
3968#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003969 if (as_string) {
3970 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003971 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003972 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003973
3974 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3975 /* close the first block: */
3976 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003977 /* while parsing N from ${var:N[:M]}
3978 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003979 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003980 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003981 end_ch = '}';
3982 goto again;
3983 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003984 /* got '}' */
3985 if (end_ch == '}' * 0x100 + ':') {
3986 /* it's ${var:N} - emulate :999999999 */
3987 o_addstr(dest, "999999999");
3988 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003989 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003990 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003991 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003992 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003993 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3994 break;
3995 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003996#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003997 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003998 unsigned pos;
3999
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004000 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004001 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004002# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004003 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004004 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004005 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004006 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4007 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004008 if (!BB_MMU)
4009 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004010 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4011 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004012 if (as_string) {
4013 o_addstr(as_string, dest->data + pos);
4014 o_addchr(as_string, ')');
4015 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004016 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004017 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004018 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004019 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004020# endif
4021# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004022 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4023 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004024 if (!BB_MMU)
4025 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004026 if (!add_till_closing_bracket(dest, input, ')'))
4027 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004028 if (as_string) {
4029 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004030 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004031 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004032 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004033# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004034 break;
4035 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004036#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004037 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004038 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004039 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004040 ch = i_peek(input);
4041 if (isalnum(ch)) { /* it's $_name or $_123 */
4042 ch = '_';
4043 goto make_var;
4044 }
4045 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004046 /* TODO: $_ and $-: */
4047 /* $_ Shell or shell script name; or last argument of last command
4048 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4049 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004050 /* $- Option flags set by set builtin or shell options (-i etc) */
4051 default:
4052 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004053 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004054 debug_printf_parse("parse_dollar return 1 (ok)\n");
4055 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004056#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004057}
4058
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004059#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004060# if ENABLE_HUSH_BASH_COMPAT
4061#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4062 encode_string(dest, input, dquote_end, process_bkslash)
4063# else
4064/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4065#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4066 encode_string(dest, input, dquote_end)
4067# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004068#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004069
4070#else /* !MMU */
4071
4072# if ENABLE_HUSH_BASH_COMPAT
4073/* all parameters are needed, no macro tricks */
4074# else
4075#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4076 encode_string(as_string, dest, input, dquote_end)
4077# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004078#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004079static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004080 o_string *dest,
4081 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004082 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004083 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004084{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004085#if !ENABLE_HUSH_BASH_COMPAT
4086 const int process_bkslash = 1;
4087#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004088 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004089 int next;
4090
4091 again:
4092 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004093 if (ch != EOF)
4094 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004095 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004096 debug_printf_parse("encode_string return 1 (ok)\n");
4097 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004098 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004099 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004100 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004101 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004102 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004103 }
4104 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004105 if (ch != '\n') {
4106 next = i_peek(input);
4107 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004108 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004109 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004110 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004111 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004112 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004113 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004114 }
4115 /* bash:
4116 * "The backslash retains its special meaning [in "..."]
4117 * only when followed by one of the following characters:
4118 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004119 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004120 * NB: in (unquoted) heredoc, above does not apply to ",
4121 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004122 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004123 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004124 ch = i_getch(input); /* eat next */
4125 if (ch == '\n')
4126 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004127 } /* else: ch remains == '\\', and we double it below: */
4128 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004129 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004130 goto again;
4131 }
4132 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004133 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4134 debug_printf_parse("encode_string return 0: "
4135 "parse_dollar returned 0 (error)\n");
4136 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004137 }
4138 goto again;
4139 }
4140#if ENABLE_HUSH_TICK
4141 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004142 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004143 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4144 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004145 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4146 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004147 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4148 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004149 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004150 }
4151#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004152 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004153 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004154#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004155}
4156
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004157/*
4158 * Scan input until EOF or end_trigger char.
4159 * Return a list of pipes to execute, or NULL on EOF
4160 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004161 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004162 * reset parsing machinery and start parsing anew,
4163 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004164 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004165static struct pipe *parse_stream(char **pstring,
4166 struct in_str *input,
4167 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004168{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004169 struct parse_context ctx;
4170 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004171 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004172
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004173 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004174 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004175 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004176 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004177 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004178 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004179
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004180 /* If very first arg is "" or '', dest.data may end up NULL.
4181 * Preventing this: */
4182 o_addchr(&dest, '\0');
4183 dest.length = 0;
4184
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004185 /* We used to separate words on $IFS here. This was wrong.
4186 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004187 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004188 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004189
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004190 if (MAYBE_ASSIGNMENT != 0)
4191 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004192 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004193 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004194 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004195 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004196 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004197 int ch;
4198 int next;
4199 int redir_fd;
4200 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004201
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004202 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004203 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004204 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004205 if (ch == EOF) {
4206 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004207
4208 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004209 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004210 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004211 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004212 /* end_trigger == '}' case errors out earlier,
4213 * checking only ')' */
4214 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004215 syntax_error_unterm_ch('(');
4216 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004217 }
4218
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004219 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004220 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004221 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004222 o_free(&dest);
4223 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004224 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004225 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004226 /* (this makes bare "&" cmd a no-op.
4227 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004228 if (pi->num_cmds == 0
4229 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4230 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004231 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004232 pi = NULL;
4233 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004234#if !BB_MMU
4235 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4236 if (pstring)
4237 *pstring = ctx.as_string.data;
4238 else
4239 o_free_unsafe(&ctx.as_string);
4240#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004241 debug_leave();
4242 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004243 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004244 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004245 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004246
4247 next = '\0';
4248 if (ch != '\n')
4249 next = i_peek(input);
4250
4251 is_special = "{}<>;&|()#'" /* special outside of "str" */
4252 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4253 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004254 if (ctx.command->argv /* word [word]{... - non-special */
4255 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004256 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004257 || (next != ';' /* }; - special */
4258 && next != ')' /* }) - special */
4259 && next != '&' /* }& and }&& ... - special */
4260 && next != '|' /* }|| ... - special */
4261 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004262 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004263 ) {
4264 /* They are not special, skip "{}" */
4265 is_special += 2;
4266 }
4267 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004268 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004269
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004270 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004271 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004272 o_addQchr(&dest, ch);
4273 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4274 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004275 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004276 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004277 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004278 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004279 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004280 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004281 continue;
4282 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004283
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004284 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004285 if (done_word(&dest, &ctx)) {
4286 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004287 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004288 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004289 /* Is this a case when newline is simply ignored?
4290 * Some examples:
4291 * "cmd | <newline> cmd ..."
4292 * "case ... in <newline> word) ..."
4293 */
4294 if (IS_NULL_CMD(ctx.command)
4295 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004296 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004297 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004298 * Without check #1, interactive shell
4299 * ignores even bare <newline>,
4300 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004301 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004302 * ps2> _ <=== wrong, should be ps1
4303 * Without check #2, "cmd & <newline>"
4304 * is similarly mistreated.
4305 * (BTW, this makes "cmd & cmd"
4306 * and "cmd && cmd" non-orthogonal.
4307 * Really, ask yourself, why
4308 * "cmd && <newline>" doesn't start
4309 * cmd but waits for more input?
4310 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004311 */
4312 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004313 if (pi->num_cmds != 0 /* check #1 */
4314 && pi->followup != PIPE_BG /* check #2 */
4315 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004316 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004317 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004318 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004319 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004320 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004321 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4322 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004323 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004324 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004325 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004326 heredoc_cnt = 0;
4327 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004328 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004329 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004330 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004331 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004332 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004333 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004334 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004335
4336 /* "cmd}" or "cmd }..." without semicolon or &:
4337 * } is an ordinary char in this case, even inside { cmd; }
4338 * Pathological example: { ""}; } should exec "}" cmd
4339 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004340 if (ch == '}') {
4341 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4342 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004343 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004344 ) {
4345 goto ordinary_char;
4346 }
4347 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4348 goto skip_end_trigger;
4349 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004350 }
4351
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004352 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004353 && (ch != ';' || heredoc_cnt == 0)
4354#if ENABLE_HUSH_CASE
4355 && (ch != ')'
4356 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004357 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004358 )
4359#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004360 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004361 if (heredoc_cnt) {
4362 /* This is technically valid:
4363 * { cat <<HERE; }; echo Ok
4364 * heredoc
4365 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004366 * HERE
4367 * but we don't support this.
4368 * We require heredoc to be in enclosing {}/(),
4369 * if any.
4370 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004371 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004372 goto parse_error;
4373 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004374 if (done_word(&dest, &ctx)) {
4375 goto parse_error;
4376 }
4377 done_pipe(&ctx, PIPE_SEQ);
4378 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004379 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004380 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004381 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004382 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004383 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004384 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004385#if !BB_MMU
4386 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4387 if (pstring)
4388 *pstring = ctx.as_string.data;
4389 else
4390 o_free_unsafe(&ctx.as_string);
4391#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004392 debug_leave();
4393 debug_printf_parse("parse_stream return %p: "
4394 "end_trigger char found\n",
4395 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004396 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004397 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004398 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004399 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004400 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004401 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004402
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004403 /* Catch <, > before deciding whether this word is
4404 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4405 switch (ch) {
4406 case '>':
4407 redir_fd = redirect_opt_num(&dest);
4408 if (done_word(&dest, &ctx)) {
4409 goto parse_error;
4410 }
4411 redir_style = REDIRECT_OVERWRITE;
4412 if (next == '>') {
4413 redir_style = REDIRECT_APPEND;
4414 ch = i_getch(input);
4415 nommu_addchr(&ctx.as_string, ch);
4416 }
4417#if 0
4418 else if (next == '(') {
4419 syntax_error(">(process) not supported");
4420 goto parse_error;
4421 }
4422#endif
4423 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4424 goto parse_error;
4425 continue; /* back to top of while (1) */
4426 case '<':
4427 redir_fd = redirect_opt_num(&dest);
4428 if (done_word(&dest, &ctx)) {
4429 goto parse_error;
4430 }
4431 redir_style = REDIRECT_INPUT;
4432 if (next == '<') {
4433 redir_style = REDIRECT_HEREDOC;
4434 heredoc_cnt++;
4435 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4436 ch = i_getch(input);
4437 nommu_addchr(&ctx.as_string, ch);
4438 } else if (next == '>') {
4439 redir_style = REDIRECT_IO;
4440 ch = i_getch(input);
4441 nommu_addchr(&ctx.as_string, ch);
4442 }
4443#if 0
4444 else if (next == '(') {
4445 syntax_error("<(process) not supported");
4446 goto parse_error;
4447 }
4448#endif
4449 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4450 goto parse_error;
4451 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004452 case '#':
4453 if (dest.length == 0 && !dest.has_quoted_part) {
4454 /* skip "#comment" */
4455 while (1) {
4456 ch = i_peek(input);
4457 if (ch == EOF || ch == '\n')
4458 break;
4459 i_getch(input);
4460 /* note: we do not add it to &ctx.as_string */
4461 }
4462 nommu_addchr(&ctx.as_string, '\n');
4463 continue; /* back to top of while (1) */
4464 }
4465 break;
4466 case '\\':
4467 if (next == '\n') {
4468 /* It's "\<newline>" */
4469#if !BB_MMU
4470 /* Remove trailing '\' from ctx.as_string */
4471 ctx.as_string.data[--ctx.as_string.length] = '\0';
4472#endif
4473 ch = i_getch(input); /* eat it */
4474 continue; /* back to top of while (1) */
4475 }
4476 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004477 }
4478
4479 if (dest.o_assignment == MAYBE_ASSIGNMENT
4480 /* check that we are not in word in "a=1 2>word b=1": */
4481 && !ctx.pending_redirect
4482 ) {
4483 /* ch is a special char and thus this word
4484 * cannot be an assignment */
4485 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004486 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004487 }
4488
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004489 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4490
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004491 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004492 case '#': /* non-comment #: "echo a#b" etc */
4493 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004494 break;
4495 case '\\':
4496 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004497 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004498 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004499 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004500 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004501 /* note: ch != '\n' (that case does not reach this place) */
4502 o_addchr(&dest, '\\');
4503 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4504 o_addchr(&dest, ch);
4505 nommu_addchr(&ctx.as_string, ch);
4506 /* Example: echo Hello \2>file
4507 * we need to know that word 2 is quoted */
4508 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004509 break;
4510 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004511 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004512 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004513 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004514 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004515 }
Eric Andersen25f27032001-04-26 23:22:31 +00004516 break;
4517 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004518 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004519 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004520 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004521 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004522 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004523 goto parse_error;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004524 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004525 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004526 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004527 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004528 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004529 }
Eric Andersen25f27032001-04-26 23:22:31 +00004530 break;
4531 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004532 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004533 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004534 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004535 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004536 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004537 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004538 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004539#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004540 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004541 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004542
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004543 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4544 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004545 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004546 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4547 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004548# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004549 o_addstr(&ctx.as_string, dest.data + pos);
4550 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004551# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004552 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4553 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004554 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004555 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004556#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004557 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004558#if ENABLE_HUSH_CASE
4559 case_semi:
4560#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004561 if (done_word(&dest, &ctx)) {
4562 goto parse_error;
4563 }
4564 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004565#if ENABLE_HUSH_CASE
4566 /* Eat multiple semicolons, detect
4567 * whether it means something special */
4568 while (1) {
4569 ch = i_peek(input);
4570 if (ch != ';')
4571 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004572 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004573 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004574 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004575 ctx.ctx_dsemicolon = 1;
4576 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004577 break;
4578 }
4579 }
4580#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004581 new_cmd:
4582 /* We just finished a cmd. New one may start
4583 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004584 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004585 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004586 break;
4587 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004588 if (done_word(&dest, &ctx)) {
4589 goto parse_error;
4590 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004591 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004592 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004593 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004594 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004595 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004596 done_pipe(&ctx, PIPE_BG);
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 Vlasenkob6e65562009-04-03 16:49:04 +00004600 if (done_word(&dest, &ctx)) {
4601 goto parse_error;
4602 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004603#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004604 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004605 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004606#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004607 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004608 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004609 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004610 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004611 } else {
4612 /* we could pick up a file descriptor choice here
4613 * with redirect_opt_num(), but bash doesn't do it.
4614 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004615 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004616#if !BB_MMU
4617 o_reset_to_empty_unquoted(&ctx.as_string);
4618#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004619 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004620 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004621 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004622#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004623 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004624 if (ctx.ctx_res_w == RES_MATCH
4625 && ctx.command->argv == NULL /* not (word|(... */
4626 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004627 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004628 ) {
4629 continue;
4630 }
4631#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004632 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004633 if (parse_group(&dest, &ctx, input, ch) != 0) {
4634 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004635 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004636 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004637 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004638#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004639 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004640 goto case_semi;
4641#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004642 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004643 /* proper use of this character is caught by end_trigger:
4644 * if we see {, we call parse_group(..., end_trigger='}')
4645 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004646 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004647 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004648 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004649 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004650 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004651 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004652 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004653
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004654 parse_error:
4655 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004656 struct parse_context *pctx;
4657 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004658
4659 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004660 * Sample for finding leaks on syntax error recovery path.
4661 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004662 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004663 * Samples to catch leaks at execution:
4664 * while if (true | {true;}); then echo ok; fi; do break; done
4665 * 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 +00004666 */
4667 pctx = &ctx;
4668 do {
4669 /* Update pipe/command counts,
4670 * otherwise freeing may miss some */
4671 done_pipe(pctx, PIPE_SEQ);
4672 debug_printf_clean("freeing list %p from ctx %p\n",
4673 pctx->list_head, pctx);
4674 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004675 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004676 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004677#if !BB_MMU
4678 o_free_unsafe(&pctx->as_string);
4679#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004680 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004681 if (pctx != &ctx) {
4682 free(pctx);
4683 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004684 IF_HAS_KEYWORDS(pctx = p2;)
4685 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004686
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004687 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004688 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004689#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004690 if (pstring)
4691 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004692#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004693 debug_leave();
4694 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004695 }
Eric Andersen25f27032001-04-26 23:22:31 +00004696}
4697
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004698
4699/*** Execution routines ***/
4700
4701/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004702#if !ENABLE_HUSH_BASH_COMPAT
4703/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4704#define expand_string_to_string(str, do_unbackslash) \
4705 expand_string_to_string(str)
4706#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004707static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004708#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004709static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004710#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004711
4712/* expand_strvec_to_strvec() takes a list of strings, expands
4713 * all variable references within and returns a pointer to
4714 * a list of expanded strings, possibly with larger number
4715 * of strings. (Think VAR="a b"; echo $VAR).
4716 * This new list is allocated as a single malloc block.
4717 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004718 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004719 * Caller can deallocate entire list by single free(list). */
4720
Denys Vlasenko238081f2010-10-03 14:26:26 +02004721/* A horde of its helpers come first: */
4722
4723static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4724{
4725 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004726 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004727
Denys Vlasenko9e800222010-10-03 14:28:04 +02004728#if ENABLE_HUSH_BRACE_EXPANSION
4729 if (c == '{' || c == '}') {
4730 /* { -> \{, } -> \} */
4731 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004732 /* And now we want to add { or } and continue:
4733 * o_addchr(o, c);
4734 * continue;
4735 * luckily, just falling throught achieves this.
4736 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004737 }
4738#endif
4739 o_addchr(o, c);
4740 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004741 /* \z -> \\\z; \<eol> -> \\<eol> */
4742 o_addchr(o, '\\');
4743 if (len) {
4744 len--;
4745 o_addchr(o, '\\');
4746 o_addchr(o, *str++);
4747 }
4748 }
4749 }
4750}
4751
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004752/* Store given string, finalizing the word and starting new one whenever
4753 * we encounter IFS char(s). This is used for expanding variable values.
4754 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4755static int expand_on_ifs(o_string *output, int n, const char *str)
4756{
4757 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004758 int word_len;
4759
4760 if (!*str) /* EOL - do not finalize word */
4761 break;
4762 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004763 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004764 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02004765 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004766 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004767 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004768 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004769 * Example: "v='\*'; echo b$v" prints "b\*"
4770 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004771 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004772 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004773 /*/ Why can't we do it easier? */
4774 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4775 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4776 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004777 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004778 if (!*str) /* EOL - do not finalize word */
4779 break;
4780 goto finalize; /* optimization (can just fall thru) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004781 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004782 /* Case "v=' a'; echo ''$v": we do need to finalize empty word */
4783 if (output->has_quoted_part
4784 /* Case "v=' a'; echo $v":
4785 * here nothing precedes the space in $v expansion,
4786 * therefore we should not finish the word
4787 * (IOW: if there *is* word to finalize, only then do it)
4788 */
4789 || (output->length && output->data[output->length - 1])
4790 ) {
4791 finalize:
4792 o_addchr(output, '\0');
4793 debug_print_list("expand_on_ifs", output, n);
4794 n = o_save_ptr(output, n);
4795 }
4796 str += strspn(str, G.ifs); /* skip IFS chars */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004797 }
4798 debug_print_list("expand_on_ifs[1]", output, n);
4799 return n;
4800}
4801
4802/* Helper to expand $((...)) and heredoc body. These act as if
4803 * they are in double quotes, with the exception that they are not :).
4804 * Just the rules are similar: "expand only $var and `cmd`"
4805 *
4806 * Returns malloced string.
4807 * As an optimization, we return NULL if expansion is not needed.
4808 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004809#if !ENABLE_HUSH_BASH_COMPAT
4810/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4811#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4812 encode_then_expand_string(str)
4813#endif
4814static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004815{
4816 char *exp_str;
4817 struct in_str input;
4818 o_string dest = NULL_O_STRING;
4819
4820 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004821 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004822#if ENABLE_HUSH_TICK
4823 && !strchr(str, '`')
4824#endif
4825 ) {
4826 return NULL;
4827 }
4828
4829 /* We need to expand. Example:
4830 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4831 */
4832 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004833 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004834//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004835 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004836 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004837 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4838 o_free_unsafe(&dest);
4839 return exp_str;
4840}
4841
4842#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004843static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004844{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004845 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004846 arith_t res;
4847 char *exp_str;
4848
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004849 math_state.lookupvar = get_local_var_value;
4850 math_state.setvar = set_local_var_from_halves;
4851 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004852 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004853 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004854 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004855 if (errmsg_p)
4856 *errmsg_p = math_state.errmsg;
4857 if (math_state.errmsg)
4858 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004859 return res;
4860}
4861#endif
4862
4863#if ENABLE_HUSH_BASH_COMPAT
4864/* ${var/[/]pattern[/repl]} helpers */
4865static char *strstr_pattern(char *val, const char *pattern, int *size)
4866{
4867 while (1) {
4868 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4869 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4870 if (end) {
4871 *size = end - val;
4872 return val;
4873 }
4874 if (*val == '\0')
4875 return NULL;
4876 /* Optimization: if "*pat" did not match the start of "string",
4877 * we know that "tring", "ring" etc will not match too:
4878 */
4879 if (pattern[0] == '*')
4880 return NULL;
4881 val++;
4882 }
4883}
4884static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4885{
4886 char *result = NULL;
4887 unsigned res_len = 0;
4888 unsigned repl_len = strlen(repl);
4889
4890 while (1) {
4891 int size;
4892 char *s = strstr_pattern(val, pattern, &size);
4893 if (!s)
4894 break;
4895
4896 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4897 memcpy(result + res_len, val, s - val);
4898 res_len += s - val;
4899 strcpy(result + res_len, repl);
4900 res_len += repl_len;
4901 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4902
4903 val = s + size;
4904 if (exp_op == '/')
4905 break;
4906 }
4907 if (val[0] && result) {
4908 result = xrealloc(result, res_len + strlen(val) + 1);
4909 strcpy(result + res_len, val);
4910 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4911 }
4912 debug_printf_varexp("result:'%s'\n", result);
4913 return result;
4914}
4915#endif
4916
4917/* Helper:
4918 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4919 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004920static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004921{
4922 const char *val = NULL;
4923 char *to_be_freed = NULL;
4924 char *p = *pp;
4925 char *var;
4926 char first_char;
4927 char exp_op;
4928 char exp_save = exp_save; /* for compiler */
4929 char *exp_saveptr; /* points to expansion operator */
4930 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004931 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004932
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004933 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004934 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004935 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004936 arg0 = arg[0];
4937 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004938 exp_op = 0;
4939
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004940 if (first_char == '#' /* ${#... */
4941 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4942 ) {
4943 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004944 var++;
4945 exp_op = 'L';
4946 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004947 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004948 if (exp_saveptr /* if 2nd char is one of expansion operators */
4949 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4950 ) {
4951 /* ${?:0}, ${#[:]%0} etc */
4952 exp_saveptr = var + 1;
4953 } else {
4954 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4955 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4956 }
4957 exp_op = exp_save = *exp_saveptr;
4958 if (exp_op) {
4959 exp_word = exp_saveptr + 1;
4960 if (exp_op == ':') {
4961 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004962//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004963 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004964 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004965 ) {
4966 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4967 exp_op = ':';
4968 exp_word--;
4969 }
4970 }
4971 *exp_saveptr = '\0';
4972 } /* else: it's not an expansion op, but bare ${var} */
4973 }
4974
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004975 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004976 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004977 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004978 int n = xatoi_positive(var);
4979 if (n < G.global_argc)
4980 val = G.global_argv[n];
4981 /* else val remains NULL: $N with too big N */
4982 } else {
4983 switch (var[0]) {
4984 case '$': /* pid */
4985 val = utoa(G.root_pid);
4986 break;
4987 case '!': /* bg pid */
4988 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4989 break;
4990 case '?': /* exitcode */
4991 val = utoa(G.last_exitcode);
4992 break;
4993 case '#': /* argc */
4994 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4995 break;
4996 default:
4997 val = get_local_var_value(var);
4998 }
4999 }
5000
5001 /* Handle any expansions */
5002 if (exp_op == 'L') {
5003 debug_printf_expand("expand: length(%s)=", val);
5004 val = utoa(val ? strlen(val) : 0);
5005 debug_printf_expand("%s\n", val);
5006 } else if (exp_op) {
5007 if (exp_op == '%' || exp_op == '#') {
5008 /* Standard-mandated substring removal ops:
5009 * ${parameter%word} - remove smallest suffix pattern
5010 * ${parameter%%word} - remove largest suffix pattern
5011 * ${parameter#word} - remove smallest prefix pattern
5012 * ${parameter##word} - remove largest prefix pattern
5013 *
5014 * Word is expanded to produce a glob pattern.
5015 * Then var's value is matched to it and matching part removed.
5016 */
5017 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005018 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005019 char *exp_exp_word;
5020 char *loc;
5021 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005022 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005023 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005024 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005025 if (exp_exp_word)
5026 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005027 /* HACK ALERT. We depend here on the fact that
5028 * G.global_argv and results of utoa and get_local_var_value
5029 * are actually in writable memory:
5030 * scan_and_match momentarily stores NULs there. */
5031 t = (char*)val;
5032 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005033 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005034 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005035 free(exp_exp_word);
5036 if (loc) { /* match was found */
5037 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005038 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005039 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005040 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005041 }
5042 }
5043 }
5044#if ENABLE_HUSH_BASH_COMPAT
5045 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005046 /* It's ${var/[/]pattern[/repl]} thing.
5047 * Note that in encoded form it has TWO parts:
5048 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005049 * and if // is used, it is encoded as \:
5050 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005051 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005052 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005053 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005054 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005055 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005056 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005057 * by the usual expansion rules:
5058 * >az; >bz;
5059 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5060 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5061 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5062 * v='a bz'; echo ${v/a*z/\z} prints "z"
5063 * (note that a*z _pattern_ is never globbed!)
5064 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005065 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005066 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005067 if (!pattern)
5068 pattern = xstrdup(exp_word);
5069 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5070 *p++ = SPECIAL_VAR_SYMBOL;
5071 exp_word = p;
5072 p = strchr(p, SPECIAL_VAR_SYMBOL);
5073 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005074 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005075 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5076 /* HACK ALERT. We depend here on the fact that
5077 * G.global_argv and results of utoa and get_local_var_value
5078 * are actually in writable memory:
5079 * replace_pattern momentarily stores NULs there. */
5080 t = (char*)val;
5081 to_be_freed = replace_pattern(t,
5082 pattern,
5083 (repl ? repl : exp_word),
5084 exp_op);
5085 if (to_be_freed) /* at least one replace happened */
5086 val = to_be_freed;
5087 free(pattern);
5088 free(repl);
5089 }
5090 }
5091#endif
5092 else if (exp_op == ':') {
5093#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5094 /* It's ${var:N[:M]} bashism.
5095 * Note that in encoded form it has TWO parts:
5096 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5097 */
5098 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005099 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005100
Denys Vlasenko063847d2010-09-15 13:33:02 +02005101 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5102 if (errmsg)
5103 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005104 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5105 *p++ = SPECIAL_VAR_SYMBOL;
5106 exp_word = p;
5107 p = strchr(p, SPECIAL_VAR_SYMBOL);
5108 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005109 len = expand_and_evaluate_arith(exp_word, &errmsg);
5110 if (errmsg)
5111 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005112 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005113 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005114 if (beg < 0) /* bash compat */
5115 beg = 0;
5116 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005117 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005118 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005119 val = NULL;
5120 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005121 /* Paranoia. What if user entered 9999999999999
5122 * which fits in arith_t but not int? */
5123 if (len >= INT_MAX)
5124 len = INT_MAX;
5125 val = to_be_freed = xstrndup(val + beg, len);
5126 }
5127 debug_printf_varexp("val:'%s'\n", val);
5128 } else
5129#endif
5130 {
5131 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005132 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005133 }
5134 } else { /* one of "-=+?" */
5135 /* Standard-mandated substitution ops:
5136 * ${var?word} - indicate error if unset
5137 * If var is unset, word (or a message indicating it is unset
5138 * if word is null) is written to standard error
5139 * and the shell exits with a non-zero exit status.
5140 * Otherwise, the value of var is substituted.
5141 * ${var-word} - use default value
5142 * If var is unset, word is substituted.
5143 * ${var=word} - assign and use default value
5144 * If var is unset, word is assigned to var.
5145 * In all cases, final value of var is substituted.
5146 * ${var+word} - use alternative value
5147 * If var is unset, null is substituted.
5148 * Otherwise, word is substituted.
5149 *
5150 * Word is subjected to tilde expansion, parameter expansion,
5151 * command substitution, and arithmetic expansion.
5152 * If word is not needed, it is not expanded.
5153 *
5154 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5155 * but also treat null var as if it is unset.
5156 */
5157 int use_word = (!val || ((exp_save == ':') && !val[0]));
5158 if (exp_op == '+')
5159 use_word = !use_word;
5160 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5161 (exp_save == ':') ? "true" : "false", use_word);
5162 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005163 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005164 if (to_be_freed)
5165 exp_word = to_be_freed;
5166 if (exp_op == '?') {
5167 /* mimic bash message */
5168 die_if_script("%s: %s",
5169 var,
5170 exp_word[0] ? exp_word : "parameter null or not set"
5171 );
5172//TODO: how interactive bash aborts expansion mid-command?
5173 } else {
5174 val = exp_word;
5175 }
5176
5177 if (exp_op == '=') {
5178 /* ${var=[word]} or ${var:=[word]} */
5179 if (isdigit(var[0]) || var[0] == '#') {
5180 /* mimic bash message */
5181 die_if_script("$%s: cannot assign in this way", var);
5182 val = NULL;
5183 } else {
5184 char *new_var = xasprintf("%s=%s", var, val);
5185 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5186 }
5187 }
5188 }
5189 } /* one of "-=+?" */
5190
5191 *exp_saveptr = exp_save;
5192 } /* if (exp_op) */
5193
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005194 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005195
5196 *pp = p;
5197 *to_be_freed_pp = to_be_freed;
5198 return val;
5199}
5200
5201/* Expand all variable references in given string, adding words to list[]
5202 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5203 * to be filled). This routine is extremely tricky: has to deal with
5204 * variables/parameters with whitespace, $* and $@, and constructs like
5205 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005206static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005207{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005208 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005209 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005210 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005211 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005212 char *p;
5213
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005214 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5215 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005216 debug_print_list("expand_vars_to_list", output, n);
5217 n = o_save_ptr(output, n);
5218 debug_print_list("expand_vars_to_list[0]", output, n);
5219
5220 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5221 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005222 char *to_be_freed = NULL;
5223 const char *val = NULL;
5224#if ENABLE_HUSH_TICK
5225 o_string subst_result = NULL_O_STRING;
5226#endif
5227#if ENABLE_SH_MATH_SUPPORT
5228 char arith_buf[sizeof(arith_t)*3 + 2];
5229#endif
5230 o_addblock(output, arg, p - arg);
5231 debug_print_list("expand_vars_to_list[1]", output, n);
5232 arg = ++p;
5233 p = strchr(p, SPECIAL_VAR_SYMBOL);
5234
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005235 /* Fetch special var name (if it is indeed one of them)
5236 * and quote bit, force the bit on if singleword expansion -
5237 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005238 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005239
5240 /* Is this variable quoted and thus expansion can't be null?
5241 * "$@" is special. Even if quoted, it can still
5242 * expand to nothing (not even an empty string),
5243 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005244 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005245 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005246
5247 switch (first_ch & 0x7f) {
5248 /* Highest bit in first_ch indicates that var is double-quoted */
5249 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005250 case '@': {
5251 int i;
5252 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005253 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005254 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005255 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005256 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005257 while (G.global_argv[i]) {
5258 n = expand_on_ifs(output, n, G.global_argv[i]);
5259 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5260 if (G.global_argv[i++][0] && G.global_argv[i]) {
5261 /* this argv[] is not empty and not last:
5262 * put terminating NUL, start new word */
5263 o_addchr(output, '\0');
5264 debug_print_list("expand_vars_to_list[2]", output, n);
5265 n = o_save_ptr(output, n);
5266 debug_print_list("expand_vars_to_list[3]", output, n);
5267 }
5268 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005269 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005270 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005271 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005272 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005273 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005274 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005275 while (1) {
5276 o_addQstr(output, G.global_argv[i]);
5277 if (++i >= G.global_argc)
5278 break;
5279 o_addchr(output, '\0');
5280 debug_print_list("expand_vars_to_list[4]", output, n);
5281 n = o_save_ptr(output, n);
5282 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005283 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005284 while (1) {
5285 o_addQstr(output, G.global_argv[i]);
5286 if (!G.global_argv[++i])
5287 break;
5288 if (G.ifs[0])
5289 o_addchr(output, G.ifs[0]);
5290 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005291 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005292 }
5293 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005294 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005295 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5296 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005297 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005298 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005299 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005300 break;
5301#if ENABLE_HUSH_TICK
5302 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005303 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005304 arg++;
5305 /* Can't just stuff it into output o_string,
5306 * expanded result may need to be globbed
5307 * and $IFS-splitted */
5308 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5309 G.last_exitcode = process_command_subs(&subst_result, arg);
5310 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5311 val = subst_result.data;
5312 goto store_val;
5313#endif
5314#if ENABLE_SH_MATH_SUPPORT
5315 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5316 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005317
5318 arg++; /* skip '+' */
5319 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5320 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005321 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005322 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5323 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005324 val = arith_buf;
5325 break;
5326 }
5327#endif
5328 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005329 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005330 IF_HUSH_TICK(store_val:)
5331 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005332 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5333 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005334 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005335 n = expand_on_ifs(output, n, val);
5336 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005337 }
5338 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005339 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005340 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5341 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005342 }
5343 break;
5344
5345 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5346
5347 if (val && val[0]) {
5348 o_addQstr(output, val);
5349 }
5350 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005351
5352 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5353 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005354 if (*p != SPECIAL_VAR_SYMBOL)
5355 *p = SPECIAL_VAR_SYMBOL;
5356
5357#if ENABLE_HUSH_TICK
5358 o_free(&subst_result);
5359#endif
5360 arg = ++p;
5361 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5362
5363 if (arg[0]) {
5364 debug_print_list("expand_vars_to_list[a]", output, n);
5365 /* this part is literal, and it was already pre-quoted
5366 * if needed (much earlier), do not use o_addQstr here! */
5367 o_addstr_with_NUL(output, arg);
5368 debug_print_list("expand_vars_to_list[b]", output, n);
5369 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005370 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005371 ) {
5372 n--;
5373 /* allow to reuse list[n] later without re-growth */
5374 output->has_empty_slot = 1;
5375 } else {
5376 o_addchr(output, '\0');
5377 }
5378
5379 return n;
5380}
5381
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005382static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005383{
5384 int n;
5385 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005386 o_string output = NULL_O_STRING;
5387
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005388 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005389
5390 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005391 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005392 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005393 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005394 }
5395 debug_print_list("expand_variables", &output, n);
5396
5397 /* output.data (malloced in one block) gets returned in "list" */
5398 list = o_finalize_list(&output, n);
5399 debug_print_strings("expand_variables[1]", list);
5400 return list;
5401}
5402
5403static char **expand_strvec_to_strvec(char **argv)
5404{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005405 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005406}
5407
5408#if ENABLE_HUSH_BASH_COMPAT
5409static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5410{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005411 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005412}
5413#endif
5414
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005415/* Used for expansion of right hand of assignments,
5416 * $((...)), heredocs, variable espansion parts.
5417 *
5418 * NB: should NOT do globbing!
5419 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5420 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005421static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005422{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005423#if !ENABLE_HUSH_BASH_COMPAT
5424 const int do_unbackslash = 1;
5425#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005426 char *argv[2], **list;
5427
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005428 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005429 /* This is generally an optimization, but it also
5430 * handles "", which otherwise trips over !list[0] check below.
5431 * (is this ever happens that we actually get str="" here?)
5432 */
5433 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5434 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005435 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005436 return xstrdup(str);
5437 }
5438
5439 argv[0] = (char*)str;
5440 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005441 list = expand_variables(argv, do_unbackslash
5442 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5443 : EXP_FLAG_SINGLEWORD
5444 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005445 if (HUSH_DEBUG)
5446 if (!list[0] || list[1])
5447 bb_error_msg_and_die("BUG in varexp2");
5448 /* actually, just move string 2*sizeof(char*) bytes back */
5449 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005450 if (do_unbackslash)
5451 unbackslash((char*)list);
5452 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005453 return (char*)list;
5454}
5455
5456/* Used for "eval" builtin */
5457static char* expand_strvec_to_string(char **argv)
5458{
5459 char **list;
5460
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005461 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005462 /* Convert all NULs to spaces */
5463 if (list[0]) {
5464 int n = 1;
5465 while (list[n]) {
5466 if (HUSH_DEBUG)
5467 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5468 bb_error_msg_and_die("BUG in varexp3");
5469 /* bash uses ' ' regardless of $IFS contents */
5470 list[n][-1] = ' ';
5471 n++;
5472 }
5473 }
5474 overlapping_strcpy((char*)list, list[0]);
5475 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5476 return (char*)list;
5477}
5478
5479static char **expand_assignments(char **argv, int count)
5480{
5481 int i;
5482 char **p;
5483
5484 G.expanded_assignments = p = NULL;
5485 /* Expand assignments into one string each */
5486 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005487 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005488 }
5489 G.expanded_assignments = NULL;
5490 return p;
5491}
5492
5493
5494#if BB_MMU
5495/* never called */
5496void re_execute_shell(char ***to_free, const char *s,
5497 char *g_argv0, char **g_argv,
5498 char **builtin_argv) NORETURN;
5499
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005500static void switch_off_special_sigs(unsigned mask)
5501{
5502 unsigned sig = 0;
5503 while ((mask >>= 1) != 0) {
5504 sig++;
5505 if (!(mask & 1))
5506 continue;
5507 if (G.traps) {
5508 if (G.traps[sig] && !G.traps[sig][0])
5509 /* trap is '', has to remain SIG_IGN */
5510 continue;
5511 free(G.traps[sig]);
5512 G.traps[sig] = NULL;
5513 }
5514 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005515 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005516 }
5517}
5518
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005519static void reset_traps_to_defaults(void)
5520{
5521 /* This function is always called in a child shell
5522 * after fork (not vfork, NOMMU doesn't use this function).
5523 */
5524 unsigned sig;
5525 unsigned mask;
5526
5527 /* Child shells are not interactive.
5528 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5529 * Testcase: (while :; do :; done) + ^Z should background.
5530 * Same goes for SIGTERM, SIGHUP, SIGINT.
5531 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005532 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5533 if (!G.traps && !mask)
5534 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005535
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005536 /* Switch off special sigs */
5537 switch_off_special_sigs(mask);
5538#if ENABLE_HUSH_JOB
5539 G_fatal_sig_mask = 0;
5540#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005541 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005542 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5543 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005544
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005545 if (!G.traps)
5546 return;
5547
5548 /* Reset all sigs to default except ones with empty traps */
5549 for (sig = 0; sig < NSIG; sig++) {
5550 if (!G.traps[sig])
5551 continue; /* no trap: nothing to do */
5552 if (!G.traps[sig][0])
5553 continue; /* empty trap: has to remain SIG_IGN */
5554 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005555 free(G.traps[sig]);
5556 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005557 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005558 if (sig == 0)
5559 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005560 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005561 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005562}
5563
5564#else /* !BB_MMU */
5565
5566static void re_execute_shell(char ***to_free, const char *s,
5567 char *g_argv0, char **g_argv,
5568 char **builtin_argv) NORETURN;
5569static void re_execute_shell(char ***to_free, const char *s,
5570 char *g_argv0, char **g_argv,
5571 char **builtin_argv)
5572{
5573# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5574 /* delims + 2 * (number of bytes in printed hex numbers) */
5575 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5576 char *heredoc_argv[4];
5577 struct variable *cur;
5578# if ENABLE_HUSH_FUNCTIONS
5579 struct function *funcp;
5580# endif
5581 char **argv, **pp;
5582 unsigned cnt;
5583 unsigned long long empty_trap_mask;
5584
5585 if (!g_argv0) { /* heredoc */
5586 argv = heredoc_argv;
5587 argv[0] = (char *) G.argv0_for_re_execing;
5588 argv[1] = (char *) "-<";
5589 argv[2] = (char *) s;
5590 argv[3] = NULL;
5591 pp = &argv[3]; /* used as pointer to empty environment */
5592 goto do_exec;
5593 }
5594
5595 cnt = 0;
5596 pp = builtin_argv;
5597 if (pp) while (*pp++)
5598 cnt++;
5599
5600 empty_trap_mask = 0;
5601 if (G.traps) {
5602 int sig;
5603 for (sig = 1; sig < NSIG; sig++) {
5604 if (G.traps[sig] && !G.traps[sig][0])
5605 empty_trap_mask |= 1LL << sig;
5606 }
5607 }
5608
5609 sprintf(param_buf, NOMMU_HACK_FMT
5610 , (unsigned) G.root_pid
5611 , (unsigned) G.root_ppid
5612 , (unsigned) G.last_bg_pid
5613 , (unsigned) G.last_exitcode
5614 , cnt
5615 , empty_trap_mask
5616 IF_HUSH_LOOPS(, G.depth_of_loop)
5617 );
5618# undef NOMMU_HACK_FMT
5619 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5620 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5621 */
5622 cnt += 6;
5623 for (cur = G.top_var; cur; cur = cur->next) {
5624 if (!cur->flg_export || cur->flg_read_only)
5625 cnt += 2;
5626 }
5627# if ENABLE_HUSH_FUNCTIONS
5628 for (funcp = G.top_func; funcp; funcp = funcp->next)
5629 cnt += 3;
5630# endif
5631 pp = g_argv;
5632 while (*pp++)
5633 cnt++;
5634 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5635 *pp++ = (char *) G.argv0_for_re_execing;
5636 *pp++ = param_buf;
5637 for (cur = G.top_var; cur; cur = cur->next) {
5638 if (strcmp(cur->varstr, hush_version_str) == 0)
5639 continue;
5640 if (cur->flg_read_only) {
5641 *pp++ = (char *) "-R";
5642 *pp++ = cur->varstr;
5643 } else if (!cur->flg_export) {
5644 *pp++ = (char *) "-V";
5645 *pp++ = cur->varstr;
5646 }
5647 }
5648# if ENABLE_HUSH_FUNCTIONS
5649 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5650 *pp++ = (char *) "-F";
5651 *pp++ = funcp->name;
5652 *pp++ = funcp->body_as_string;
5653 }
5654# endif
5655 /* We can pass activated traps here. Say, -Tnn:trap_string
5656 *
5657 * However, POSIX says that subshells reset signals with traps
5658 * to SIG_DFL.
5659 * I tested bash-3.2 and it not only does that with true subshells
5660 * of the form ( list ), but with any forked children shells.
5661 * I set trap "echo W" WINCH; and then tried:
5662 *
5663 * { echo 1; sleep 20; echo 2; } &
5664 * while true; do echo 1; sleep 20; echo 2; break; done &
5665 * true | { echo 1; sleep 20; echo 2; } | cat
5666 *
5667 * In all these cases sending SIGWINCH to the child shell
5668 * did not run the trap. If I add trap "echo V" WINCH;
5669 * _inside_ group (just before echo 1), it works.
5670 *
5671 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005672 */
5673 *pp++ = (char *) "-c";
5674 *pp++ = (char *) s;
5675 if (builtin_argv) {
5676 while (*++builtin_argv)
5677 *pp++ = *builtin_argv;
5678 *pp++ = (char *) "";
5679 }
5680 *pp++ = g_argv0;
5681 while (*g_argv)
5682 *pp++ = *g_argv++;
5683 /* *pp = NULL; - is already there */
5684 pp = environ;
5685
5686 do_exec:
5687 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02005688 /* Don't propagate SIG_IGN to the child */
5689 if (SPECIAL_JOBSTOP_SIGS != 0)
5690 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005691 execve(bb_busybox_exec_path, argv, pp);
5692 /* Fallback. Useful for init=/bin/hush usage etc */
5693 if (argv[0][0] == '/')
5694 execve(argv[0], argv, pp);
5695 xfunc_error_retval = 127;
5696 bb_error_msg_and_die("can't re-execute the shell");
5697}
5698#endif /* !BB_MMU */
5699
5700
5701static int run_and_free_list(struct pipe *pi);
5702
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005703/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005704 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5705 * end_trigger controls how often we stop parsing
5706 * NUL: parse all, execute, return
5707 * ';': parse till ';' or newline, execute, repeat till EOF
5708 */
5709static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005710{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005711 /* Why we need empty flag?
5712 * An obscure corner case "false; ``; echo $?":
5713 * empty command in `` should still set $? to 0.
5714 * But we can't just set $? to 0 at the start,
5715 * this breaks "false; echo `echo $?`" case.
5716 */
5717 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005718 while (1) {
5719 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005720
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005721#if ENABLE_HUSH_INTERACTIVE
5722 if (end_trigger == ';')
5723 inp->promptmode = 0; /* PS1 */
5724#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005725 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005726 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5727 /* If we are in "big" script
5728 * (not in `cmd` or something similar)...
5729 */
5730 if (pipe_list == ERR_PTR && end_trigger == ';') {
5731 /* Discard cached input (rest of line) */
5732 int ch = inp->last_char;
5733 while (ch != EOF && ch != '\n') {
5734 //bb_error_msg("Discarded:'%c'", ch);
5735 ch = i_getch(inp);
5736 }
5737 /* Force prompt */
5738 inp->p = NULL;
5739 /* This stream isn't empty */
5740 empty = 0;
5741 continue;
5742 }
5743 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01005744 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005745 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005746 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005747 debug_print_tree(pipe_list, 0);
5748 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5749 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005750 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005751#if ENABLE_HUSH_FUNCTIONS
5752 if (G.flag_return_in_progress == 1)
5753 break;
5754#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005755 }
Eric Andersen25f27032001-04-26 23:22:31 +00005756}
5757
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005758static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005759{
5760 struct in_str input;
5761 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005762 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005763}
5764
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005765static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005766{
Eric Andersen25f27032001-04-26 23:22:31 +00005767 struct in_str input;
5768 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005769 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005770}
5771
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005772#if ENABLE_HUSH_TICK
5773static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5774{
5775 pid_t pid;
5776 int channel[2];
5777# if !BB_MMU
5778 char **to_free = NULL;
5779# endif
5780
5781 xpipe(channel);
5782 pid = BB_MMU ? xfork() : xvfork();
5783 if (pid == 0) { /* child */
5784 disable_restore_tty_pgrp_on_exit();
5785 /* Process substitution is not considered to be usual
5786 * 'command execution'.
5787 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5788 */
5789 bb_signals(0
5790 + (1 << SIGTSTP)
5791 + (1 << SIGTTIN)
5792 + (1 << SIGTTOU)
5793 , SIG_IGN);
5794 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5795 close(channel[0]); /* NB: close _first_, then move fd! */
5796 xmove_fd(channel[1], 1);
5797 /* Prevent it from trying to handle ctrl-z etc */
5798 IF_HUSH_JOB(G.run_list_level = 1;)
5799 /* Awful hack for `trap` or $(trap).
5800 *
5801 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5802 * contains an example where "trap" is executed in a subshell:
5803 *
5804 * save_traps=$(trap)
5805 * ...
5806 * eval "$save_traps"
5807 *
5808 * Standard does not say that "trap" in subshell shall print
5809 * parent shell's traps. It only says that its output
5810 * must have suitable form, but then, in the above example
5811 * (which is not supposed to be normative), it implies that.
5812 *
5813 * bash (and probably other shell) does implement it
5814 * (traps are reset to defaults, but "trap" still shows them),
5815 * but as a result, "trap" logic is hopelessly messed up:
5816 *
5817 * # trap
5818 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5819 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5820 * # true | trap <--- trap is in subshell - no output (ditto)
5821 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5822 * trap -- 'echo Ho' SIGWINCH
5823 * # echo `(trap)` <--- in subshell in subshell - output
5824 * trap -- 'echo Ho' SIGWINCH
5825 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5826 * trap -- 'echo Ho' SIGWINCH
5827 *
5828 * The rules when to forget and when to not forget traps
5829 * get really complex and nonsensical.
5830 *
5831 * Our solution: ONLY bare $(trap) or `trap` is special.
5832 */
5833 s = skip_whitespace(s);
5834 if (strncmp(s, "trap", 4) == 0
5835 && skip_whitespace(s + 4)[0] == '\0'
5836 ) {
5837 static const char *const argv[] = { NULL, NULL };
5838 builtin_trap((char**)argv);
5839 exit(0); /* not _exit() - we need to fflush */
5840 }
5841# if BB_MMU
5842 reset_traps_to_defaults();
5843 parse_and_run_string(s);
5844 _exit(G.last_exitcode);
5845# else
5846 /* We re-execute after vfork on NOMMU. This makes this script safe:
5847 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5848 * huge=`cat BIG` # was blocking here forever
5849 * echo OK
5850 */
5851 re_execute_shell(&to_free,
5852 s,
5853 G.global_argv[0],
5854 G.global_argv + 1,
5855 NULL);
5856# endif
5857 }
5858
5859 /* parent */
5860 *pid_p = pid;
5861# if ENABLE_HUSH_FAST
5862 G.count_SIGCHLD++;
5863//bb_error_msg("[%d] fork in generate_stream_from_string:"
5864// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5865// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5866# endif
5867 enable_restore_tty_pgrp_on_exit();
5868# if !BB_MMU
5869 free(to_free);
5870# endif
5871 close(channel[1]);
5872 close_on_exec_on(channel[0]);
5873 return xfdopen_for_read(channel[0]);
5874}
5875
5876/* Return code is exit status of the process that is run. */
5877static int process_command_subs(o_string *dest, const char *s)
5878{
5879 FILE *fp;
5880 struct in_str pipe_str;
5881 pid_t pid;
5882 int status, ch, eol_cnt;
5883
5884 fp = generate_stream_from_string(s, &pid);
5885
5886 /* Now send results of command back into original context */
5887 setup_file_in_str(&pipe_str, fp);
5888 eol_cnt = 0;
5889 while ((ch = i_getch(&pipe_str)) != EOF) {
5890 if (ch == '\n') {
5891 eol_cnt++;
5892 continue;
5893 }
5894 while (eol_cnt) {
5895 o_addchr(dest, '\n');
5896 eol_cnt--;
5897 }
5898 o_addQchr(dest, ch);
5899 }
5900
5901 debug_printf("done reading from `cmd` pipe, closing it\n");
5902 fclose(fp);
5903 /* We need to extract exitcode. Test case
5904 * "true; echo `sleep 1; false` $?"
5905 * should print 1 */
5906 safe_waitpid(pid, &status, 0);
5907 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5908 return WEXITSTATUS(status);
5909}
5910#endif /* ENABLE_HUSH_TICK */
5911
5912
5913static void setup_heredoc(struct redir_struct *redir)
5914{
5915 struct fd_pair pair;
5916 pid_t pid;
5917 int len, written;
5918 /* the _body_ of heredoc (misleading field name) */
5919 const char *heredoc = redir->rd_filename;
5920 char *expanded;
5921#if !BB_MMU
5922 char **to_free;
5923#endif
5924
5925 expanded = NULL;
5926 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005927 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005928 if (expanded)
5929 heredoc = expanded;
5930 }
5931 len = strlen(heredoc);
5932
5933 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5934 xpiped_pair(pair);
5935 xmove_fd(pair.rd, redir->rd_fd);
5936
5937 /* Try writing without forking. Newer kernels have
5938 * dynamically growing pipes. Must use non-blocking write! */
5939 ndelay_on(pair.wr);
5940 while (1) {
5941 written = write(pair.wr, heredoc, len);
5942 if (written <= 0)
5943 break;
5944 len -= written;
5945 if (len == 0) {
5946 close(pair.wr);
5947 free(expanded);
5948 return;
5949 }
5950 heredoc += written;
5951 }
5952 ndelay_off(pair.wr);
5953
5954 /* Okay, pipe buffer was not big enough */
5955 /* Note: we must not create a stray child (bastard? :)
5956 * for the unsuspecting parent process. Child creates a grandchild
5957 * and exits before parent execs the process which consumes heredoc
5958 * (that exec happens after we return from this function) */
5959#if !BB_MMU
5960 to_free = NULL;
5961#endif
5962 pid = xvfork();
5963 if (pid == 0) {
5964 /* child */
5965 disable_restore_tty_pgrp_on_exit();
5966 pid = BB_MMU ? xfork() : xvfork();
5967 if (pid != 0)
5968 _exit(0);
5969 /* grandchild */
5970 close(redir->rd_fd); /* read side of the pipe */
5971#if BB_MMU
5972 full_write(pair.wr, heredoc, len); /* may loop or block */
5973 _exit(0);
5974#else
5975 /* Delegate blocking writes to another process */
5976 xmove_fd(pair.wr, STDOUT_FILENO);
5977 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5978#endif
5979 }
5980 /* parent */
5981#if ENABLE_HUSH_FAST
5982 G.count_SIGCHLD++;
5983//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5984#endif
5985 enable_restore_tty_pgrp_on_exit();
5986#if !BB_MMU
5987 free(to_free);
5988#endif
5989 close(pair.wr);
5990 free(expanded);
5991 wait(NULL); /* wait till child has died */
5992}
5993
5994/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5995 * and stderr if they are redirected. */
5996static int setup_redirects(struct command *prog, int squirrel[])
5997{
5998 int openfd, mode;
5999 struct redir_struct *redir;
6000
6001 for (redir = prog->redirects; redir; redir = redir->next) {
6002 if (redir->rd_type == REDIRECT_HEREDOC2) {
6003 /* rd_fd<<HERE case */
6004 if (squirrel && redir->rd_fd < 3
6005 && squirrel[redir->rd_fd] < 0
6006 ) {
6007 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6008 }
6009 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6010 * of the heredoc */
6011 debug_printf_parse("set heredoc '%s'\n",
6012 redir->rd_filename);
6013 setup_heredoc(redir);
6014 continue;
6015 }
6016
6017 if (redir->rd_dup == REDIRFD_TO_FILE) {
6018 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6019 char *p;
6020 if (redir->rd_filename == NULL) {
6021 /* Something went wrong in the parse.
6022 * Pretend it didn't happen */
6023 bb_error_msg("bug in redirect parse");
6024 continue;
6025 }
6026 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006027 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006028 openfd = open_or_warn(p, mode);
6029 free(p);
6030 if (openfd < 0) {
6031 /* this could get lost if stderr has been redirected, but
6032 * bash and ash both lose it as well (though zsh doesn't!) */
6033//what the above comment tries to say?
6034 return 1;
6035 }
6036 } else {
6037 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6038 openfd = redir->rd_dup;
6039 }
6040
6041 if (openfd != redir->rd_fd) {
6042 if (squirrel && redir->rd_fd < 3
6043 && squirrel[redir->rd_fd] < 0
6044 ) {
6045 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6046 }
6047 if (openfd == REDIRFD_CLOSE) {
6048 /* "n>-" means "close me" */
6049 close(redir->rd_fd);
6050 } else {
6051 xdup2(openfd, redir->rd_fd);
6052 if (redir->rd_dup == REDIRFD_TO_FILE)
6053 close(openfd);
6054 }
6055 }
6056 }
6057 return 0;
6058}
6059
6060static void restore_redirects(int squirrel[])
6061{
6062 int i, fd;
6063 for (i = 0; i < 3; i++) {
6064 fd = squirrel[i];
6065 if (fd != -1) {
6066 /* We simply die on error */
6067 xmove_fd(fd, i);
6068 }
6069 }
6070}
6071
6072static char *find_in_path(const char *arg)
6073{
6074 char *ret = NULL;
6075 const char *PATH = get_local_var_value("PATH");
6076
6077 if (!PATH)
6078 return NULL;
6079
6080 while (1) {
6081 const char *end = strchrnul(PATH, ':');
6082 int sz = end - PATH; /* must be int! */
6083
6084 free(ret);
6085 if (sz != 0) {
6086 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6087 } else {
6088 /* We have xxx::yyyy in $PATH,
6089 * it means "use current dir" */
6090 ret = xstrdup(arg);
6091 }
6092 if (access(ret, F_OK) == 0)
6093 break;
6094
6095 if (*end == '\0') {
6096 free(ret);
6097 return NULL;
6098 }
6099 PATH = end + 1;
6100 }
6101
6102 return ret;
6103}
6104
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006105static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006106 const struct built_in_command *x,
6107 const struct built_in_command *end)
6108{
6109 while (x != end) {
6110 if (strcmp(name, x->b_cmd) != 0) {
6111 x++;
6112 continue;
6113 }
6114 debug_printf_exec("found builtin '%s'\n", name);
6115 return x;
6116 }
6117 return NULL;
6118}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006119static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006120{
6121 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6122}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006123static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006124{
6125 const struct built_in_command *x = find_builtin1(name);
6126 if (x)
6127 return x;
6128 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6129}
6130
6131#if ENABLE_HUSH_FUNCTIONS
6132static struct function **find_function_slot(const char *name)
6133{
6134 struct function **funcpp = &G.top_func;
6135 while (*funcpp) {
6136 if (strcmp(name, (*funcpp)->name) == 0) {
6137 break;
6138 }
6139 funcpp = &(*funcpp)->next;
6140 }
6141 return funcpp;
6142}
6143
6144static const struct function *find_function(const char *name)
6145{
6146 const struct function *funcp = *find_function_slot(name);
6147 if (funcp)
6148 debug_printf_exec("found function '%s'\n", name);
6149 return funcp;
6150}
6151
6152/* Note: takes ownership on name ptr */
6153static struct function *new_function(char *name)
6154{
6155 struct function **funcpp = find_function_slot(name);
6156 struct function *funcp = *funcpp;
6157
6158 if (funcp != NULL) {
6159 struct command *cmd = funcp->parent_cmd;
6160 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6161 if (!cmd) {
6162 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6163 free(funcp->name);
6164 /* Note: if !funcp->body, do not free body_as_string!
6165 * This is a special case of "-F name body" function:
6166 * body_as_string was not malloced! */
6167 if (funcp->body) {
6168 free_pipe_list(funcp->body);
6169# if !BB_MMU
6170 free(funcp->body_as_string);
6171# endif
6172 }
6173 } else {
6174 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6175 cmd->argv[0] = funcp->name;
6176 cmd->group = funcp->body;
6177# if !BB_MMU
6178 cmd->group_as_string = funcp->body_as_string;
6179# endif
6180 }
6181 } else {
6182 debug_printf_exec("remembering new function '%s'\n", name);
6183 funcp = *funcpp = xzalloc(sizeof(*funcp));
6184 /*funcp->next = NULL;*/
6185 }
6186
6187 funcp->name = name;
6188 return funcp;
6189}
6190
6191static void unset_func(const char *name)
6192{
6193 struct function **funcpp = find_function_slot(name);
6194 struct function *funcp = *funcpp;
6195
6196 if (funcp != NULL) {
6197 debug_printf_exec("freeing function '%s'\n", funcp->name);
6198 *funcpp = funcp->next;
6199 /* funcp is unlinked now, deleting it.
6200 * Note: if !funcp->body, the function was created by
6201 * "-F name body", do not free ->body_as_string
6202 * and ->name as they were not malloced. */
6203 if (funcp->body) {
6204 free_pipe_list(funcp->body);
6205 free(funcp->name);
6206# if !BB_MMU
6207 free(funcp->body_as_string);
6208# endif
6209 }
6210 free(funcp);
6211 }
6212}
6213
6214# if BB_MMU
6215#define exec_function(to_free, funcp, argv) \
6216 exec_function(funcp, argv)
6217# endif
6218static void exec_function(char ***to_free,
6219 const struct function *funcp,
6220 char **argv) NORETURN;
6221static void exec_function(char ***to_free,
6222 const struct function *funcp,
6223 char **argv)
6224{
6225# if BB_MMU
6226 int n = 1;
6227
6228 argv[0] = G.global_argv[0];
6229 G.global_argv = argv;
6230 while (*++argv)
6231 n++;
6232 G.global_argc = n;
6233 /* On MMU, funcp->body is always non-NULL */
6234 n = run_list(funcp->body);
6235 fflush_all();
6236 _exit(n);
6237# else
6238 re_execute_shell(to_free,
6239 funcp->body_as_string,
6240 G.global_argv[0],
6241 argv + 1,
6242 NULL);
6243# endif
6244}
6245
6246static int run_function(const struct function *funcp, char **argv)
6247{
6248 int rc;
6249 save_arg_t sv;
6250 smallint sv_flg;
6251
6252 save_and_replace_G_args(&sv, argv);
6253
6254 /* "we are in function, ok to use return" */
6255 sv_flg = G.flag_return_in_progress;
6256 G.flag_return_in_progress = -1;
6257# if ENABLE_HUSH_LOCAL
6258 G.func_nest_level++;
6259# endif
6260
6261 /* On MMU, funcp->body is always non-NULL */
6262# if !BB_MMU
6263 if (!funcp->body) {
6264 /* Function defined by -F */
6265 parse_and_run_string(funcp->body_as_string);
6266 rc = G.last_exitcode;
6267 } else
6268# endif
6269 {
6270 rc = run_list(funcp->body);
6271 }
6272
6273# if ENABLE_HUSH_LOCAL
6274 {
6275 struct variable *var;
6276 struct variable **var_pp;
6277
6278 var_pp = &G.top_var;
6279 while ((var = *var_pp) != NULL) {
6280 if (var->func_nest_level < G.func_nest_level) {
6281 var_pp = &var->next;
6282 continue;
6283 }
6284 /* Unexport */
6285 if (var->flg_export)
6286 bb_unsetenv(var->varstr);
6287 /* Remove from global list */
6288 *var_pp = var->next;
6289 /* Free */
6290 if (!var->max_len)
6291 free(var->varstr);
6292 free(var);
6293 }
6294 G.func_nest_level--;
6295 }
6296# endif
6297 G.flag_return_in_progress = sv_flg;
6298
6299 restore_G_args(&sv, argv);
6300
6301 return rc;
6302}
6303#endif /* ENABLE_HUSH_FUNCTIONS */
6304
6305
6306#if BB_MMU
6307#define exec_builtin(to_free, x, argv) \
6308 exec_builtin(x, argv)
6309#else
6310#define exec_builtin(to_free, x, argv) \
6311 exec_builtin(to_free, argv)
6312#endif
6313static void exec_builtin(char ***to_free,
6314 const struct built_in_command *x,
6315 char **argv) NORETURN;
6316static void exec_builtin(char ***to_free,
6317 const struct built_in_command *x,
6318 char **argv)
6319{
6320#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006321 int rcode;
6322 fflush_all();
6323 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006324 fflush_all();
6325 _exit(rcode);
6326#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006327 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006328 /* On NOMMU, we must never block!
6329 * Example: { sleep 99 | read line; } & echo Ok
6330 */
6331 re_execute_shell(to_free,
6332 argv[0],
6333 G.global_argv[0],
6334 G.global_argv + 1,
6335 argv);
6336#endif
6337}
6338
6339
6340static void execvp_or_die(char **argv) NORETURN;
6341static void execvp_or_die(char **argv)
6342{
6343 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006344 /* Don't propagate SIG_IGN to the child */
6345 if (SPECIAL_JOBSTOP_SIGS != 0)
6346 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006347 execvp(argv[0], argv);
6348 bb_perror_msg("can't execute '%s'", argv[0]);
6349 _exit(127); /* bash compat */
6350}
6351
6352#if ENABLE_HUSH_MODE_X
6353static void dump_cmd_in_x_mode(char **argv)
6354{
6355 if (G_x_mode && argv) {
6356 /* We want to output the line in one write op */
6357 char *buf, *p;
6358 int len;
6359 int n;
6360
6361 len = 3;
6362 n = 0;
6363 while (argv[n])
6364 len += strlen(argv[n++]) + 1;
6365 buf = xmalloc(len);
6366 buf[0] = '+';
6367 p = buf + 1;
6368 n = 0;
6369 while (argv[n])
6370 p += sprintf(p, " %s", argv[n++]);
6371 *p++ = '\n';
6372 *p = '\0';
6373 fputs(buf, stderr);
6374 free(buf);
6375 }
6376}
6377#else
6378# define dump_cmd_in_x_mode(argv) ((void)0)
6379#endif
6380
6381#if BB_MMU
6382#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6383 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6384#define pseudo_exec(nommu_save, command, argv_expanded) \
6385 pseudo_exec(command, argv_expanded)
6386#endif
6387
6388/* Called after [v]fork() in run_pipe, or from builtin_exec.
6389 * Never returns.
6390 * Don't exit() here. If you don't exec, use _exit instead.
6391 * The at_exit handlers apparently confuse the calling process,
6392 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6393static void pseudo_exec_argv(nommu_save_t *nommu_save,
6394 char **argv, int assignment_cnt,
6395 char **argv_expanded) NORETURN;
6396static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6397 char **argv, int assignment_cnt,
6398 char **argv_expanded)
6399{
6400 char **new_env;
6401
6402 new_env = expand_assignments(argv, assignment_cnt);
6403 dump_cmd_in_x_mode(new_env);
6404
6405 if (!argv[assignment_cnt]) {
6406 /* Case when we are here: ... | var=val | ...
6407 * (note that we do not exit early, i.e., do not optimize out
6408 * expand_assignments(): think about ... | var=`sleep 1` | ...
6409 */
6410 free_strings(new_env);
6411 _exit(EXIT_SUCCESS);
6412 }
6413
6414#if BB_MMU
6415 set_vars_and_save_old(new_env);
6416 free(new_env); /* optional */
6417 /* we can also destroy set_vars_and_save_old's return value,
6418 * to save memory */
6419#else
6420 nommu_save->new_env = new_env;
6421 nommu_save->old_vars = set_vars_and_save_old(new_env);
6422#endif
6423
6424 if (argv_expanded) {
6425 argv = argv_expanded;
6426 } else {
6427 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6428#if !BB_MMU
6429 nommu_save->argv = argv;
6430#endif
6431 }
6432 dump_cmd_in_x_mode(argv);
6433
6434#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6435 if (strchr(argv[0], '/') != NULL)
6436 goto skip;
6437#endif
6438
6439 /* Check if the command matches any of the builtins.
6440 * Depending on context, this might be redundant. But it's
6441 * easier to waste a few CPU cycles than it is to figure out
6442 * if this is one of those cases.
6443 */
6444 {
6445 /* On NOMMU, it is more expensive to re-execute shell
6446 * just in order to run echo or test builtin.
6447 * It's better to skip it here and run corresponding
6448 * non-builtin later. */
6449 const struct built_in_command *x;
6450 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6451 if (x) {
6452 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6453 }
6454 }
6455#if ENABLE_HUSH_FUNCTIONS
6456 /* Check if the command matches any functions */
6457 {
6458 const struct function *funcp = find_function(argv[0]);
6459 if (funcp) {
6460 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6461 }
6462 }
6463#endif
6464
6465#if ENABLE_FEATURE_SH_STANDALONE
6466 /* Check if the command matches any busybox applets */
6467 {
6468 int a = find_applet_by_name(argv[0]);
6469 if (a >= 0) {
6470# if BB_MMU /* see above why on NOMMU it is not allowed */
6471 if (APPLET_IS_NOEXEC(a)) {
6472 debug_printf_exec("running applet '%s'\n", argv[0]);
6473 run_applet_no_and_exit(a, argv);
6474 }
6475# endif
6476 /* Re-exec ourselves */
6477 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006478 /* Don't propagate SIG_IGN to the child */
6479 if (SPECIAL_JOBSTOP_SIGS != 0)
6480 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006481 execv(bb_busybox_exec_path, argv);
6482 /* If they called chroot or otherwise made the binary no longer
6483 * executable, fall through */
6484 }
6485 }
6486#endif
6487
6488#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6489 skip:
6490#endif
6491 execvp_or_die(argv);
6492}
6493
6494/* Called after [v]fork() in run_pipe
6495 */
6496static void pseudo_exec(nommu_save_t *nommu_save,
6497 struct command *command,
6498 char **argv_expanded) NORETURN;
6499static void pseudo_exec(nommu_save_t *nommu_save,
6500 struct command *command,
6501 char **argv_expanded)
6502{
6503 if (command->argv) {
6504 pseudo_exec_argv(nommu_save, command->argv,
6505 command->assignment_cnt, argv_expanded);
6506 }
6507
6508 if (command->group) {
6509 /* Cases when we are here:
6510 * ( list )
6511 * { list } &
6512 * ... | ( list ) | ...
6513 * ... | { list } | ...
6514 */
6515#if BB_MMU
6516 int rcode;
6517 debug_printf_exec("pseudo_exec: run_list\n");
6518 reset_traps_to_defaults();
6519 rcode = run_list(command->group);
6520 /* OK to leak memory by not calling free_pipe_list,
6521 * since this process is about to exit */
6522 _exit(rcode);
6523#else
6524 re_execute_shell(&nommu_save->argv_from_re_execing,
6525 command->group_as_string,
6526 G.global_argv[0],
6527 G.global_argv + 1,
6528 NULL);
6529#endif
6530 }
6531
6532 /* Case when we are here: ... | >file */
6533 debug_printf_exec("pseudo_exec'ed null command\n");
6534 _exit(EXIT_SUCCESS);
6535}
6536
6537#if ENABLE_HUSH_JOB
6538static const char *get_cmdtext(struct pipe *pi)
6539{
6540 char **argv;
6541 char *p;
6542 int len;
6543
6544 /* This is subtle. ->cmdtext is created only on first backgrounding.
6545 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6546 * On subsequent bg argv is trashed, but we won't use it */
6547 if (pi->cmdtext)
6548 return pi->cmdtext;
6549 argv = pi->cmds[0].argv;
6550 if (!argv || !argv[0]) {
6551 pi->cmdtext = xzalloc(1);
6552 return pi->cmdtext;
6553 }
6554
6555 len = 0;
6556 do {
6557 len += strlen(*argv) + 1;
6558 } while (*++argv);
6559 p = xmalloc(len);
6560 pi->cmdtext = p;
6561 argv = pi->cmds[0].argv;
6562 do {
6563 len = strlen(*argv);
6564 memcpy(p, *argv, len);
6565 p += len;
6566 *p++ = ' ';
6567 } while (*++argv);
6568 p[-1] = '\0';
6569 return pi->cmdtext;
6570}
6571
6572static void insert_bg_job(struct pipe *pi)
6573{
6574 struct pipe *job, **jobp;
6575 int i;
6576
6577 /* Linear search for the ID of the job to use */
6578 pi->jobid = 1;
6579 for (job = G.job_list; job; job = job->next)
6580 if (job->jobid >= pi->jobid)
6581 pi->jobid = job->jobid + 1;
6582
6583 /* Add job to the list of running jobs */
6584 jobp = &G.job_list;
6585 while ((job = *jobp) != NULL)
6586 jobp = &job->next;
6587 job = *jobp = xmalloc(sizeof(*job));
6588
6589 *job = *pi; /* physical copy */
6590 job->next = NULL;
6591 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6592 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6593 for (i = 0; i < pi->num_cmds; i++) {
6594 job->cmds[i].pid = pi->cmds[i].pid;
6595 /* all other fields are not used and stay zero */
6596 }
6597 job->cmdtext = xstrdup(get_cmdtext(pi));
6598
6599 if (G_interactive_fd)
6600 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6601 G.last_jobid = job->jobid;
6602}
6603
6604static void remove_bg_job(struct pipe *pi)
6605{
6606 struct pipe *prev_pipe;
6607
6608 if (pi == G.job_list) {
6609 G.job_list = pi->next;
6610 } else {
6611 prev_pipe = G.job_list;
6612 while (prev_pipe->next != pi)
6613 prev_pipe = prev_pipe->next;
6614 prev_pipe->next = pi->next;
6615 }
6616 if (G.job_list)
6617 G.last_jobid = G.job_list->jobid;
6618 else
6619 G.last_jobid = 0;
6620}
6621
6622/* Remove a backgrounded job */
6623static void delete_finished_bg_job(struct pipe *pi)
6624{
6625 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006626 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006627}
6628#endif /* JOB */
6629
6630/* Check to see if any processes have exited -- if they
6631 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006632static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006633{
6634 int attributes;
6635 int status;
6636#if ENABLE_HUSH_JOB
6637 struct pipe *pi;
6638#endif
6639 pid_t childpid;
6640 int rcode = 0;
6641
6642 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6643
6644 attributes = WUNTRACED;
6645 if (fg_pipe == NULL)
6646 attributes |= WNOHANG;
6647
6648 errno = 0;
6649#if ENABLE_HUSH_FAST
6650 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6651//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6652//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6653 /* There was neither fork nor SIGCHLD since last waitpid */
6654 /* Avoid doing waitpid syscall if possible */
6655 if (!G.we_have_children) {
6656 errno = ECHILD;
6657 return -1;
6658 }
6659 if (fg_pipe == NULL) { /* is WNOHANG set? */
6660 /* We have children, but they did not exit
6661 * or stop yet (we saw no SIGCHLD) */
6662 return 0;
6663 }
6664 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6665 }
6666#endif
6667
6668/* Do we do this right?
6669 * bash-3.00# sleep 20 | false
6670 * <ctrl-Z pressed>
6671 * [3]+ Stopped sleep 20 | false
6672 * bash-3.00# echo $?
6673 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6674 * [hush 1.14.0: yes we do it right]
6675 */
6676 wait_more:
6677 while (1) {
6678 int i;
6679 int dead;
6680
6681#if ENABLE_HUSH_FAST
6682 i = G.count_SIGCHLD;
6683#endif
6684 childpid = waitpid(-1, &status, attributes);
6685 if (childpid <= 0) {
6686 if (childpid && errno != ECHILD)
6687 bb_perror_msg("waitpid");
6688#if ENABLE_HUSH_FAST
6689 else { /* Until next SIGCHLD, waitpid's are useless */
6690 G.we_have_children = (childpid == 0);
6691 G.handled_SIGCHLD = i;
6692//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6693 }
6694#endif
6695 break;
6696 }
6697 dead = WIFEXITED(status) || WIFSIGNALED(status);
6698
6699#if DEBUG_JOBS
6700 if (WIFSTOPPED(status))
6701 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6702 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6703 if (WIFSIGNALED(status))
6704 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6705 childpid, WTERMSIG(status), WEXITSTATUS(status));
6706 if (WIFEXITED(status))
6707 debug_printf_jobs("pid %d exited, exitcode %d\n",
6708 childpid, WEXITSTATUS(status));
6709#endif
6710 /* Were we asked to wait for fg pipe? */
6711 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006712 i = fg_pipe->num_cmds;
6713 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006714 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6715 if (fg_pipe->cmds[i].pid != childpid)
6716 continue;
6717 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006718 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006719 fg_pipe->cmds[i].pid = 0;
6720 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006721 ex = WEXITSTATUS(status);
6722 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006723 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006724 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6725 */
6726 if (WIFSIGNALED(status)) {
6727 int sig = WTERMSIG(status);
6728 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006729 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6730 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6731 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006732 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6733 * Maybe we need to use sig | 128? */
6734 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006735 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006736 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006737 } else {
6738 fg_pipe->cmds[i].is_stopped = 1;
6739 fg_pipe->stopped_cmds++;
6740 }
6741 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6742 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006743 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006744 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006745 i = fg_pipe->num_cmds;
6746 while (--i >= 0) {
6747 rcode = fg_pipe->cmds[i].cmd_exitcode;
6748 /* usually last process gives overall exitstatus,
6749 * but with "set -o pipefail", last *failed* process does */
6750 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6751 break;
6752 }
6753 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006754/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6755 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6756 * and "killall -STOP cat" */
6757 if (G_interactive_fd) {
6758#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006759 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006760 insert_bg_job(fg_pipe);
6761#endif
6762 return rcode;
6763 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006764 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006765 return rcode;
6766 }
6767 /* There are still running processes in the fg pipe */
6768 goto wait_more; /* do waitpid again */
6769 }
6770 /* it wasnt fg_pipe, look for process in bg pipes */
6771 }
6772
6773#if ENABLE_HUSH_JOB
6774 /* We asked to wait for bg or orphaned children */
6775 /* No need to remember exitcode in this case */
6776 for (pi = G.job_list; pi; pi = pi->next) {
6777 for (i = 0; i < pi->num_cmds; i++) {
6778 if (pi->cmds[i].pid == childpid)
6779 goto found_pi_and_prognum;
6780 }
6781 }
6782 /* Happens when shell is used as init process (init=/bin/sh) */
6783 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6784 continue; /* do waitpid again */
6785
6786 found_pi_and_prognum:
6787 if (dead) {
6788 /* child exited */
6789 pi->cmds[i].pid = 0;
6790 pi->alive_cmds--;
6791 if (!pi->alive_cmds) {
6792 if (G_interactive_fd)
6793 printf(JOB_STATUS_FORMAT, pi->jobid,
6794 "Done", pi->cmdtext);
6795 delete_finished_bg_job(pi);
6796 }
6797 } else {
6798 /* child stopped */
6799 pi->cmds[i].is_stopped = 1;
6800 pi->stopped_cmds++;
6801 }
6802#endif
6803 } /* while (waitpid succeeds)... */
6804
6805 return rcode;
6806}
6807
6808#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006809static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006810{
6811 pid_t p;
6812 int rcode = checkjobs(fg_pipe);
6813 if (G_saved_tty_pgrp) {
6814 /* Job finished, move the shell to the foreground */
6815 p = getpgrp(); /* our process group id */
6816 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6817 tcsetpgrp(G_interactive_fd, p);
6818 }
6819 return rcode;
6820}
6821#endif
6822
6823/* Start all the jobs, but don't wait for anything to finish.
6824 * See checkjobs().
6825 *
6826 * Return code is normally -1, when the caller has to wait for children
6827 * to finish to determine the exit status of the pipe. If the pipe
6828 * is a simple builtin command, however, the action is done by the
6829 * time run_pipe returns, and the exit code is provided as the
6830 * return value.
6831 *
6832 * Returns -1 only if started some children. IOW: we have to
6833 * mask out retvals of builtins etc with 0xff!
6834 *
6835 * The only case when we do not need to [v]fork is when the pipe
6836 * is single, non-backgrounded, non-subshell command. Examples:
6837 * cmd ; ... { list } ; ...
6838 * cmd && ... { list } && ...
6839 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006840 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006841 * or (if SH_STANDALONE) an applet, and we can run the { list }
6842 * with run_list. If it isn't one of these, we fork and exec cmd.
6843 *
6844 * Cases when we must fork:
6845 * non-single: cmd | cmd
6846 * backgrounded: cmd & { list } &
6847 * subshell: ( list ) [&]
6848 */
6849#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006850#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006851 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6852#endif
6853static int redirect_and_varexp_helper(char ***new_env_p,
6854 struct variable **old_vars_p,
6855 struct command *command,
6856 int squirrel[3],
6857 char **argv_expanded)
6858{
6859 /* setup_redirects acts on file descriptors, not FILEs.
6860 * This is perfect for work that comes after exec().
6861 * Is it really safe for inline use? Experimentally,
6862 * things seem to work. */
6863 int rcode = setup_redirects(command, squirrel);
6864 if (rcode == 0) {
6865 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6866 *new_env_p = new_env;
6867 dump_cmd_in_x_mode(new_env);
6868 dump_cmd_in_x_mode(argv_expanded);
6869 if (old_vars_p)
6870 *old_vars_p = set_vars_and_save_old(new_env);
6871 }
6872 return rcode;
6873}
6874static NOINLINE int run_pipe(struct pipe *pi)
6875{
6876 static const char *const null_ptr = NULL;
6877
6878 int cmd_no;
6879 int next_infd;
6880 struct command *command;
6881 char **argv_expanded;
6882 char **argv;
6883 /* it is not always needed, but we aim to smaller code */
6884 int squirrel[] = { -1, -1, -1 };
6885 int rcode;
6886
6887 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6888 debug_enter();
6889
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006890 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6891 * Result should be 3 lines: q w e, qwe, q w e
6892 */
6893 G.ifs = get_local_var_value("IFS");
6894 if (!G.ifs)
6895 G.ifs = defifs;
6896
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006897 IF_HUSH_JOB(pi->pgrp = -1;)
6898 pi->stopped_cmds = 0;
6899 command = &pi->cmds[0];
6900 argv_expanded = NULL;
6901
6902 if (pi->num_cmds != 1
6903 || pi->followup == PIPE_BG
6904 || command->cmd_type == CMD_SUBSHELL
6905 ) {
6906 goto must_fork;
6907 }
6908
6909 pi->alive_cmds = 1;
6910
6911 debug_printf_exec(": group:%p argv:'%s'\n",
6912 command->group, command->argv ? command->argv[0] : "NONE");
6913
6914 if (command->group) {
6915#if ENABLE_HUSH_FUNCTIONS
6916 if (command->cmd_type == CMD_FUNCDEF) {
6917 /* "executing" func () { list } */
6918 struct function *funcp;
6919
6920 funcp = new_function(command->argv[0]);
6921 /* funcp->name is already set to argv[0] */
6922 funcp->body = command->group;
6923# if !BB_MMU
6924 funcp->body_as_string = command->group_as_string;
6925 command->group_as_string = NULL;
6926# endif
6927 command->group = NULL;
6928 command->argv[0] = NULL;
6929 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6930 funcp->parent_cmd = command;
6931 command->child_func = funcp;
6932
6933 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6934 debug_leave();
6935 return EXIT_SUCCESS;
6936 }
6937#endif
6938 /* { list } */
6939 debug_printf("non-subshell group\n");
6940 rcode = 1; /* exitcode if redir failed */
6941 if (setup_redirects(command, squirrel) == 0) {
6942 debug_printf_exec(": run_list\n");
6943 rcode = run_list(command->group) & 0xff;
6944 }
6945 restore_redirects(squirrel);
6946 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6947 debug_leave();
6948 debug_printf_exec("run_pipe: return %d\n", rcode);
6949 return rcode;
6950 }
6951
6952 argv = command->argv ? command->argv : (char **) &null_ptr;
6953 {
6954 const struct built_in_command *x;
6955#if ENABLE_HUSH_FUNCTIONS
6956 const struct function *funcp;
6957#else
6958 enum { funcp = 0 };
6959#endif
6960 char **new_env = NULL;
6961 struct variable *old_vars = NULL;
6962
6963 if (argv[command->assignment_cnt] == NULL) {
6964 /* Assignments, but no command */
6965 /* Ensure redirects take effect (that is, create files).
6966 * Try "a=t >file" */
6967#if 0 /* A few cases in testsuite fail with this code. FIXME */
6968 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6969 /* Set shell variables */
6970 if (new_env) {
6971 argv = new_env;
6972 while (*argv) {
6973 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6974 /* Do we need to flag set_local_var() errors?
6975 * "assignment to readonly var" and "putenv error"
6976 */
6977 argv++;
6978 }
6979 }
6980 /* Redirect error sets $? to 1. Otherwise,
6981 * if evaluating assignment value set $?, retain it.
6982 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6983 if (rcode == 0)
6984 rcode = G.last_exitcode;
6985 /* Exit, _skipping_ variable restoring code: */
6986 goto clean_up_and_ret0;
6987
6988#else /* Older, bigger, but more correct code */
6989
6990 rcode = setup_redirects(command, squirrel);
6991 restore_redirects(squirrel);
6992 /* Set shell variables */
6993 if (G_x_mode)
6994 bb_putchar_stderr('+');
6995 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006996 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006997 if (G_x_mode)
6998 fprintf(stderr, " %s", p);
6999 debug_printf_exec("set shell var:'%s'->'%s'\n",
7000 *argv, p);
7001 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7002 /* Do we need to flag set_local_var() errors?
7003 * "assignment to readonly var" and "putenv error"
7004 */
7005 argv++;
7006 }
7007 if (G_x_mode)
7008 bb_putchar_stderr('\n');
7009 /* Redirect error sets $? to 1. Otherwise,
7010 * if evaluating assignment value set $?, retain it.
7011 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7012 if (rcode == 0)
7013 rcode = G.last_exitcode;
7014 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7015 debug_leave();
7016 debug_printf_exec("run_pipe: return %d\n", rcode);
7017 return rcode;
7018#endif
7019 }
7020
7021 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007022#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007023 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007024 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007025 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007026#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007027 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007028 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7029 }
7030
7031 /* if someone gives us an empty string: `cmd with empty output` */
7032 if (!argv_expanded[0]) {
7033 free(argv_expanded);
7034 debug_leave();
7035 return G.last_exitcode;
7036 }
7037
7038 x = find_builtin(argv_expanded[0]);
7039#if ENABLE_HUSH_FUNCTIONS
7040 funcp = NULL;
7041 if (!x)
7042 funcp = find_function(argv_expanded[0]);
7043#endif
7044 if (x || funcp) {
7045 if (!funcp) {
7046 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7047 debug_printf("exec with redirects only\n");
7048 rcode = setup_redirects(command, NULL);
7049 goto clean_up_and_ret1;
7050 }
7051 }
7052 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7053 if (rcode == 0) {
7054 if (!funcp) {
7055 debug_printf_exec(": builtin '%s' '%s'...\n",
7056 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007057 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007058 rcode = x->b_function(argv_expanded) & 0xff;
7059 fflush_all();
7060 }
7061#if ENABLE_HUSH_FUNCTIONS
7062 else {
7063# if ENABLE_HUSH_LOCAL
7064 struct variable **sv;
7065 sv = G.shadowed_vars_pp;
7066 G.shadowed_vars_pp = &old_vars;
7067# endif
7068 debug_printf_exec(": function '%s' '%s'...\n",
7069 funcp->name, argv_expanded[1]);
7070 rcode = run_function(funcp, argv_expanded) & 0xff;
7071# if ENABLE_HUSH_LOCAL
7072 G.shadowed_vars_pp = sv;
7073# endif
7074 }
7075#endif
7076 }
7077 clean_up_and_ret:
7078 unset_vars(new_env);
7079 add_vars(old_vars);
7080/* clean_up_and_ret0: */
7081 restore_redirects(squirrel);
7082 clean_up_and_ret1:
7083 free(argv_expanded);
7084 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7085 debug_leave();
7086 debug_printf_exec("run_pipe return %d\n", rcode);
7087 return rcode;
7088 }
7089
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007090 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007091 int n = find_applet_by_name(argv_expanded[0]);
7092 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7093 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7094 if (rcode == 0) {
7095 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7096 argv_expanded[0], argv_expanded[1]);
7097 rcode = run_nofork_applet(n, argv_expanded);
7098 }
7099 goto clean_up_and_ret;
7100 }
7101 }
7102 /* It is neither builtin nor applet. We must fork. */
7103 }
7104
7105 must_fork:
7106 /* NB: argv_expanded may already be created, and that
7107 * might include `cmd` runs! Do not rerun it! We *must*
7108 * use argv_expanded if it's non-NULL */
7109
7110 /* Going to fork a child per each pipe member */
7111 pi->alive_cmds = 0;
7112 next_infd = 0;
7113
7114 cmd_no = 0;
7115 while (cmd_no < pi->num_cmds) {
7116 struct fd_pair pipefds;
7117#if !BB_MMU
7118 volatile nommu_save_t nommu_save;
7119 nommu_save.new_env = NULL;
7120 nommu_save.old_vars = NULL;
7121 nommu_save.argv = NULL;
7122 nommu_save.argv_from_re_execing = NULL;
7123#endif
7124 command = &pi->cmds[cmd_no];
7125 cmd_no++;
7126 if (command->argv) {
7127 debug_printf_exec(": pipe member '%s' '%s'...\n",
7128 command->argv[0], command->argv[1]);
7129 } else {
7130 debug_printf_exec(": pipe member with no argv\n");
7131 }
7132
7133 /* pipes are inserted between pairs of commands */
7134 pipefds.rd = 0;
7135 pipefds.wr = 1;
7136 if (cmd_no < pi->num_cmds)
7137 xpiped_pair(pipefds);
7138
7139 command->pid = BB_MMU ? fork() : vfork();
7140 if (!command->pid) { /* child */
7141#if ENABLE_HUSH_JOB
7142 disable_restore_tty_pgrp_on_exit();
7143 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7144
7145 /* Every child adds itself to new process group
7146 * with pgid == pid_of_first_child_in_pipe */
7147 if (G.run_list_level == 1 && G_interactive_fd) {
7148 pid_t pgrp;
7149 pgrp = pi->pgrp;
7150 if (pgrp < 0) /* true for 1st process only */
7151 pgrp = getpid();
7152 if (setpgid(0, pgrp) == 0
7153 && pi->followup != PIPE_BG
7154 && G_saved_tty_pgrp /* we have ctty */
7155 ) {
7156 /* We do it in *every* child, not just first,
7157 * to avoid races */
7158 tcsetpgrp(G_interactive_fd, pgrp);
7159 }
7160 }
7161#endif
7162 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7163 /* 1st cmd in backgrounded pipe
7164 * should have its stdin /dev/null'ed */
7165 close(0);
7166 if (open(bb_dev_null, O_RDONLY))
7167 xopen("/", O_RDONLY);
7168 } else {
7169 xmove_fd(next_infd, 0);
7170 }
7171 xmove_fd(pipefds.wr, 1);
7172 if (pipefds.rd > 1)
7173 close(pipefds.rd);
7174 /* Like bash, explicit redirects override pipes,
7175 * and the pipe fd is available for dup'ing. */
7176 if (setup_redirects(command, NULL))
7177 _exit(1);
7178
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007179 /* Stores to nommu_save list of env vars putenv'ed
7180 * (NOMMU, on MMU we don't need that) */
7181 /* cast away volatility... */
7182 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7183 /* pseudo_exec() does not return */
7184 }
7185
7186 /* parent or error */
7187#if ENABLE_HUSH_FAST
7188 G.count_SIGCHLD++;
7189//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7190#endif
7191 enable_restore_tty_pgrp_on_exit();
7192#if !BB_MMU
7193 /* Clean up after vforked child */
7194 free(nommu_save.argv);
7195 free(nommu_save.argv_from_re_execing);
7196 unset_vars(nommu_save.new_env);
7197 add_vars(nommu_save.old_vars);
7198#endif
7199 free(argv_expanded);
7200 argv_expanded = NULL;
7201 if (command->pid < 0) { /* [v]fork failed */
7202 /* Clearly indicate, was it fork or vfork */
7203 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7204 } else {
7205 pi->alive_cmds++;
7206#if ENABLE_HUSH_JOB
7207 /* Second and next children need to know pid of first one */
7208 if (pi->pgrp < 0)
7209 pi->pgrp = command->pid;
7210#endif
7211 }
7212
7213 if (cmd_no > 1)
7214 close(next_infd);
7215 if (cmd_no < pi->num_cmds)
7216 close(pipefds.wr);
7217 /* Pass read (output) pipe end to next iteration */
7218 next_infd = pipefds.rd;
7219 }
7220
7221 if (!pi->alive_cmds) {
7222 debug_leave();
7223 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7224 return 1;
7225 }
7226
7227 debug_leave();
7228 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7229 return -1;
7230}
7231
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007232/* NB: called by pseudo_exec, and therefore must not modify any
7233 * global data until exec/_exit (we can be a child after vfork!) */
7234static int run_list(struct pipe *pi)
7235{
7236#if ENABLE_HUSH_CASE
7237 char *case_word = NULL;
7238#endif
7239#if ENABLE_HUSH_LOOPS
7240 struct pipe *loop_top = NULL;
7241 char **for_lcur = NULL;
7242 char **for_list = NULL;
7243#endif
7244 smallint last_followup;
7245 smalluint rcode;
7246#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7247 smalluint cond_code = 0;
7248#else
7249 enum { cond_code = 0 };
7250#endif
7251#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007252 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007253 smallint last_rword; /* ditto */
7254#endif
7255
7256 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7257 debug_enter();
7258
7259#if ENABLE_HUSH_LOOPS
7260 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007261 {
7262 struct pipe *cpipe;
7263 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7264 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7265 continue;
7266 /* current word is FOR or IN (BOLD in comments below) */
7267 if (cpipe->next == NULL) {
7268 syntax_error("malformed for");
7269 debug_leave();
7270 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7271 return 1;
7272 }
7273 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7274 if (cpipe->next->res_word == RES_DO)
7275 continue;
7276 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7277 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7278 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7279 ) {
7280 syntax_error("malformed for");
7281 debug_leave();
7282 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7283 return 1;
7284 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007285 }
7286 }
7287#endif
7288
7289 /* Past this point, all code paths should jump to ret: label
7290 * in order to return, no direct "return" statements please.
7291 * This helps to ensure that no memory is leaked. */
7292
7293#if ENABLE_HUSH_JOB
7294 G.run_list_level++;
7295#endif
7296
7297#if HAS_KEYWORDS
7298 rword = RES_NONE;
7299 last_rword = RES_XXXX;
7300#endif
7301 last_followup = PIPE_SEQ;
7302 rcode = G.last_exitcode;
7303
7304 /* Go through list of pipes, (maybe) executing them. */
7305 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7306 if (G.flag_SIGINT)
7307 break;
7308
7309 IF_HAS_KEYWORDS(rword = pi->res_word;)
7310 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7311 rword, cond_code, last_rword);
7312#if ENABLE_HUSH_LOOPS
7313 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7314 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7315 ) {
7316 /* start of a loop: remember where loop starts */
7317 loop_top = pi;
7318 G.depth_of_loop++;
7319 }
7320#endif
7321 /* Still in the same "if...", "then..." or "do..." branch? */
7322 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7323 if ((rcode == 0 && last_followup == PIPE_OR)
7324 || (rcode != 0 && last_followup == PIPE_AND)
7325 ) {
7326 /* It is "<true> || CMD" or "<false> && CMD"
7327 * and we should not execute CMD */
7328 debug_printf_exec("skipped cmd because of || or &&\n");
7329 last_followup = pi->followup;
7330 continue;
7331 }
7332 }
7333 last_followup = pi->followup;
7334 IF_HAS_KEYWORDS(last_rword = rword;)
7335#if ENABLE_HUSH_IF
7336 if (cond_code) {
7337 if (rword == RES_THEN) {
7338 /* if false; then ... fi has exitcode 0! */
7339 G.last_exitcode = rcode = EXIT_SUCCESS;
7340 /* "if <false> THEN cmd": skip cmd */
7341 continue;
7342 }
7343 } else {
7344 if (rword == RES_ELSE || rword == RES_ELIF) {
7345 /* "if <true> then ... ELSE/ELIF cmd":
7346 * skip cmd and all following ones */
7347 break;
7348 }
7349 }
7350#endif
7351#if ENABLE_HUSH_LOOPS
7352 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7353 if (!for_lcur) {
7354 /* first loop through for */
7355
7356 static const char encoded_dollar_at[] ALIGN1 = {
7357 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7358 }; /* encoded representation of "$@" */
7359 static const char *const encoded_dollar_at_argv[] = {
7360 encoded_dollar_at, NULL
7361 }; /* argv list with one element: "$@" */
7362 char **vals;
7363
7364 vals = (char**)encoded_dollar_at_argv;
7365 if (pi->next->res_word == RES_IN) {
7366 /* if no variable values after "in" we skip "for" */
7367 if (!pi->next->cmds[0].argv) {
7368 G.last_exitcode = rcode = EXIT_SUCCESS;
7369 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7370 break;
7371 }
7372 vals = pi->next->cmds[0].argv;
7373 } /* else: "for var; do..." -> assume "$@" list */
7374 /* create list of variable values */
7375 debug_print_strings("for_list made from", vals);
7376 for_list = expand_strvec_to_strvec(vals);
7377 for_lcur = for_list;
7378 debug_print_strings("for_list", for_list);
7379 }
7380 if (!*for_lcur) {
7381 /* "for" loop is over, clean up */
7382 free(for_list);
7383 for_list = NULL;
7384 for_lcur = NULL;
7385 break;
7386 }
7387 /* Insert next value from for_lcur */
7388 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7389 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7390 continue;
7391 }
7392 if (rword == RES_IN) {
7393 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7394 }
7395 if (rword == RES_DONE) {
7396 continue; /* "done" has no cmds too */
7397 }
7398#endif
7399#if ENABLE_HUSH_CASE
7400 if (rword == RES_CASE) {
7401 case_word = expand_strvec_to_string(pi->cmds->argv);
7402 continue;
7403 }
7404 if (rword == RES_MATCH) {
7405 char **argv;
7406
7407 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7408 break;
7409 /* all prev words didn't match, does this one match? */
7410 argv = pi->cmds->argv;
7411 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007412 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007413 /* TODO: which FNM_xxx flags to use? */
7414 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7415 free(pattern);
7416 if (cond_code == 0) { /* match! we will execute this branch */
7417 free(case_word); /* make future "word)" stop */
7418 case_word = NULL;
7419 break;
7420 }
7421 argv++;
7422 }
7423 continue;
7424 }
7425 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7426 if (cond_code != 0)
7427 continue; /* not matched yet, skip this pipe */
7428 }
7429#endif
7430 /* Just pressing <enter> in shell should check for jobs.
7431 * OTOH, in non-interactive shell this is useless
7432 * and only leads to extra job checks */
7433 if (pi->num_cmds == 0) {
7434 if (G_interactive_fd)
7435 goto check_jobs_and_continue;
7436 continue;
7437 }
7438
7439 /* After analyzing all keywords and conditions, we decided
7440 * to execute this pipe. NB: have to do checkjobs(NULL)
7441 * after run_pipe to collect any background children,
7442 * even if list execution is to be stopped. */
7443 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7444 {
7445 int r;
7446#if ENABLE_HUSH_LOOPS
7447 G.flag_break_continue = 0;
7448#endif
7449 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7450 if (r != -1) {
7451 /* We ran a builtin, function, or group.
7452 * rcode is already known
7453 * and we don't need to wait for anything. */
7454 G.last_exitcode = rcode;
7455 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007456 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007457#if ENABLE_HUSH_LOOPS
7458 /* Was it "break" or "continue"? */
7459 if (G.flag_break_continue) {
7460 smallint fbc = G.flag_break_continue;
7461 /* We might fall into outer *loop*,
7462 * don't want to break it too */
7463 if (loop_top) {
7464 G.depth_break_continue--;
7465 if (G.depth_break_continue == 0)
7466 G.flag_break_continue = 0;
7467 /* else: e.g. "continue 2" should *break* once, *then* continue */
7468 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7469 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7470 goto check_jobs_and_break;
7471 /* "continue": simulate end of loop */
7472 rword = RES_DONE;
7473 continue;
7474 }
7475#endif
7476#if ENABLE_HUSH_FUNCTIONS
7477 if (G.flag_return_in_progress == 1) {
7478 /* same as "goto check_jobs_and_break" */
7479 checkjobs(NULL);
7480 break;
7481 }
7482#endif
7483 } else if (pi->followup == PIPE_BG) {
7484 /* What does bash do with attempts to background builtins? */
7485 /* even bash 3.2 doesn't do that well with nested bg:
7486 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7487 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007488 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007489#if ENABLE_HUSH_JOB
7490 if (G.run_list_level == 1)
7491 insert_bg_job(pi);
7492#endif
7493 /* Last command's pid goes to $! */
7494 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7495 G.last_exitcode = rcode = EXIT_SUCCESS;
7496 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7497 } else {
7498#if ENABLE_HUSH_JOB
7499 if (G.run_list_level == 1 && G_interactive_fd) {
7500 /* Waits for completion, then fg's main shell */
7501 rcode = checkjobs_and_fg_shell(pi);
7502 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007503 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007504 } else
7505#endif
7506 { /* This one just waits for completion */
7507 rcode = checkjobs(pi);
7508 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007509 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007510 }
7511 G.last_exitcode = rcode;
7512 }
7513 }
7514
7515 /* Analyze how result affects subsequent commands */
7516#if ENABLE_HUSH_IF
7517 if (rword == RES_IF || rword == RES_ELIF)
7518 cond_code = rcode;
7519#endif
7520#if ENABLE_HUSH_LOOPS
7521 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007522 if (pi->next
7523 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02007524 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007525 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007526 if (rword == RES_WHILE) {
7527 if (rcode) {
7528 /* "while false; do...done" - exitcode 0 */
7529 G.last_exitcode = rcode = EXIT_SUCCESS;
7530 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7531 goto check_jobs_and_break;
7532 }
7533 }
7534 if (rword == RES_UNTIL) {
7535 if (!rcode) {
7536 debug_printf_exec(": until expr is true: breaking\n");
7537 check_jobs_and_break:
7538 checkjobs(NULL);
7539 break;
7540 }
7541 }
7542 }
7543#endif
7544
7545 check_jobs_and_continue:
7546 checkjobs(NULL);
7547 } /* for (pi) */
7548
7549#if ENABLE_HUSH_JOB
7550 G.run_list_level--;
7551#endif
7552#if ENABLE_HUSH_LOOPS
7553 if (loop_top)
7554 G.depth_of_loop--;
7555 free(for_list);
7556#endif
7557#if ENABLE_HUSH_CASE
7558 free(case_word);
7559#endif
7560 debug_leave();
7561 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7562 return rcode;
7563}
7564
7565/* Select which version we will use */
7566static int run_and_free_list(struct pipe *pi)
7567{
7568 int rcode = 0;
7569 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007570 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007571 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7572 rcode = run_list(pi);
7573 }
7574 /* free_pipe_list has the side effect of clearing memory.
7575 * In the long run that function can be merged with run_list,
7576 * but doing that now would hobble the debugging effort. */
7577 free_pipe_list(pi);
7578 debug_printf_exec("run_and_free_list return %d\n", rcode);
7579 return rcode;
7580}
7581
7582
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007583static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007584{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007585 sighandler_t old_handler;
7586 unsigned sig = 0;
7587 while ((mask >>= 1) != 0) {
7588 sig++;
7589 if (!(mask & 1))
7590 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007591 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007592 /* POSIX allows shell to re-enable SIGCHLD
7593 * even if it was SIG_IGN on entry.
7594 * Therefore we skip IGN check for it:
7595 */
7596 if (sig == SIGCHLD)
7597 continue;
7598 if (old_handler == SIG_IGN) {
7599 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007600 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007601 if (!G.traps)
7602 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7603 free(G.traps[sig]);
7604 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7605 }
7606 }
7607}
7608
7609/* Called a few times only (or even once if "sh -c") */
7610static void install_special_sighandlers(void)
7611{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007612 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007613
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007614 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007615 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007616 if (G_interactive_fd) {
7617 mask |= SPECIAL_INTERACTIVE_SIGS;
7618 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007619 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007620 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007621 /* Careful, do not re-install handlers we already installed */
7622 if (G.special_sig_mask != mask) {
7623 unsigned diff = mask & ~G.special_sig_mask;
7624 G.special_sig_mask = mask;
7625 install_sighandlers(diff);
7626 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007627}
7628
7629#if ENABLE_HUSH_JOB
7630/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007631/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007632static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007633{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007634 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007635
7636 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007637 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007638 + (1 << SIGILL ) * HUSH_DEBUG
7639 + (1 << SIGFPE ) * HUSH_DEBUG
7640 + (1 << SIGBUS ) * HUSH_DEBUG
7641 + (1 << SIGSEGV) * HUSH_DEBUG
7642 + (1 << SIGTRAP) * HUSH_DEBUG
7643 + (1 << SIGABRT)
7644 /* bash 3.2 seems to handle these just like 'fatal' ones */
7645 + (1 << SIGPIPE)
7646 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007647 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007648 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007649 * we never want to restore pgrp on exit, and this fn is not called
7650 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007651 /*+ (1 << SIGHUP )*/
7652 /*+ (1 << SIGTERM)*/
7653 /*+ (1 << SIGINT )*/
7654 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007655 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007656
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007657 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007658}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007659#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007660
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007661static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007662{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007663 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007664 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007665 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007666 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007667 break;
7668 case 'x':
7669 IF_HUSH_MODE_X(G_x_mode = state;)
7670 break;
7671 case 'o':
7672 if (!o_opt) {
7673 /* "set -+o" without parameter.
7674 * in bash, set -o produces this output:
7675 * pipefail off
7676 * and set +o:
7677 * set +o pipefail
7678 * We always use the second form.
7679 */
7680 const char *p = o_opt_strings;
7681 idx = 0;
7682 while (*p) {
7683 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7684 idx++;
7685 p += strlen(p) + 1;
7686 }
7687 break;
7688 }
7689 idx = index_in_strings(o_opt_strings, o_opt);
7690 if (idx >= 0) {
7691 G.o_opt[idx] = state;
7692 break;
7693 }
7694 default:
7695 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007696 }
7697 return EXIT_SUCCESS;
7698}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007699
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007700int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007701int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007702{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007703 enum {
7704 OPT_login = (1 << 0),
7705 };
7706 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00007707 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007708 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007709 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007710 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007711 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007712
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007713 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02007714 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007715 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenko10c01312011-05-11 11:49:21 +02007716#if ENABLE_HUSH_FAST
7717 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7718#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007719#if !BB_MMU
7720 G.argv0_for_re_execing = argv[0];
7721#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007722 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007723 shell_ver = xzalloc(sizeof(*shell_ver));
7724 shell_ver->flg_export = 1;
7725 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007726 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007727 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007728 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007729 /* Create shell local variables from the values
7730 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007731 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007732 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007733 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007734 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007735 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007736 if (e) while (*e) {
7737 char *value = strchr(*e, '=');
7738 if (value) { /* paranoia */
7739 cur_var->next = xzalloc(sizeof(*cur_var));
7740 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007741 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007742 cur_var->max_len = strlen(*e);
7743 cur_var->flg_export = 1;
7744 }
7745 e++;
7746 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007747 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007748 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7749 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007750
7751 /* Export PWD */
7752 set_pwd_var(/*exp:*/ 1);
7753 /* bash also exports SHLVL and _,
7754 * and sets (but doesn't export) the following variables:
7755 * BASH=/bin/bash
7756 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7757 * BASH_VERSION='3.2.0(1)-release'
7758 * HOSTTYPE=i386
7759 * MACHTYPE=i386-pc-linux-gnu
7760 * OSTYPE=linux-gnu
7761 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007762 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007763 * EUID=<NNNNN>
7764 * UID=<NNNNN>
7765 * GROUPS=()
7766 * LINES=<NNN>
7767 * COLUMNS=<NNN>
7768 * BASH_ARGC=()
7769 * BASH_ARGV=()
7770 * BASH_LINENO=()
7771 * BASH_SOURCE=()
7772 * DIRSTACK=()
7773 * PIPESTATUS=([0]="0")
7774 * HISTFILE=/<xxx>/.bash_history
7775 * HISTFILESIZE=500
7776 * HISTSIZE=500
7777 * MAILCHECK=60
7778 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7779 * SHELL=/bin/bash
7780 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7781 * TERM=dumb
7782 * OPTERR=1
7783 * OPTIND=1
7784 * IFS=$' \t\n'
7785 * PS1='\s-\v\$ '
7786 * PS2='> '
7787 * PS4='+ '
7788 */
7789
Denis Vlasenko38f63192007-01-22 09:03:07 +00007790#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007791 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007792# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7793 {
7794 const char *hp = get_local_var_value("HISTFILE");
7795 if (!hp) {
7796 hp = get_local_var_value("HOME");
7797 if (hp) {
7798 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7799 //set_local_var(xasprintf("HISTFILE=%s", ...));
7800 }
7801 }
Denys Vlasenko2c4de5b2011-03-31 13:16:52 +02007802# if ENABLE_FEATURE_SH_HISTFILESIZE
7803 hp = get_local_var_value("HISTFILESIZE");
7804 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
7805# endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007806 }
7807# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007808#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007809
Eric Andersen94ac2442001-05-22 19:05:18 +00007810 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007811 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007812
Denis Vlasenkoed782372009-04-10 00:45:02 +00007813 if (setjmp(die_jmp)) {
7814 /* xfunc has failed! die die die */
7815 /* no EXIT traps, this is an escape hatch! */
7816 G.exiting = 1;
7817 hush_exit(xfunc_error_retval);
7818 }
7819
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007820 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007821 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007822 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007823 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007824 * in order to intercept (more) signals.
7825 */
7826
7827 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007828 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007829 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007830 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007831 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007832 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007833#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007834 "<:$:R:V:"
7835# if ENABLE_HUSH_FUNCTIONS
7836 "F:"
7837# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007838#endif
7839 );
7840 if (opt <= 0)
7841 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007842 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007843 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007844 /* Possibilities:
7845 * sh ... -c 'script'
7846 * sh ... -c 'script' ARG0 [ARG1...]
7847 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007848 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007849 * "" needs to be replaced with NULL
7850 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007851 * Note: the form without ARG0 never happens:
7852 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007853 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007854 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007855 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007856 G.root_ppid = getppid();
7857 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007858 G.global_argv = argv + optind;
7859 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007860 if (builtin_argc) {
7861 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7862 const struct built_in_command *x;
7863
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007864 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007865 x = find_builtin(optarg);
7866 if (x) { /* paranoia */
7867 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7868 G.global_argv += builtin_argc;
7869 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007870 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007871 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007872 }
7873 goto final_return;
7874 }
7875 if (!G.global_argv[0]) {
7876 /* -c 'script' (no params): prevent empty $0 */
7877 G.global_argv--; /* points to argv[i] of 'script' */
7878 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007879 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007880 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007881 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007882 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007883 goto final_return;
7884 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007885 /* Well, we cannot just declare interactiveness,
7886 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007887 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007888 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007889 case 's':
7890 /* "-s" means "read from stdin", but this is how we always
7891 * operate, so simply do nothing here. */
7892 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007893 case 'l':
7894 flags |= OPT_login;
7895 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007896#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007897 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007898 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007899 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007900 case '$': {
7901 unsigned long long empty_trap_mask;
7902
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007903 G.root_pid = bb_strtou(optarg, &optarg, 16);
7904 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007905 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7906 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007907 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7908 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007909 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007910 optarg++;
7911 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007912 optarg++;
7913 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7914 if (empty_trap_mask != 0) {
7915 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007916 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007917 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7918 for (sig = 1; sig < NSIG; sig++) {
7919 if (empty_trap_mask & (1LL << sig)) {
7920 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007921 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007922 }
7923 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007924 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007925# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007926 optarg++;
7927 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007928# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007929 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007930 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007931 case 'R':
7932 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007933 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007934 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007935# if ENABLE_HUSH_FUNCTIONS
7936 case 'F': {
7937 struct function *funcp = new_function(optarg);
7938 /* funcp->name is already set to optarg */
7939 /* funcp->body is set to NULL. It's a special case. */
7940 funcp->body_as_string = argv[optind];
7941 optind++;
7942 break;
7943 }
7944# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007945#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007946 case 'n':
7947 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007948 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007949 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007950 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007951#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007952 fprintf(stderr, "Usage: sh [FILE]...\n"
7953 " or: sh -c command [args]...\n\n");
7954 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007955#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007956 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007957#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007958 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007959 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007960
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007961 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7962 G.global_argc = argc - (optind - 1);
7963 G.global_argv = argv + (optind - 1);
7964 G.global_argv[0] = argv[0];
7965
Denys Vlasenkodea47882009-10-09 15:40:49 +02007966 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007967 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007968 G.root_ppid = getppid();
7969 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007970
7971 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007972 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007973 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007974 debug_printf("sourcing /etc/profile\n");
7975 input = fopen_for_read("/etc/profile");
7976 if (input != NULL) {
7977 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007978 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007979 parse_and_run_file(input);
7980 fclose(input);
7981 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007982 /* bash: after sourcing /etc/profile,
7983 * tries to source (in the given order):
7984 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007985 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007986 * bash also sources ~/.bash_logout on exit.
7987 * If called as sh, skips .bash_XXX files.
7988 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007989 }
7990
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007991 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007992 FILE *input;
7993 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007994 * "bash <script>" (which is never interactive (unless -i?))
7995 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007996 * If called as sh, does the same but with $ENV.
7997 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007998 G.global_argc--;
7999 G.global_argv++;
8000 debug_printf("running script '%s'\n", G.global_argv[0]);
8001 input = xfopen_for_read(G.global_argv[0]);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008002 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008003 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008004 parse_and_run_file(input);
8005#if ENABLE_FEATURE_CLEAN_UP
8006 fclose(input);
8007#endif
8008 goto final_return;
8009 }
8010
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008011 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008012 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008013 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008014
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008015 /* A shell is interactive if the '-i' flag was given,
8016 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008017 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008018 * no arguments remaining or the -s flag given
8019 * standard input is a terminal
8020 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008021 * Refer to Posix.2, the description of the 'sh' utility.
8022 */
8023#if ENABLE_HUSH_JOB
8024 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008025 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8026 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8027 if (G_saved_tty_pgrp < 0)
8028 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008029
8030 /* try to dup stdin to high fd#, >= 255 */
8031 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8032 if (G_interactive_fd < 0) {
8033 /* try to dup to any fd */
8034 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008035 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008036 /* give up */
8037 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008038 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008039 }
8040 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008041// TODO: track & disallow any attempts of user
8042// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008043 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008044 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008045 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008046 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008047
Mike Frysinger38478a62009-05-20 04:48:06 -04008048 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008049 /* If we were run as 'hush &', sleep until we are
8050 * in the foreground (tty pgrp == our pgrp).
8051 * If we get started under a job aware app (like bash),
8052 * make sure we are now in charge so we don't fight over
8053 * who gets the foreground */
8054 while (1) {
8055 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008056 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8057 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008058 break;
8059 /* send TTIN to ourself (should stop us) */
8060 kill(- shell_pgrp, SIGTTIN);
8061 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008062 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008063
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008064 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008065 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008066
Mike Frysinger38478a62009-05-20 04:48:06 -04008067 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008068 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008069 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008070 /* Put ourselves in our own process group
8071 * (bash, too, does this only if ctty is available) */
8072 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8073 /* Grab control of the terminal */
8074 tcsetpgrp(G_interactive_fd, getpid());
8075 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00008076 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00008077 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00008078 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008079 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008080 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008081 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008082#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008083 /* No job control compiled in, only prompt/line editing */
8084 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008085 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8086 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008087 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008088 G_interactive_fd = dup(STDIN_FILENO);
8089 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008090 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008091 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008092 }
8093 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008094 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008095 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008096 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008097 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008098#else
8099 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008100 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008101#endif
8102 /* bash:
8103 * if interactive but not a login shell, sources ~/.bashrc
8104 * (--norc turns this off, --rcfile <file> overrides)
8105 */
8106
8107 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008108 /* note: ash and hush share this string */
8109 printf("\n\n%s %s\n"
8110 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8111 "\n",
8112 bb_banner,
8113 "hush - the humble shell"
8114 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008115 }
8116
Denis Vlasenkof9375282009-04-05 19:13:39 +00008117 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008118
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008119 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008120 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008121}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008122
8123
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008124#if ENABLE_MSH
8125int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8126int msh_main(int argc, char **argv)
8127{
8128 //bb_error_msg("msh is deprecated, please use hush instead");
8129 return hush_main(argc, argv);
8130}
8131#endif
8132
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008133
8134/*
8135 * Built-ins
8136 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008137static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008138{
8139 return 0;
8140}
8141
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008142static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008143{
8144 int argc = 0;
8145 while (*argv) {
8146 argc++;
8147 argv++;
8148 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008149 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008150}
8151
8152static int FAST_FUNC builtin_test(char **argv)
8153{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008154 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008155}
8156
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008157static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008158{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008159 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008160}
8161
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008162#if ENABLE_PRINTF
8163static int FAST_FUNC builtin_printf(char **argv)
8164{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008165 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008166}
8167#endif
8168
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008169static char **skip_dash_dash(char **argv)
8170{
8171 argv++;
8172 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8173 argv++;
8174 return argv;
8175}
8176
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008177static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008178{
8179 int rcode = EXIT_SUCCESS;
8180
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008181 argv = skip_dash_dash(argv);
8182 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008183 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008184 /* bash:
8185 * eval "echo Hi; done" ("done" is syntax error):
8186 * "echo Hi" will not execute too.
8187 */
8188 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008189 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008190 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008191 }
8192 return rcode;
8193}
8194
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008195static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008196{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008197 const char *newdir;
8198
8199 argv = skip_dash_dash(argv);
8200 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008201 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008202 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008203 * bash says "bash: cd: HOME not set" and does nothing
8204 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008205 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008206 const char *home = get_local_var_value("HOME");
8207 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008208 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008209 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008210 /* Mimic bash message exactly */
8211 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008212 return EXIT_FAILURE;
8213 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008214 /* Read current dir (get_cwd(1) is inside) and set PWD.
8215 * Note: do not enforce exporting. If PWD was unset or unexported,
8216 * set it again, but do not export. bash does the same.
8217 */
8218 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008219 return EXIT_SUCCESS;
8220}
8221
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008222static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008223{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008224 argv = skip_dash_dash(argv);
8225 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008226 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008227
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008228 /* Careful: we can end up here after [v]fork. Do not restore
8229 * tty pgrp then, only top-level shell process does that */
8230 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8231 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8232
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008233 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008234 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008235 * and tcsetpgrp, and this is inherently racy.
8236 */
8237 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008238}
8239
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008240static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008241{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008242 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008243
8244 /* interactive bash:
8245 * # trap "echo EEE" EXIT
8246 * # exit
8247 * exit
8248 * There are stopped jobs.
8249 * (if there are _stopped_ jobs, running ones don't count)
8250 * # exit
8251 * exit
8252 # EEE (then bash exits)
8253 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008254 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008255 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008256
8257 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008258 argv = skip_dash_dash(argv);
8259 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008260 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008261 /* mimic bash: exit 123abc == exit 255 + error msg */
8262 xfunc_error_retval = 255;
8263 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008264 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008265}
8266
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008267static void print_escaped(const char *s)
8268{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008269 if (*s == '\'')
8270 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008271 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008272 const char *p = strchrnul(s, '\'');
8273 /* print 'xxxx', possibly just '' */
8274 printf("'%.*s'", (int)(p - s), s);
8275 if (*p == '\0')
8276 break;
8277 s = p;
8278 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008279 /* s points to '; print "'''...'''" */
8280 putchar('"');
8281 do putchar('\''); while (*++s == '\'');
8282 putchar('"');
8283 } while (*s);
8284}
8285
Denys Vlasenko295fef82009-06-03 12:47:26 +02008286#if !ENABLE_HUSH_LOCAL
8287#define helper_export_local(argv, exp, lvl) \
8288 helper_export_local(argv, exp)
8289#endif
8290static void helper_export_local(char **argv, int exp, int lvl)
8291{
8292 do {
8293 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008294 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008295
8296 /* So far we do not check that name is valid (TODO?) */
8297
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008298 if (*name_end == '\0') {
8299 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008300
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008301 vpp = get_ptr_to_local_var(name, name_end - name);
8302 var = vpp ? *vpp : NULL;
8303
Denys Vlasenko295fef82009-06-03 12:47:26 +02008304 if (exp == -1) { /* unexporting? */
8305 /* export -n NAME (without =VALUE) */
8306 if (var) {
8307 var->flg_export = 0;
8308 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8309 unsetenv(name);
8310 } /* else: export -n NOT_EXISTING_VAR: no-op */
8311 continue;
8312 }
8313 if (exp == 1) { /* exporting? */
8314 /* export NAME (without =VALUE) */
8315 if (var) {
8316 var->flg_export = 1;
8317 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8318 putenv(var->varstr);
8319 continue;
8320 }
8321 }
8322 /* Exporting non-existing variable.
8323 * bash does not put it in environment,
8324 * but remembers that it is exported,
8325 * and does put it in env when it is set later.
8326 * We just set it to "" and export. */
8327 /* Or, it's "local NAME" (without =VALUE).
8328 * bash sets the value to "". */
8329 name = xasprintf("%s=", name);
8330 } else {
8331 /* (Un)exporting/making local NAME=VALUE */
8332 name = xstrdup(name);
8333 }
8334 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8335 } while (*++argv);
8336}
8337
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008338static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008339{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008340 unsigned opt_unexport;
8341
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008342#if ENABLE_HUSH_EXPORT_N
8343 /* "!": do not abort on errors */
8344 opt_unexport = getopt32(argv, "!n");
8345 if (opt_unexport == (uint32_t)-1)
8346 return EXIT_FAILURE;
8347 argv += optind;
8348#else
8349 opt_unexport = 0;
8350 argv++;
8351#endif
8352
8353 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008354 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008355 if (e) {
8356 while (*e) {
8357#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008358 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008359#else
8360 /* ash emits: export VAR='VAL'
8361 * bash: declare -x VAR="VAL"
8362 * we follow ash example */
8363 const char *s = *e++;
8364 const char *p = strchr(s, '=');
8365
8366 if (!p) /* wtf? take next variable */
8367 continue;
8368 /* export var= */
8369 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008370 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008371 putchar('\n');
8372#endif
8373 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008374 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008375 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008376 return EXIT_SUCCESS;
8377 }
8378
Denys Vlasenko295fef82009-06-03 12:47:26 +02008379 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008380
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008381 return EXIT_SUCCESS;
8382}
8383
Denys Vlasenko295fef82009-06-03 12:47:26 +02008384#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008385static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008386{
8387 if (G.func_nest_level == 0) {
8388 bb_error_msg("%s: not in a function", argv[0]);
8389 return EXIT_FAILURE; /* bash compat */
8390 }
8391 helper_export_local(argv, 0, G.func_nest_level);
8392 return EXIT_SUCCESS;
8393}
8394#endif
8395
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008396static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008397{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008398 int sig;
8399 char *new_cmd;
8400
8401 if (!G.traps)
8402 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8403
8404 argv++;
8405 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008406 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008407 /* No args: print all trapped */
8408 for (i = 0; i < NSIG; ++i) {
8409 if (G.traps[i]) {
8410 printf("trap -- ");
8411 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008412 /* note: bash adds "SIG", but only if invoked
8413 * as "bash". If called as "sh", or if set -o posix,
8414 * then it prints short signal names.
8415 * We are printing short names: */
8416 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008417 }
8418 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008419 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008420 return EXIT_SUCCESS;
8421 }
8422
8423 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008424 /* If first arg is a number: reset all specified signals */
8425 sig = bb_strtou(*argv, NULL, 10);
8426 if (errno == 0) {
8427 int ret;
8428 process_sig_list:
8429 ret = EXIT_SUCCESS;
8430 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008431 sighandler_t handler;
8432
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008433 sig = get_signum(*argv++);
8434 if (sig < 0 || sig >= NSIG) {
8435 ret = EXIT_FAILURE;
8436 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008437 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008438 continue;
8439 }
8440
8441 free(G.traps[sig]);
8442 G.traps[sig] = xstrdup(new_cmd);
8443
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008444 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008445 get_signame(sig), sig, G.traps[sig]);
8446
8447 /* There is no signal for 0 (EXIT) */
8448 if (sig == 0)
8449 continue;
8450
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008451 if (new_cmd)
8452 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8453 else
8454 /* We are removing trap handler */
8455 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02008456 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008457 }
8458 return ret;
8459 }
8460
8461 if (!argv[1]) { /* no second arg */
8462 bb_error_msg("trap: invalid arguments");
8463 return EXIT_FAILURE;
8464 }
8465
8466 /* First arg is "-": reset all specified to default */
8467 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8468 /* Everything else: set arg as signal handler
8469 * (includes "" case, which ignores signal) */
8470 if (argv[0][0] == '-') {
8471 if (argv[0][1] == '\0') { /* "-" */
8472 /* new_cmd remains NULL: "reset these sigs" */
8473 goto reset_traps;
8474 }
8475 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8476 argv++;
8477 }
8478 /* else: "-something", no special meaning */
8479 }
8480 new_cmd = *argv;
8481 reset_traps:
8482 argv++;
8483 goto process_sig_list;
8484}
8485
Mike Frysinger93cadc22009-05-27 17:06:25 -04008486/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008487static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008488{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008489 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008490
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008491 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008492 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008493 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008494
8495 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008496 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008497 type = "an alias";*/
8498#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008499 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008500 type = "a function";
8501#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008502 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008503 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008504 else if ((path = find_in_path(*argv)) != NULL)
8505 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008506 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008507 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008508 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008509 continue;
8510 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008511
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008512 printf("%s is %s\n", *argv, type);
8513 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008514 }
8515
8516 return ret;
8517}
8518
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008519#if ENABLE_HUSH_JOB
8520/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008521static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008522{
8523 int i, jobnum;
8524 struct pipe *pi;
8525
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008526 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008527 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008528
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008529 /* If they gave us no args, assume they want the last backgrounded task */
8530 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008531 for (pi = G.job_list; pi; pi = pi->next) {
8532 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008533 goto found;
8534 }
8535 }
8536 bb_error_msg("%s: no current job", argv[0]);
8537 return EXIT_FAILURE;
8538 }
8539 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8540 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8541 return EXIT_FAILURE;
8542 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008543 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008544 if (pi->jobid == jobnum) {
8545 goto found;
8546 }
8547 }
8548 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8549 return EXIT_FAILURE;
8550 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008551 /* TODO: bash prints a string representation
8552 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008553 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008554 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008555 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008556 }
8557
8558 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008559 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8560 for (i = 0; i < pi->num_cmds; i++) {
8561 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8562 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008563 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008564 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008565
8566 i = kill(- pi->pgrp, SIGCONT);
8567 if (i < 0) {
8568 if (errno == ESRCH) {
8569 delete_finished_bg_job(pi);
8570 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008571 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008572 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008573 }
8574
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008575 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008576 remove_bg_job(pi);
8577 return checkjobs_and_fg_shell(pi);
8578 }
8579 return EXIT_SUCCESS;
8580}
8581#endif
8582
8583#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008584static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008585{
8586 const struct built_in_command *x;
8587
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008588 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008589 "Built-in commands:\n"
8590 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008591 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008592 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008593 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008594 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008595 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008596 return EXIT_SUCCESS;
8597}
8598#endif
8599
8600#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008601static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008602{
8603 struct pipe *job;
8604 const char *status_string;
8605
Denis Vlasenko87a86552008-07-29 19:43:10 +00008606 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008607 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008608 status_string = "Stopped";
8609 else
8610 status_string = "Running";
8611
8612 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8613 }
8614 return EXIT_SUCCESS;
8615}
8616#endif
8617
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008618#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008619static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008620{
8621 void *p;
8622 unsigned long l;
8623
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008624# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008625 /* Optional. Reduces probability of false positives */
8626 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008627# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008628 /* Crude attempt to find where "free memory" starts,
8629 * sans fragmentation. */
8630 p = malloc(240);
8631 l = (unsigned long)p;
8632 free(p);
8633 p = malloc(3400);
8634 if (l < (unsigned long)p) l = (unsigned long)p;
8635 free(p);
8636
8637 if (!G.memleak_value)
8638 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008639
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008640 l -= G.memleak_value;
8641 if ((long)l < 0)
8642 l = 0;
8643 l /= 1024;
8644 if (l > 127)
8645 l = 127;
8646
8647 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8648 return l;
8649}
8650#endif
8651
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008652static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008653{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008654 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008655 return EXIT_SUCCESS;
8656}
8657
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008658/* Interruptibility of read builtin in bash
8659 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8660 *
8661 * Empty trap makes read ignore corresponding signal, for any signal.
8662 *
8663 * SIGINT:
8664 * - terminates non-interactive shell;
8665 * - interrupts read in interactive shell;
8666 * if it has non-empty trap:
8667 * - executes trap and returns to command prompt in interactive shell;
8668 * - executes trap and returns to read in non-interactive shell;
8669 * SIGTERM:
8670 * - is ignored (does not interrupt) read in interactive shell;
8671 * - terminates non-interactive shell;
8672 * if it has non-empty trap:
8673 * - executes trap and returns to read;
8674 * SIGHUP:
8675 * - terminates shell (regardless of interactivity);
8676 * if it has non-empty trap:
8677 * - executes trap and returns to read;
8678 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008679static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008680{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008681 const char *r;
8682 char *opt_n = NULL;
8683 char *opt_p = NULL;
8684 char *opt_t = NULL;
8685 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008686 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01008687 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008688
Denys Vlasenko03dad222010-01-12 23:29:57 +01008689 /* "!": do not abort on errors.
8690 * Option string must start with "sr" to match BUILTIN_READ_xxx
8691 */
8692 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8693 if (read_flags == (uint32_t)-1)
8694 return EXIT_FAILURE;
8695 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008696 ifs = get_local_var_value("IFS"); /* can be NULL */
8697
8698 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01008699 r = shell_builtin_read(set_local_var_from_halves,
8700 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008701 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01008702 read_flags,
8703 opt_n,
8704 opt_p,
8705 opt_t,
8706 opt_u
8707 );
8708
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008709 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008710 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008711 if (sig && sig != SIGINT)
8712 goto again;
8713 }
8714
Denys Vlasenko03dad222010-01-12 23:29:57 +01008715 if ((uintptr_t)r > 1) {
8716 bb_error_msg("%s", r);
8717 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008718 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008719
Denys Vlasenko03dad222010-01-12 23:29:57 +01008720 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008721}
8722
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008723/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8724 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008725 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008726 * set [-abCefhmnuvx] [-o option] [argument...]
8727 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008728 * set -- [argument...]
8729 * set -o
8730 * set +o
8731 * Implementations shall support the options in both their hyphen and
8732 * plus-sign forms. These options can also be specified as options to sh.
8733 * Examples:
8734 * Write out all variables and their values: set
8735 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8736 * Turn on the -x and -v options: set -xv
8737 * Unset all positional parameters: set --
8738 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8739 * Set the positional parameters to the expansion of x, even if x expands
8740 * with a leading '-' or '+': set -- $x
8741 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008742 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008743 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008744static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008745{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008746 int n;
8747 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008748 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008749
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008750 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008751 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008752 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008753 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008754 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008755 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008756
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008757 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008758 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008759 ++argv;
8760 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008761 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008762 if (arg[0] != '+' && arg[0] != '-')
8763 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008764 for (n = 1; arg[n]; ++n) {
8765 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008766 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008767 if (arg[n] == 'o' && argv[1])
8768 argv++;
8769 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008770 } while ((arg = *++argv) != NULL);
8771 /* Now argv[0] is 1st argument */
8772
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008773 if (arg == NULL)
8774 return EXIT_SUCCESS;
8775 set_argv:
8776
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008777 /* NB: G.global_argv[0] ($0) is never freed/changed */
8778 g_argv = G.global_argv;
8779 if (G.global_args_malloced) {
8780 pp = g_argv;
8781 while (*++pp)
8782 free(*pp);
8783 g_argv[1] = NULL;
8784 } else {
8785 G.global_args_malloced = 1;
8786 pp = xzalloc(sizeof(pp[0]) * 2);
8787 pp[0] = g_argv[0]; /* retain $0 */
8788 g_argv = pp;
8789 }
8790 /* This realloc's G.global_argv */
8791 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8792
8793 n = 1;
8794 while (*++pp)
8795 n++;
8796 G.global_argc = n;
8797
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008798 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008799
8800 /* Nothing known, so abort */
8801 error:
8802 bb_error_msg("set: %s: invalid option", arg);
8803 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008804}
8805
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008806static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008807{
8808 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008809 argv = skip_dash_dash(argv);
8810 if (argv[0]) {
8811 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008812 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008813 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008814 if (G.global_args_malloced) {
8815 int m = 1;
8816 while (m <= n)
8817 free(G.global_argv[m++]);
8818 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008819 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008820 memmove(&G.global_argv[1], &G.global_argv[n+1],
8821 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008822 return EXIT_SUCCESS;
8823 }
8824 return EXIT_FAILURE;
8825}
8826
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008827static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008828{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008829 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008830 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008831 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008832#if ENABLE_HUSH_FUNCTIONS
8833 smallint sv_flg;
8834#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008835
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008836 argv = skip_dash_dash(argv);
8837 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008838 if (!filename) {
8839 /* bash says: "bash: .: filename argument required" */
8840 return 2; /* bash compat */
8841 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008842 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008843 if (!strchr(filename, '/')) {
8844 arg_path = find_in_path(filename);
8845 if (arg_path)
8846 filename = arg_path;
8847 }
8848 input = fopen_or_warn(filename, "r");
8849 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008850 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008851 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008852 return EXIT_FAILURE;
8853 }
8854 close_on_exec_on(fileno(input));
8855
Mike Frysinger885b6f22009-04-18 21:04:25 +00008856#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008857 sv_flg = G.flag_return_in_progress;
8858 /* "we are inside sourced file, ok to use return" */
8859 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008860#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008861 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008862
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008863 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008864 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008865
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008866 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008867#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008868 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008869#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008870
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008871 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008872}
8873
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008874static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008875{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008876 int rc;
8877 mode_t mask;
8878
8879 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008880 argv = skip_dash_dash(argv);
8881 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008882 mode_t old_mask = mask;
8883
8884 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008885 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008886 mask ^= 0777;
8887 if (rc == 0) {
8888 mask = old_mask;
8889 /* bash messages:
8890 * bash: umask: 'q': invalid symbolic mode operator
8891 * bash: umask: 999: octal number out of range
8892 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008893 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008894 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008895 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008896 rc = 1;
8897 /* Mimic bash */
8898 printf("%04o\n", (unsigned) mask);
8899 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008900 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008901 umask(mask);
8902
8903 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008904}
8905
Mike Frysingerd690f682009-03-30 06:50:54 +00008906/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008907static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008908{
Mike Frysingerd690f682009-03-30 06:50:54 +00008909 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008910 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008911
Denis Vlasenko28e67962009-04-26 23:22:40 +00008912 /* "!": do not abort on errors */
8913 /* "+": stop at 1st non-option */
8914 opts = getopt32(argv, "!+vf");
8915 if (opts == (unsigned)-1)
8916 return EXIT_FAILURE;
8917 if (opts == 3) {
8918 bb_error_msg("unset: -v and -f are exclusive");
8919 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008920 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008921 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008922
8923 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008924 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008925 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008926 if (unset_local_var(*argv)) {
8927 /* unset <nonexistent_var> doesn't fail.
8928 * Error is when one tries to unset RO var.
8929 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008930 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008931 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008932 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008933#if ENABLE_HUSH_FUNCTIONS
8934 else {
8935 unset_func(*argv);
8936 }
8937#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008938 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008939 }
8940 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008941}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008942
Mike Frysinger56bdea12009-03-28 20:01:58 +00008943/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008944static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008945{
8946 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008947 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008948
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008949 argv = skip_dash_dash(argv);
8950 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008951 /* Don't care about wait results */
8952 /* Note 1: must wait until there are no more children */
8953 /* Note 2: must be interruptible */
8954 /* Examples:
8955 * $ sleep 3 & sleep 6 & wait
8956 * [1] 30934 sleep 3
8957 * [2] 30935 sleep 6
8958 * [1] Done sleep 3
8959 * [2] Done sleep 6
8960 * $ sleep 3 & sleep 6 & wait
8961 * [1] 30936 sleep 3
8962 * [2] 30937 sleep 6
8963 * [1] Done sleep 3
8964 * ^C <-- after ~4 sec from keyboard
8965 * $
8966 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008967 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008968 int sig;
8969 sigset_t oldset, allsigs;
8970
8971 /* waitpid is not interruptible by SA_RESTARTed
8972 * signals which we use. Thus, this ugly dance:
8973 */
8974
8975 /* Make sure possible SIGCHLD is stored in kernel's
8976 * pending signal mask before we call waitpid.
8977 * Or else we may race with SIGCHLD, lose it,
8978 * and get stuck in sigwaitinfo...
8979 */
8980 sigfillset(&allsigs);
8981 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
8982
8983 if (!sigisemptyset(&G.pending_set)) {
8984 /* Crap! we raced with some signal! */
8985 // sig = 0;
8986 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008987 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008988
8989 checkjobs(NULL); /* waitpid(WNOHANG) inside */
8990 if (errno == ECHILD) {
8991 sigprocmask(SIG_SETMASK, &oldset, NULL);
8992 break;
8993 }
8994
8995 /* Wait for SIGCHLD or any other signal */
8996 //sig = sigwaitinfo(&allsigs, NULL);
8997 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
8998 /* Note: sigsuspend invokes signal handler */
8999 sigsuspend(&oldset);
9000 restore:
9001 sigprocmask(SIG_SETMASK, &oldset, NULL);
9002
9003 /* So, did we get a signal? */
9004 //if (sig > 0)
9005 // raise(sig); /* run handler */
9006 sig = check_and_run_traps();
9007 if (sig /*&& sig != SIGCHLD - always true */) {
9008 /* see note 2 */
9009 ret = 128 + sig;
9010 break;
9011 }
9012 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009013 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009014 return ret;
9015 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009016
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009017 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009018 while (*argv) {
9019 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00009020 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009021 /* mimic bash message */
9022 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009023 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009024 }
9025 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00009026 if (WIFSIGNALED(status))
9027 ret = 128 + WTERMSIG(status);
9028 else if (WIFEXITED(status))
9029 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00009030 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00009031 ret = EXIT_FAILURE;
9032 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009033 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009034 ret = 127;
9035 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00009036 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009037 }
9038
9039 return ret;
9040}
9041
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009042#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9043static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9044{
9045 if (argv[1]) {
9046 def = bb_strtou(argv[1], NULL, 10);
9047 if (errno || def < def_min || argv[2]) {
9048 bb_error_msg("%s: bad arguments", argv[0]);
9049 def = UINT_MAX;
9050 }
9051 }
9052 return def;
9053}
9054#endif
9055
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009056#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009057static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009058{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009059 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009060 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009061 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009062 return EXIT_SUCCESS; /* bash compat */
9063 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009064 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009065
9066 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9067 if (depth == UINT_MAX)
9068 G.flag_break_continue = BC_BREAK;
9069 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009070 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009071
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009072 return EXIT_SUCCESS;
9073}
9074
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009075static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009076{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009077 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9078 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009079}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009080#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009081
9082#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009083static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009084{
9085 int rc;
9086
9087 if (G.flag_return_in_progress != -1) {
9088 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9089 return EXIT_FAILURE; /* bash compat */
9090 }
9091
9092 G.flag_return_in_progress = 1;
9093
9094 /* bash:
9095 * out of range: wraps around at 256, does not error out
9096 * non-numeric param:
9097 * f() { false; return qwe; }; f; echo $?
9098 * bash: return: qwe: numeric argument required <== we do this
9099 * 255 <== we also do this
9100 */
9101 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9102 return rc;
9103}
9104#endif