blob: 7a34f59ae60b25a8c98b6f8e1ce04940f7750dfb [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 Vlasenkobede2152011-09-04 16:12:33 +02001544#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1545 save_history(G.line_input_state);
1546#endif
1547
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001548 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001549 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001550 char *argv[3];
1551 /* argv[0] is unused */
1552 argv[1] = G.traps[0];
1553 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001554 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001555 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001556 * "trap" will still show it, if executed
1557 * in the handler */
1558 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001559 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001560
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001561#if ENABLE_FEATURE_CLEAN_UP
1562 {
1563 struct variable *cur_var;
1564 if (G.cwd != bb_msg_unknown)
1565 free((char*)G.cwd);
1566 cur_var = G.top_var;
1567 while (cur_var) {
1568 struct variable *tmp = cur_var;
1569 if (!cur_var->max_len)
1570 free(cur_var->varstr);
1571 cur_var = cur_var->next;
1572 free(tmp);
1573 }
1574 }
1575#endif
1576
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001577#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001578 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001579 sigexit(- (exitcode & 0xff));
1580#else
1581 exit(exitcode);
1582#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001583}
1584
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001585
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001586//TODO: return a mask of ALL handled sigs?
1587static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001588{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001589 int last_sig = 0;
1590
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001591 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001592 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001593
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001594 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001595 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001596 sig = 0;
1597 do {
1598 sig++;
1599 if (sigismember(&G.pending_set, sig)) {
1600 sigdelset(&G.pending_set, sig);
1601 goto got_sig;
1602 }
1603 } while (sig < NSIG);
1604 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001605 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001606 if (G.traps && G.traps[sig]) {
1607 if (G.traps[sig][0]) {
1608 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001609 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001610 char *argv[3];
1611 /* argv[0] is unused */
1612 argv[1] = G.traps[sig];
1613 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001614 save_rcode = G.last_exitcode;
1615 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001616 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001617 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001618 } /* else: "" trap, ignoring signal */
1619 continue;
1620 }
1621 /* not a trap: special action */
1622 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001623 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001624 /* Builtin was ^C'ed, make it look prettier: */
1625 bb_putchar('\n');
1626 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001627 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001628 break;
1629#if ENABLE_HUSH_JOB
1630 case SIGHUP: {
1631 struct pipe *job;
1632 /* bash is observed to signal whole process groups,
1633 * not individual processes */
1634 for (job = G.job_list; job; job = job->next) {
1635 if (job->pgrp <= 0)
1636 continue;
1637 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1638 if (kill(- job->pgrp, SIGHUP) == 0)
1639 kill(- job->pgrp, SIGCONT);
1640 }
1641 sigexit(SIGHUP);
1642 }
1643#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001644#if ENABLE_HUSH_FAST
1645 case SIGCHLD:
1646 G.count_SIGCHLD++;
1647//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1648 /* Note:
1649 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1650 * This simplifies wait builtin a bit.
1651 */
1652 break;
1653#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001654 default: /* ignored: */
1655 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001656 /* Note:
1657 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1658 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001659 * in interactive shell, because TERM is ignored.
1660 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001661 break;
1662 }
1663 }
1664 return last_sig;
1665}
1666
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001667
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001668static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001669{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001670 if (force || G.cwd == NULL) {
1671 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1672 * we must not try to free(bb_msg_unknown) */
1673 if (G.cwd == bb_msg_unknown)
1674 G.cwd = NULL;
1675 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1676 if (!G.cwd)
1677 G.cwd = bb_msg_unknown;
1678 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001679 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001680}
1681
Denis Vlasenko83506862007-11-23 13:11:42 +00001682
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001683/*
1684 * Shell and environment variable support
1685 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001686static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001687{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001688 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001689 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001690
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001691 pp = &G.top_var;
1692 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001693 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001694 return pp;
1695 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001696 }
1697 return NULL;
1698}
1699
Denys Vlasenko03dad222010-01-12 23:29:57 +01001700static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001701{
Denys Vlasenko29082232010-07-16 13:52:32 +02001702 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001703 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001704
1705 if (G.expanded_assignments) {
1706 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001707 while (*cpp) {
1708 char *cp = *cpp;
1709 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1710 return cp + len + 1;
1711 cpp++;
1712 }
1713 }
1714
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001715 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001716 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001717 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001718
Denys Vlasenkodea47882009-10-09 15:40:49 +02001719 if (strcmp(name, "PPID") == 0)
1720 return utoa(G.root_ppid);
1721 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001722#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001723 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001724 return utoa(next_random(&G.random_gen));
1725#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001726 return NULL;
1727}
1728
1729/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001730 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001731 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001732 * 0: do not change export flag
1733 * (if creating new variable, flag will be 0)
1734 * 1: set export flag and putenv the variable
1735 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001736 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001737 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001738#if !BB_MMU && ENABLE_HUSH_LOCAL
1739/* all params are used */
1740#elif BB_MMU && ENABLE_HUSH_LOCAL
1741#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1742 set_local_var(str, flg_export, local_lvl)
1743#elif BB_MMU && !ENABLE_HUSH_LOCAL
1744#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001745 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001746#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1747#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1748 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001749#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001750static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001751{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001752 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001753 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001754 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001755 int name_len;
1756
Denis Vlasenko950bd722009-04-21 11:23:56 +00001757 eq_sign = strchr(str, '=');
1758 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001759 free(str);
1760 return -1;
1761 }
1762
Denis Vlasenko950bd722009-04-21 11:23:56 +00001763 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001764 var_pp = &G.top_var;
1765 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001766 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001767 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001768 continue;
1769 }
1770 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001771 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001772#if !BB_MMU
1773 if (!flg_read_only)
1774#endif
1775 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001776 free(str);
1777 return -1;
1778 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001779 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001780 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1781 *eq_sign = '\0';
1782 unsetenv(str);
1783 *eq_sign = '=';
1784 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001785#if ENABLE_HUSH_LOCAL
1786 if (cur->func_nest_level < local_lvl) {
1787 /* New variable is declared as local,
1788 * and existing one is global, or local
1789 * from enclosing function.
1790 * Remove and save old one: */
1791 *var_pp = cur->next;
1792 cur->next = *G.shadowed_vars_pp;
1793 *G.shadowed_vars_pp = cur;
1794 /* bash 3.2.33(1) and exported vars:
1795 * # export z=z
1796 * # f() { local z=a; env | grep ^z; }
1797 * # f
1798 * z=a
1799 * # env | grep ^z
1800 * z=z
1801 */
1802 if (cur->flg_export)
1803 flg_export = 1;
1804 break;
1805 }
1806#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001807 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001808 free_and_exp:
1809 free(str);
1810 goto exp;
1811 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001812 if (cur->max_len != 0) {
1813 if (cur->max_len >= strlen(str)) {
1814 /* This one is from startup env, reuse space */
1815 strcpy(cur->varstr, str);
1816 goto free_and_exp;
1817 }
1818 } else {
1819 /* max_len == 0 signifies "malloced" var, which we can
1820 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001821 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001822 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001823 cur->max_len = 0;
1824 goto set_str_and_exp;
1825 }
1826
Denys Vlasenko295fef82009-06-03 12:47:26 +02001827 /* Not found - create new variable struct */
1828 cur = xzalloc(sizeof(*cur));
1829#if ENABLE_HUSH_LOCAL
1830 cur->func_nest_level = local_lvl;
1831#endif
1832 cur->next = *var_pp;
1833 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001834
1835 set_str_and_exp:
1836 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001837#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001838 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001839#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001840 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001841 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001842 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001843 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1844 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001845 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001846 if (flg_export == -1) {
1847 cur->flg_export = 0;
1848 /* unsetenv was already done */
1849 } else {
1850 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1851 return putenv(cur->varstr);
1852 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001853 }
1854 return 0;
1855}
1856
Denys Vlasenko6db47842009-09-05 20:15:17 +02001857/* Used at startup and after each cd */
1858static void set_pwd_var(int exp)
1859{
1860 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1861 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1862}
1863
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001864static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001865{
1866 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001867 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001868
1869 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001870 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001871 var_pp = &G.top_var;
1872 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001873 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1874 if (cur->flg_read_only) {
1875 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001876 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001877 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001878 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001879 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1880 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001881 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1882 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001883 if (!cur->max_len)
1884 free(cur->varstr);
1885 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001886 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001887 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001888 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001889 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001890 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001891}
1892
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001893static int unset_local_var(const char *name)
1894{
1895 return unset_local_var_len(name, strlen(name));
1896}
1897
1898static void unset_vars(char **strings)
1899{
1900 char **v;
1901
1902 if (!strings)
1903 return;
1904 v = strings;
1905 while (*v) {
1906 const char *eq = strchrnul(*v, '=');
1907 unset_local_var_len(*v, (int)(eq - *v));
1908 v++;
1909 }
1910 free(strings);
1911}
1912
Denys Vlasenko03dad222010-01-12 23:29:57 +01001913static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001914{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001915 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001916 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001917}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001918
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001919
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001920/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001921 * Helpers for "var1=val1 var2=val2 cmd" feature
1922 */
1923static void add_vars(struct variable *var)
1924{
1925 struct variable *next;
1926
1927 while (var) {
1928 next = var->next;
1929 var->next = G.top_var;
1930 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001931 if (var->flg_export) {
1932 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001933 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001934 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001935 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001936 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001937 var = next;
1938 }
1939}
1940
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001941static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001942{
1943 char **s;
1944 struct variable *old = NULL;
1945
1946 if (!strings)
1947 return old;
1948 s = strings;
1949 while (*s) {
1950 struct variable *var_p;
1951 struct variable **var_pp;
1952 char *eq;
1953
1954 eq = strchr(*s, '=');
1955 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001956 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001957 if (var_pp) {
1958 /* Remove variable from global linked list */
1959 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001960 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001961 *var_pp = var_p->next;
1962 /* Add it to returned list */
1963 var_p->next = old;
1964 old = var_p;
1965 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001966 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001967 }
1968 s++;
1969 }
1970 return old;
1971}
1972
1973
1974/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001975 * in_str support
1976 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001977static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001978{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001979 int ch = *i->p;
1980 if (ch != '\0') {
1981 i->p++;
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001982 i->last_char = ch;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001983 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001984 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001985 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001986}
1987
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001988static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001989{
1990 return *i->p;
1991}
1992
1993#if ENABLE_HUSH_INTERACTIVE
1994
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001995static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001996{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001997 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001998 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001999 if (G.PS1 == NULL)
2000 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002001 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002002 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002003 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002004 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002005 if (G.PS2 == NULL)
2006 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002007}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002008
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002009static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002010{
2011 const char *prompt_str;
2012 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002013 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2014 /* Set up the prompt */
2015 if (promptmode == 0) { /* PS1 */
2016 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002017 /* bash uses $PWD value, even if it is set by user.
2018 * It uses current dir only if PWD is unset.
2019 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002020 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002021 prompt_str = G.PS1;
2022 } else
2023 prompt_str = G.PS2;
2024 } else
2025 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002026 debug_printf("result '%s'\n", prompt_str);
2027 return prompt_str;
2028}
2029
2030static void get_user_input(struct in_str *i)
2031{
2032 int r;
2033 const char *prompt_str;
2034
2035 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002036# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002037 /* Enable command line editing only while a command line
2038 * is actually being read */
2039 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01002040 /* Unicode support should be activated even if LANG is set
2041 * _during_ shell execution, not only if it was set when
2042 * shell was started. Therefore, re-check LANG every time:
2043 */
2044 reinit_unicode(get_local_var_value("LANG"));
2045
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002046 G.flag_SIGINT = 0;
2047 /* buglet: SIGINT will not make new prompt to appear _at once_,
2048 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002049 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 +00002050 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002051 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002052 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002053 i->eof_flag = (r < 0);
2054 if (i->eof_flag) { /* EOF/error detected */
2055 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2056 G.user_input_buf[1] = '\0';
2057 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02002058# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002059 do {
2060 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002061 if (i->last_char == '\0' || i->last_char == '\n') {
2062 /* Why check_and_run_traps here? Try this interactively:
2063 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2064 * $ <[enter], repeatedly...>
2065 * Without check_and_run_traps, handler never runs.
2066 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002067 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002068 fputs(prompt_str, stdout);
2069 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002070 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002071 G.user_input_buf[0] = r = fgetc(i->file);
2072 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002073 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002074 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002075# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002076 i->p = G.user_input_buf;
2077}
2078
2079#endif /* INTERACTIVE */
2080
2081/* This is the magic location that prints prompts
2082 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002083static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002084{
2085 int ch;
2086
2087 /* If there is data waiting, eat it up */
2088 if (i->p && *i->p) {
2089#if ENABLE_HUSH_INTERACTIVE
2090 take_cached:
2091#endif
2092 ch = *i->p++;
2093 if (i->eof_flag && !*i->p)
2094 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002095 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002096 } else {
2097 /* need to double check i->file because we might be doing something
2098 * more complicated by now, like sourcing or substituting. */
2099#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002100 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002101 do {
2102 get_user_input(i);
2103 } while (!*i->p); /* need non-empty line */
2104 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002105 goto take_cached;
2106 }
2107#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00002108 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002109 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002110 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002111 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002112 return ch;
2113}
2114
Denis Vlasenko913a2012009-04-05 22:17:04 +00002115/* All callers guarantee this routine will never
2116 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002117 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002118static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002119{
2120 int ch;
2121 if (i->p && *i->p) {
2122 if (i->eof_flag && !i->p[1])
2123 return EOF;
2124 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002125 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002126 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002127 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002128 i->eof_flag = (ch == EOF);
2129 i->peek_buf[0] = ch;
2130 i->peek_buf[1] = '\0';
2131 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002132 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002133 return ch;
2134}
2135
2136static void setup_file_in_str(struct in_str *i, FILE *f)
2137{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002138 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002139 i->peek = file_peek;
2140 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002141 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002142 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002143 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002144}
2145
2146static void setup_string_in_str(struct in_str *i, const char *s)
2147{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002148 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002149 i->peek = static_peek;
2150 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002151 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002152 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002153 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002154}
2155
2156
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002157/*
2158 * o_string support
2159 */
2160#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002161
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002162static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002163{
2164 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002165 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002166 if (o->data)
2167 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002168}
2169
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002170static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002171{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002172 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002173 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002174}
2175
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002176static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2177{
2178 free(o->data);
2179}
2180
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002181static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002182{
2183 if (o->length + len > o->maxlen) {
2184 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2185 o->data = xrealloc(o->data, 1 + o->maxlen);
2186 }
2187}
2188
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002189static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002190{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002191 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2192 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002193 o->data[o->length] = ch;
2194 o->length++;
2195 o->data[o->length] = '\0';
2196}
2197
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002198static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002199{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002200 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002201 memcpy(&o->data[o->length], str, len);
2202 o->length += len;
2203 o->data[o->length] = '\0';
2204}
2205
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002206static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002207{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002208 o_addblock(o, str, strlen(str));
2209}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002210
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002211#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002212static void nommu_addchr(o_string *o, int ch)
2213{
2214 if (o)
2215 o_addchr(o, ch);
2216}
2217#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002218# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002219#endif
2220
2221static void o_addstr_with_NUL(o_string *o, const char *str)
2222{
2223 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002224}
2225
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002226/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002227 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002228 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2229 * Apparently, on unquoted $v bash still does globbing
2230 * ("v='*.txt'; echo $v" prints all .txt files),
2231 * but NOT brace expansion! Thus, there should be TWO independent
2232 * quoting mechanisms on $v expansion side: one protects
2233 * $v from brace expansion, and other additionally protects "$v" against globbing.
2234 * We have only second one.
2235 */
2236
Denys Vlasenko9e800222010-10-03 14:28:04 +02002237#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002238# define MAYBE_BRACES "{}"
2239#else
2240# define MAYBE_BRACES ""
2241#endif
2242
Eric Andersen25f27032001-04-26 23:22:31 +00002243/* My analysis of quoting semantics tells me that state information
2244 * is associated with a destination, not a source.
2245 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002246static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002247{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002248 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002249 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002250 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002251 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002252 o_grow_by(o, sz);
2253 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002254 o->data[o->length] = '\\';
2255 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002256 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002257 o->data[o->length] = ch;
2258 o->length++;
2259 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002260}
2261
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002262static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002263{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002264 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002265 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2266 && strchr("*?[\\" MAYBE_BRACES, ch)
2267 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002268 sz++;
2269 o->data[o->length] = '\\';
2270 o->length++;
2271 }
2272 o_grow_by(o, sz);
2273 o->data[o->length] = ch;
2274 o->length++;
2275 o->data[o->length] = '\0';
2276}
2277
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002278static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002279{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002280 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002281 char ch;
2282 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002283 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002284 if (ordinary_cnt > len) /* paranoia */
2285 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002286 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002287 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002288 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002289 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002290 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002291
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002292 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002293 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002294 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002295 sz++;
2296 o->data[o->length] = '\\';
2297 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002298 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002299 o_grow_by(o, sz);
2300 o->data[o->length] = ch;
2301 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002302 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002303 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002304}
2305
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002306static void o_addQblock(o_string *o, const char *str, int len)
2307{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002308 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002309 o_addblock(o, str, len);
2310 return;
2311 }
2312 o_addqblock(o, str, len);
2313}
2314
Denys Vlasenko38292b62010-09-05 14:49:40 +02002315static void o_addQstr(o_string *o, const char *str)
2316{
2317 o_addQblock(o, str, strlen(str));
2318}
2319
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002320/* A special kind of o_string for $VAR and `cmd` expansion.
2321 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002322 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002323 * list[i] contains an INDEX (int!) into this string data.
2324 * It means that if list[] needs to grow, data needs to be moved higher up
2325 * but list[i]'s need not be modified.
2326 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002327 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002328 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2329 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002330#if DEBUG_EXPAND || DEBUG_GLOB
2331static void debug_print_list(const char *prefix, o_string *o, int n)
2332{
2333 char **list = (char**)o->data;
2334 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2335 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002336
2337 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002338 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 +02002339 prefix, list, n, string_start, o->length, o->maxlen,
2340 !!(o->o_expflags & EXP_FLAG_GLOB),
2341 o->has_quoted_part,
2342 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002343 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002344 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002345 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2346 o->data + (int)(uintptr_t)list[i] + string_start,
2347 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002348 i++;
2349 }
2350 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002351 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002352 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002353 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002354 }
2355}
2356#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002357# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002358#endif
2359
2360/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2361 * in list[n] so that it points past last stored byte so far.
2362 * It returns n+1. */
2363static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002364{
2365 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002366 int string_start;
2367 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002368
2369 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002370 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2371 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002372 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002373 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002374 /* list[n] points to string_start, make space for 16 more pointers */
2375 o->maxlen += 0x10 * sizeof(list[0]);
2376 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002377 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002378 memmove(list + n + 0x10, list + n, string_len);
2379 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002380 } else {
2381 debug_printf_list("list[%d]=%d string_start=%d\n",
2382 n, string_len, string_start);
2383 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002384 } else {
2385 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002386 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2387 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002388 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2389 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002390 o->has_empty_slot = 0;
2391 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002392 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002393 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002394 return n + 1;
2395}
2396
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002397/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002398static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002399{
2400 char **list = (char**)o->data;
2401 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2402
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002403 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002404}
2405
Denys Vlasenko9e800222010-10-03 14:28:04 +02002406#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002407/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2408 * first, it processes even {a} (no commas), second,
2409 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002410 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002411 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002412
2413/* Helper */
2414static int glob_needed(const char *s)
2415{
2416 while (*s) {
2417 if (*s == '\\') {
2418 if (!s[1])
2419 return 0;
2420 s += 2;
2421 continue;
2422 }
2423 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2424 return 1;
2425 s++;
2426 }
2427 return 0;
2428}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002429/* Return pointer to next closing brace or to comma */
2430static const char *next_brace_sub(const char *cp)
2431{
2432 unsigned depth = 0;
2433 cp++;
2434 while (*cp != '\0') {
2435 if (*cp == '\\') {
2436 if (*++cp == '\0')
2437 break;
2438 cp++;
2439 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002440 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002441 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002442 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002443 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002444 depth++;
2445 }
2446
2447 return *cp != '\0' ? cp : NULL;
2448}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002449/* Recursive brace globber. Note: may garble pattern[]. */
2450static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002451{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002452 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002453 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002454 const char *next;
2455 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002456 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002457 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002458
2459 debug_printf_glob("glob_brace('%s')\n", pattern);
2460
2461 begin = pattern;
2462 while (1) {
2463 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002464 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002465 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002466 /* Find the first sub-pattern and at the same time
2467 * find the rest after the closing brace */
2468 next = next_brace_sub(begin);
2469 if (next == NULL) {
2470 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002471 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002472 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002473 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002474 /* "{abc}" with no commas - illegal
2475 * brace expr, disregard and skip it */
2476 begin = next + 1;
2477 continue;
2478 }
2479 break;
2480 }
2481 if (*begin == '\\' && begin[1] != '\0')
2482 begin++;
2483 begin++;
2484 }
2485 debug_printf_glob("begin:%s\n", begin);
2486 debug_printf_glob("next:%s\n", next);
2487
2488 /* Now find the end of the whole brace expression */
2489 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002490 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002491 rest = next_brace_sub(rest);
2492 if (rest == NULL) {
2493 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002494 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002495 }
2496 debug_printf_glob("rest:%s\n", rest);
2497 }
2498 rest_len = strlen(++rest) + 1;
2499
2500 /* We are sure the brace expression is well-formed */
2501
2502 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002503 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002504
2505 /* We have a brace expression. BEGIN points to the opening {,
2506 * NEXT points past the terminator of the first element, and REST
2507 * points past the final }. We will accumulate result names from
2508 * recursive runs for each brace alternative in the buffer using
2509 * GLOB_APPEND. */
2510
2511 p = begin + 1;
2512 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002513 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002514 memcpy(
2515 mempcpy(
2516 mempcpy(new_pattern_buf,
2517 /* We know the prefix for all sub-patterns */
2518 pattern, begin - pattern),
2519 p, next - p),
2520 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002521
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002522 /* Note: glob_brace() may garble new_pattern_buf[].
2523 * That's why we re-copy prefix every time (1st memcpy above).
2524 */
2525 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002526 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002527 /* We saw the last entry */
2528 break;
2529 }
2530 p = next + 1;
2531 next = next_brace_sub(next);
2532 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002533 free(new_pattern_buf);
2534 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002535
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002536 simple_glob:
2537 {
2538 int gr;
2539 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002540
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002541 memset(&globdata, 0, sizeof(globdata));
2542 gr = glob(pattern, 0, NULL, &globdata);
2543 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2544 if (gr != 0) {
2545 if (gr == GLOB_NOMATCH) {
2546 globfree(&globdata);
2547 /* NB: garbles parameter */
2548 unbackslash(pattern);
2549 o_addstr_with_NUL(o, pattern);
2550 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2551 return o_save_ptr_helper(o, n);
2552 }
2553 if (gr == GLOB_NOSPACE)
2554 bb_error_msg_and_die(bb_msg_memory_exhausted);
2555 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2556 * but we didn't specify it. Paranoia again. */
2557 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2558 }
2559 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2560 char **argv = globdata.gl_pathv;
2561 while (1) {
2562 o_addstr_with_NUL(o, *argv);
2563 n = o_save_ptr_helper(o, n);
2564 argv++;
2565 if (!*argv)
2566 break;
2567 }
2568 }
2569 globfree(&globdata);
2570 }
2571 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002572}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002573/* Performs globbing on last list[],
2574 * saving each result as a new list[].
2575 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002576static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002577{
2578 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002579
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002580 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002581 if (!o->data)
2582 return o_save_ptr_helper(o, n);
2583 pattern = o->data + o_get_last_ptr(o, n);
2584 debug_printf_glob("glob pattern '%s'\n", pattern);
2585 if (!glob_needed(pattern)) {
2586 /* unbackslash last string in o in place, fix length */
2587 o->length = unbackslash(pattern) - o->data;
2588 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2589 return o_save_ptr_helper(o, n);
2590 }
2591
2592 copy = xstrdup(pattern);
2593 /* "forget" pattern in o */
2594 o->length = pattern - o->data;
2595 n = glob_brace(copy, o, n);
2596 free(copy);
2597 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002598 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002599 return n;
2600}
2601
Denys Vlasenko238081f2010-10-03 14:26:26 +02002602#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002603
2604/* Helper */
2605static int glob_needed(const char *s)
2606{
2607 while (*s) {
2608 if (*s == '\\') {
2609 if (!s[1])
2610 return 0;
2611 s += 2;
2612 continue;
2613 }
2614 if (*s == '*' || *s == '[' || *s == '?')
2615 return 1;
2616 s++;
2617 }
2618 return 0;
2619}
2620/* Performs globbing on last list[],
2621 * saving each result as a new list[].
2622 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002623static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002624{
2625 glob_t globdata;
2626 int gr;
2627 char *pattern;
2628
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002629 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002630 if (!o->data)
2631 return o_save_ptr_helper(o, n);
2632 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002633 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002634 if (!glob_needed(pattern)) {
2635 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002636 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002637 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002638 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002639 return o_save_ptr_helper(o, n);
2640 }
2641
2642 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002643 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2644 * If we glob "*.\*" and don't find anything, we need
2645 * to fall back to using literal "*.*", but GLOB_NOCHECK
2646 * will return "*.\*"!
2647 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002648 gr = glob(pattern, 0, NULL, &globdata);
2649 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002650 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002651 if (gr == GLOB_NOMATCH) {
2652 globfree(&globdata);
2653 goto literal;
2654 }
2655 if (gr == GLOB_NOSPACE)
2656 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002657 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2658 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002659 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002660 }
2661 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2662 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002663 /* "forget" pattern in o */
2664 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002665 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002666 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002667 n = o_save_ptr_helper(o, n);
2668 argv++;
2669 if (!*argv)
2670 break;
2671 }
2672 }
2673 globfree(&globdata);
2674 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002675 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002676 return n;
2677}
2678
Denys Vlasenko238081f2010-10-03 14:26:26 +02002679#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002680
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002681/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002682 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002683static int o_save_ptr(o_string *o, int n)
2684{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002685 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002686 /* If o->has_empty_slot, list[n] was already globbed
2687 * (if it was requested back then when it was filled)
2688 * so don't do that again! */
2689 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002690 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002691 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002692 return o_save_ptr_helper(o, n);
2693}
2694
2695/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002696static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002697{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002698 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002699 int string_start;
2700
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002701 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2702 if (DEBUG_EXPAND)
2703 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002704 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002705 list = (char**)o->data;
2706 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2707 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002708 while (n) {
2709 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002710 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002711 }
2712 return list;
2713}
2714
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002715static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002716
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002717/* Returns pi->next - next pipe in the list */
2718static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002719{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002720 struct pipe *next;
2721 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002722
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002723 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002724 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002725 struct command *command;
2726 struct redir_struct *r, *rnext;
2727
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002728 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002729 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002730 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002731 if (DEBUG_CLEAN) {
2732 int a;
2733 char **p;
2734 for (a = 0, p = command->argv; *p; a++, p++) {
2735 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2736 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002737 }
2738 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002739 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002740 }
2741 /* not "else if": on syntax error, we may have both! */
2742 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002743 debug_printf_clean(" begin group (cmd_type:%d)\n",
2744 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002745 free_pipe_list(command->group);
2746 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002747 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002748 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002749 /* else is crucial here.
2750 * If group != NULL, child_func is meaningless */
2751#if ENABLE_HUSH_FUNCTIONS
2752 else if (command->child_func) {
2753 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2754 command->child_func->parent_cmd = NULL;
2755 }
2756#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002757#if !BB_MMU
2758 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002759 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002760#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002761 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002762 debug_printf_clean(" redirect %d%s",
2763 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002764 /* guard against the case >$FOO, where foo is unset or blank */
2765 if (r->rd_filename) {
2766 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2767 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002768 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002769 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002770 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002771 rnext = r->next;
2772 free(r);
2773 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002774 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002775 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002776 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002777 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002778#if ENABLE_HUSH_JOB
2779 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002780 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002781#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002782
2783 next = pi->next;
2784 free(pi);
2785 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002786}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002787
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002788static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002789{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002790 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002791#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002792 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002793#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002794 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002795 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002796 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002797}
2798
2799
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002800/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002801
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002802#ifndef debug_print_tree
2803static void debug_print_tree(struct pipe *pi, int lvl)
2804{
2805 static const char *const PIPE[] = {
2806 [PIPE_SEQ] = "SEQ",
2807 [PIPE_AND] = "AND",
2808 [PIPE_OR ] = "OR" ,
2809 [PIPE_BG ] = "BG" ,
2810 };
2811 static const char *RES[] = {
2812 [RES_NONE ] = "NONE" ,
2813# if ENABLE_HUSH_IF
2814 [RES_IF ] = "IF" ,
2815 [RES_THEN ] = "THEN" ,
2816 [RES_ELIF ] = "ELIF" ,
2817 [RES_ELSE ] = "ELSE" ,
2818 [RES_FI ] = "FI" ,
2819# endif
2820# if ENABLE_HUSH_LOOPS
2821 [RES_FOR ] = "FOR" ,
2822 [RES_WHILE] = "WHILE",
2823 [RES_UNTIL] = "UNTIL",
2824 [RES_DO ] = "DO" ,
2825 [RES_DONE ] = "DONE" ,
2826# endif
2827# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2828 [RES_IN ] = "IN" ,
2829# endif
2830# if ENABLE_HUSH_CASE
2831 [RES_CASE ] = "CASE" ,
2832 [RES_CASE_IN ] = "CASE_IN" ,
2833 [RES_MATCH] = "MATCH",
2834 [RES_CASE_BODY] = "CASE_BODY",
2835 [RES_ESAC ] = "ESAC" ,
2836# endif
2837 [RES_XXXX ] = "XXXX" ,
2838 [RES_SNTX ] = "SNTX" ,
2839 };
2840 static const char *const CMDTYPE[] = {
2841 "{}",
2842 "()",
2843 "[noglob]",
2844# if ENABLE_HUSH_FUNCTIONS
2845 "func()",
2846# endif
2847 };
2848
2849 int pin, prn;
2850
2851 pin = 0;
2852 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002853 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002854 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2855 prn = 0;
2856 while (prn < pi->num_cmds) {
2857 struct command *command = &pi->cmds[prn];
2858 char **argv = command->argv;
2859
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002860 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002861 lvl*2, "", prn,
2862 command->assignment_cnt);
2863 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002864 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002865 CMDTYPE[command->cmd_type],
2866 argv
2867# if !BB_MMU
2868 , " group_as_string:", command->group_as_string
2869# else
2870 , "", ""
2871# endif
2872 );
2873 debug_print_tree(command->group, lvl+1);
2874 prn++;
2875 continue;
2876 }
2877 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002878 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002879 argv++;
2880 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002881 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002882 prn++;
2883 }
2884 pi = pi->next;
2885 pin++;
2886 }
2887}
2888#endif /* debug_print_tree */
2889
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002890static struct pipe *new_pipe(void)
2891{
Eric Andersen25f27032001-04-26 23:22:31 +00002892 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002893 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002894 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002895 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002896 return pi;
2897}
2898
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002899/* Command (member of a pipe) is complete, or we start a new pipe
2900 * if ctx->command is NULL.
2901 * No errors possible here.
2902 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002903static int done_command(struct parse_context *ctx)
2904{
2905 /* The command is really already in the pipe structure, so
2906 * advance the pipe counter and make a new, null command. */
2907 struct pipe *pi = ctx->pipe;
2908 struct command *command = ctx->command;
2909
2910 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002911 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002912 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002913 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002914 }
2915 pi->num_cmds++;
2916 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002917 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002918 } else {
2919 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2920 }
2921
2922 /* Only real trickiness here is that the uncommitted
2923 * command structure is not counted in pi->num_cmds. */
2924 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002925 ctx->command = command = &pi->cmds[pi->num_cmds];
2926 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002927 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002928 return pi->num_cmds; /* used only for 0/nonzero check */
2929}
2930
2931static void done_pipe(struct parse_context *ctx, pipe_style type)
2932{
2933 int not_null;
2934
2935 debug_printf_parse("done_pipe entered, followup %d\n", type);
2936 /* Close previous command */
2937 not_null = done_command(ctx);
2938 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002939#if HAS_KEYWORDS
2940 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2941 ctx->ctx_inverted = 0;
2942 ctx->pipe->res_word = ctx->ctx_res_w;
2943#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002944
2945 /* Without this check, even just <enter> on command line generates
2946 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002947 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002948 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002949#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002950 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002951#endif
2952#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002953 || ctx->ctx_res_w == RES_DONE
2954 || ctx->ctx_res_w == RES_FOR
2955 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002956#endif
2957#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002958 || ctx->ctx_res_w == RES_ESAC
2959#endif
2960 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002961 struct pipe *new_p;
2962 debug_printf_parse("done_pipe: adding new pipe: "
2963 "not_null:%d ctx->ctx_res_w:%d\n",
2964 not_null, ctx->ctx_res_w);
2965 new_p = new_pipe();
2966 ctx->pipe->next = new_p;
2967 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002968 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002969 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002970 * This is used to control execution.
2971 * RES_FOR and RES_IN are NOT sticky (needed to support
2972 * cases where variable or value happens to match a keyword):
2973 */
2974#if ENABLE_HUSH_LOOPS
2975 if (ctx->ctx_res_w == RES_FOR
2976 || ctx->ctx_res_w == RES_IN)
2977 ctx->ctx_res_w = RES_NONE;
2978#endif
2979#if ENABLE_HUSH_CASE
2980 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002981 ctx->ctx_res_w = RES_CASE_BODY;
2982 if (ctx->ctx_res_w == RES_CASE)
2983 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002984#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002985 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002986 /* Create the memory for command, roughly:
2987 * ctx->pipe->cmds = new struct command;
2988 * ctx->command = &ctx->pipe->cmds[0];
2989 */
2990 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002991 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002992 }
2993 debug_printf_parse("done_pipe return\n");
2994}
2995
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002996static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002997{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002998 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002999 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003000 /* Create the memory for command, roughly:
3001 * ctx->pipe->cmds = new struct command;
3002 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003003 */
3004 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003005}
3006
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003007/* If a reserved word is found and processed, parse context is modified
3008 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003009 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003010#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003011struct reserved_combo {
3012 char literal[6];
3013 unsigned char res;
3014 unsigned char assignment_flag;
3015 int flag;
3016};
3017enum {
3018 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003019# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003020 FLAG_IF = (1 << RES_IF ),
3021 FLAG_THEN = (1 << RES_THEN ),
3022 FLAG_ELIF = (1 << RES_ELIF ),
3023 FLAG_ELSE = (1 << RES_ELSE ),
3024 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003025# endif
3026# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003027 FLAG_FOR = (1 << RES_FOR ),
3028 FLAG_WHILE = (1 << RES_WHILE),
3029 FLAG_UNTIL = (1 << RES_UNTIL),
3030 FLAG_DO = (1 << RES_DO ),
3031 FLAG_DONE = (1 << RES_DONE ),
3032 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003033# endif
3034# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003035 FLAG_MATCH = (1 << RES_MATCH),
3036 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003037# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003038 FLAG_START = (1 << RES_XXXX ),
3039};
3040
3041static const struct reserved_combo* match_reserved_word(o_string *word)
3042{
Eric Andersen25f27032001-04-26 23:22:31 +00003043 /* Mostly a list of accepted follow-up reserved words.
3044 * FLAG_END means we are done with the sequence, and are ready
3045 * to turn the compound list into a command.
3046 * FLAG_START means the word must start a new compound list.
3047 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003048 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003049# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003050 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3051 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3052 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3053 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3054 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3055 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003056# endif
3057# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003058 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3059 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3060 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3061 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3062 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3063 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003064# endif
3065# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003066 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3067 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003068# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003069 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003070 const struct reserved_combo *r;
3071
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003072 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003073 if (strcmp(word->data, r->literal) == 0)
3074 return r;
3075 }
3076 return NULL;
3077}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003078/* Return 0: not a keyword, 1: keyword
3079 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003080static int reserved_word(o_string *word, struct parse_context *ctx)
3081{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003082# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003083 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003084 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003085 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003086# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003087 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003088
Denys Vlasenko38292b62010-09-05 14:49:40 +02003089 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003090 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003091 r = match_reserved_word(word);
3092 if (!r)
3093 return 0;
3094
3095 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003096# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003097 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3098 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003099 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003100 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003101# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003102 if (r->flag == 0) { /* '!' */
3103 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003104 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003105 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003106 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003107 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003108 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003109 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003110 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003111 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003112
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003113 old = xmalloc(sizeof(*old));
3114 debug_printf_parse("push stack %p\n", old);
3115 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003116 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003117 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003118 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003119 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003120 ctx->ctx_res_w = RES_SNTX;
3121 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003122 } else {
3123 /* "{...} fi" is ok. "{...} if" is not
3124 * Example:
3125 * if { echo foo; } then { echo bar; } fi */
3126 if (ctx->command->group)
3127 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003128 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003129
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003130 ctx->ctx_res_w = r->res;
3131 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003132 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003133 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003134
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003135 if (ctx->old_flag & FLAG_END) {
3136 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003137
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003138 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003139 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003140 old = ctx->stack;
3141 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003142 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003143# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003144 o_addstr(&old->as_string, ctx->as_string.data);
3145 o_free_unsafe(&ctx->as_string);
3146 old->command->group_as_string = xstrdup(old->as_string.data);
3147 debug_printf_parse("pop, remembering as:'%s'\n",
3148 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003149# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003150 *ctx = *old; /* physical copy */
3151 free(old);
3152 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003153 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003154}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003155#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003156
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003157/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003158 * Normal return is 0. Syntax errors return 1.
3159 * Note: on return, word is reset, but not o_free'd!
3160 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003161static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003162{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003163 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003164
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003165 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003166 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003167 debug_printf_parse("done_word return 0: true null, ignored\n");
3168 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003169 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003170
Eric Andersen25f27032001-04-26 23:22:31 +00003171 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003172 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3173 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003174 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3175 * "2.7 Redirection
3176 * ...the word that follows the redirection operator
3177 * shall be subjected to tilde expansion, parameter expansion,
3178 * command substitution, arithmetic expansion, and quote
3179 * removal. Pathname expansion shall not be performed
3180 * on the word by a non-interactive shell; an interactive
3181 * shell may perform it, but shall do so only when
3182 * the expansion would result in one word."
3183 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003184 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003185 /* Cater for >\file case:
3186 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3187 * Same with heredocs:
3188 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3189 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003190 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3191 unbackslash(ctx->pending_redirect->rd_filename);
3192 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003193 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003194 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3195 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003196 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003197 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003198 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003199 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003200#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003201# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003202 if (ctx->ctx_dsemicolon
3203 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3204 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003205 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003206 /* ctx->ctx_res_w = RES_MATCH; */
3207 ctx->ctx_dsemicolon = 0;
3208 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003209# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003210 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003211# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003212 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3213 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003214# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003215# if ENABLE_HUSH_CASE
3216 && ctx->ctx_res_w != RES_CASE
3217# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003218 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003219 int reserved = reserved_word(word, ctx);
3220 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3221 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003222 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003223 debug_printf_parse("done_word return %d\n",
3224 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003225 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003226 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003227# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003228 if (strcmp(word->data, "[[") == 0) {
3229 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3230 }
3231 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003232# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003233 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003234#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003235 if (command->group) {
3236 /* "{ echo foo; } echo bar" - bad */
3237 syntax_error_at(word->data);
3238 debug_printf_parse("done_word return 1: syntax error, "
3239 "groups and arglists don't mix\n");
3240 return 1;
3241 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003242
3243 /* If this word wasn't an assignment, next ones definitely
3244 * can't be assignments. Even if they look like ones. */
3245 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3246 && word->o_assignment != WORD_IS_KEYWORD
3247 ) {
3248 word->o_assignment = NOT_ASSIGNMENT;
3249 } else {
3250 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3251 command->assignment_cnt++;
3252 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3253 }
3254 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3255 word->o_assignment = MAYBE_ASSIGNMENT;
3256 }
3257 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3258
Denys Vlasenko38292b62010-09-05 14:49:40 +02003259 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003260 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3261 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003262 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003263 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003264 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003265 char *p = word->data;
3266 while (p[0] == SPECIAL_VAR_SYMBOL
3267 && (p[1] & 0x7f) == '@'
3268 && p[2] == SPECIAL_VAR_SYMBOL
3269 ) {
3270 p += 3;
3271 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003272 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003273 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003274 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003275 }
Eric Andersen25f27032001-04-26 23:22:31 +00003276
Denis Vlasenko06810332007-05-21 23:30:54 +00003277#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003278 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003279 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003280 || !is_well_formed_var_name(command->argv[0], '\0')
3281 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003282 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003283 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003284 return 1;
3285 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003286 /* Force FOR to have just one word (variable name) */
3287 /* NB: basically, this makes hush see "for v in ..."
3288 * syntax as if it is "for v; in ...". FOR and IN become
3289 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003290 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003291 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003292#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003293#if ENABLE_HUSH_CASE
3294 /* Force CASE to have just one word */
3295 if (ctx->ctx_res_w == RES_CASE) {
3296 done_pipe(ctx, PIPE_SEQ);
3297 }
3298#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003299
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003300 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003301
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003302 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003303 return 0;
3304}
3305
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003306
3307/* Peek ahead in the input to find out if we have a "&n" construct,
3308 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003309 * Return:
3310 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3311 * REDIRFD_SYNTAX_ERR if syntax error,
3312 * REDIRFD_TO_FILE if no & was seen,
3313 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003314 */
3315#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003316#define parse_redir_right_fd(as_string, input) \
3317 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003318#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003319static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003320{
3321 int ch, d, ok;
3322
3323 ch = i_peek(input);
3324 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003325 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003326
3327 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003328 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003329 ch = i_peek(input);
3330 if (ch == '-') {
3331 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003332 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003333 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003334 }
3335 d = 0;
3336 ok = 0;
3337 while (ch != EOF && isdigit(ch)) {
3338 d = d*10 + (ch-'0');
3339 ok = 1;
3340 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003341 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003342 ch = i_peek(input);
3343 }
3344 if (ok) return d;
3345
3346//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3347
3348 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003349 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003350}
3351
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003352/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003353 */
3354static int parse_redirect(struct parse_context *ctx,
3355 int fd,
3356 redir_type style,
3357 struct in_str *input)
3358{
3359 struct command *command = ctx->command;
3360 struct redir_struct *redir;
3361 struct redir_struct **redirp;
3362 int dup_num;
3363
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003364 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003365 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003366 /* Check for a '>&1' type redirect */
3367 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3368 if (dup_num == REDIRFD_SYNTAX_ERR)
3369 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003370 } else {
3371 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003372 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003373 if (dup_num) { /* <<-... */
3374 ch = i_getch(input);
3375 nommu_addchr(&ctx->as_string, ch);
3376 ch = i_peek(input);
3377 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003378 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003379
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003380 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003381 int ch = i_peek(input);
3382 if (ch == '|') {
3383 /* >|FILE redirect ("clobbering" >).
3384 * Since we do not support "set -o noclobber" yet,
3385 * >| and > are the same for now. Just eat |.
3386 */
3387 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003388 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003389 }
3390 }
3391
3392 /* Create a new redir_struct and append it to the linked list */
3393 redirp = &command->redirects;
3394 while ((redir = *redirp) != NULL) {
3395 redirp = &(redir->next);
3396 }
3397 *redirp = redir = xzalloc(sizeof(*redir));
3398 /* redir->next = NULL; */
3399 /* redir->rd_filename = NULL; */
3400 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003401 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003402
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003403 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3404 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003405
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003406 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003407 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003408 /* Erik had a check here that the file descriptor in question
3409 * is legit; I postpone that to "run time"
3410 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003411 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3412 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003413 } else {
3414 /* Set ctx->pending_redirect, so we know what to do at the
3415 * end of the next parsed word. */
3416 ctx->pending_redirect = redir;
3417 }
3418 return 0;
3419}
3420
Eric Andersen25f27032001-04-26 23:22:31 +00003421/* If a redirect is immediately preceded by a number, that number is
3422 * supposed to tell which file descriptor to redirect. This routine
3423 * looks for such preceding numbers. In an ideal world this routine
3424 * needs to handle all the following classes of redirects...
3425 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3426 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3427 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3428 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003429 *
3430 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3431 * "2.7 Redirection
3432 * ... If n is quoted, the number shall not be recognized as part of
3433 * the redirection expression. For example:
3434 * echo \2>a
3435 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003436 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003437 *
3438 * A -1 return means no valid number was found,
3439 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003440 */
3441static int redirect_opt_num(o_string *o)
3442{
3443 int num;
3444
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003445 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003446 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003447 num = bb_strtou(o->data, NULL, 10);
3448 if (errno || num < 0)
3449 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003450 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003451 return num;
3452}
3453
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003454#if BB_MMU
3455#define fetch_till_str(as_string, input, word, skip_tabs) \
3456 fetch_till_str(input, word, skip_tabs)
3457#endif
3458static char *fetch_till_str(o_string *as_string,
3459 struct in_str *input,
3460 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003461 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003462{
3463 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003464 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003465 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003466 int ch;
3467
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003468 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003469
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003470 while (1) {
3471 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003472 if (ch != EOF)
3473 nommu_addchr(as_string, ch);
3474 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003475 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3476 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003477 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3478 heredoc.data[past_EOL] = '\0';
3479 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3480 return heredoc.data;
3481 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003482 while (ch == '\n') {
3483 o_addchr(&heredoc, ch);
3484 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003485 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003486 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003487 do {
3488 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003489 if (ch != EOF)
3490 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003491 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003492 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003493 }
3494 if (ch == EOF) {
3495 o_free_unsafe(&heredoc);
3496 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003497 }
3498 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003499 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003500 if (prev == '\\' && ch == '\\')
3501 /* Correctly handle foo\\<eol> (not a line cont.) */
3502 prev = 0; /* not \ */
3503 else
3504 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003505 }
3506}
3507
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003508/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3509 * and load them all. There should be exactly heredoc_cnt of them.
3510 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003511static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3512{
3513 struct pipe *pi = ctx->list_head;
3514
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003515 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003516 int i;
3517 struct command *cmd = pi->cmds;
3518
3519 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3520 pi->num_cmds,
3521 cmd->argv ? cmd->argv[0] : "NONE");
3522 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003523 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003524
3525 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3526 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003527 while (redir) {
3528 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003529 char *p;
3530
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003531 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003532 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003533 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003534 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003535 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003536 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003537 return 1;
3538 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003539 free(redir->rd_filename);
3540 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003541 heredoc_cnt--;
3542 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003543 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003544 }
3545 cmd++;
3546 }
3547 pi = pi->next;
3548 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003549#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003550 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003551 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003552 bb_error_msg_and_die("heredoc BUG 2");
3553#endif
3554 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003555}
3556
3557
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003558static int run_list(struct pipe *pi);
3559#if BB_MMU
3560#define parse_stream(pstring, input, end_trigger) \
3561 parse_stream(input, end_trigger)
3562#endif
3563static struct pipe *parse_stream(char **pstring,
3564 struct in_str *input,
3565 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003566
Eric Andersen25f27032001-04-26 23:22:31 +00003567
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003568#if !ENABLE_HUSH_FUNCTIONS
3569#define parse_group(dest, ctx, input, ch) \
3570 parse_group(ctx, input, ch)
3571#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003572static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003573 struct in_str *input, int ch)
3574{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003575 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003576 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003577 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003578 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003579 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003580 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003581
3582 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003583#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003584 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003585 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003586 if (done_word(dest, ctx))
3587 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003588 if (!command->argv)
3589 goto skip; /* (... */
3590 if (command->argv[1]) { /* word word ... (... */
3591 syntax_error_unexpected_ch('(');
3592 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003593 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003594 /* it is "word(..." or "word (..." */
3595 do
3596 ch = i_getch(input);
3597 while (ch == ' ' || ch == '\t');
3598 if (ch != ')') {
3599 syntax_error_unexpected_ch(ch);
3600 return 1;
3601 }
3602 nommu_addchr(&ctx->as_string, ch);
3603 do
3604 ch = i_getch(input);
3605 while (ch == ' ' || ch == '\t' || ch == '\n');
3606 if (ch != '{') {
3607 syntax_error_unexpected_ch(ch);
3608 return 1;
3609 }
3610 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003611 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003612 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003613 }
3614#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003615
3616#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003617 if (command->argv /* word [word]{... */
3618 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003619 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003620 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003621 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003622 debug_printf_parse("parse_group return 1: "
3623 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003624 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003625 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003626#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003627
3628#if ENABLE_HUSH_FUNCTIONS
3629 skip:
3630#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003631 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003632 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003633 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003634 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003635 } else {
3636 /* bash does not allow "{echo...", requires whitespace */
3637 ch = i_getch(input);
3638 if (ch != ' ' && ch != '\t' && ch != '\n') {
3639 syntax_error_unexpected_ch(ch);
3640 return 1;
3641 }
3642 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003643 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003644
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003645 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003646#if BB_MMU
3647# define as_string NULL
3648#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003649 char *as_string = NULL;
3650#endif
3651 pipe_list = parse_stream(&as_string, input, endch);
3652#if !BB_MMU
3653 if (as_string)
3654 o_addstr(&ctx->as_string, as_string);
3655#endif
3656 /* empty ()/{} or parse error? */
3657 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003658 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003659 if (!BB_MMU)
3660 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003661 debug_printf_parse("parse_group return 1: "
3662 "parse_stream returned %p\n", pipe_list);
3663 return 1;
3664 }
3665 command->group = pipe_list;
3666#if !BB_MMU
3667 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3668 command->group_as_string = as_string;
3669 debug_printf_parse("end of group, remembering as:'%s'\n",
3670 command->group_as_string);
3671#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003672#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003673 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003674 debug_printf_parse("parse_group return 0\n");
3675 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003676 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003677}
3678
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003679#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003680/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003681static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003682/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003683static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003684{
3685 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003686 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003687 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003688 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003689 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003690 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003691 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003692 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003693 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003694 }
3695}
3696/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003697static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003698{
3699 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003700 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003701 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003702 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003703 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003704 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003705 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003706 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003707 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003708 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003709 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003710 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003711 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003712 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003713 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3714 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003715 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003716 continue;
3717 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003718 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003719 }
3720}
3721/* Process `cmd` - copy contents until "`" is seen. Complicated by
3722 * \` quoting.
3723 * "Within the backquoted style of command substitution, backslash
3724 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3725 * The search for the matching backquote shall be satisfied by the first
3726 * backquote found without a preceding backslash; during this search,
3727 * if a non-escaped backquote is encountered within a shell comment,
3728 * a here-document, an embedded command substitution of the $(command)
3729 * form, or a quoted string, undefined results occur. A single-quoted
3730 * or double-quoted string that begins, but does not end, within the
3731 * "`...`" sequence produces undefined results."
3732 * Example Output
3733 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3734 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003735static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003736{
3737 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003738 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003739 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003740 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003741 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003742 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3743 ch = i_getch(input);
3744 if (ch != '`'
3745 && ch != '$'
3746 && ch != '\\'
3747 && (!in_dquote || ch != '"')
3748 ) {
3749 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003750 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003751 }
3752 if (ch == EOF) {
3753 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003754 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003755 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003756 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003757 }
3758}
3759/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3760 * quoting and nested ()s.
3761 * "With the $(command) style of command substitution, all characters
3762 * following the open parenthesis to the matching closing parenthesis
3763 * constitute the command. Any valid shell script can be used for command,
3764 * except a script consisting solely of redirections which produces
3765 * unspecified results."
3766 * Example Output
3767 * echo $(echo '(TEST)' BEST) (TEST) BEST
3768 * echo $(echo 'TEST)' BEST) TEST) BEST
3769 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003770 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003771 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003772 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003773 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3774 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003775 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003776#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003777static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003778{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003779 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003780 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003781# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003782 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003783# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003784 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3785
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003786 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003787 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003788 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003789 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003790 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003791 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003792 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003793 if (!dbl)
3794 break;
3795 /* we look for closing )) of $((EXPR)) */
3796 if (i_peek(input) == end_ch) {
3797 i_getch(input); /* eat second ')' */
3798 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003799 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003800 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003801 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003802 if (ch == '(' || ch == '{') {
3803 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003804 if (!add_till_closing_bracket(dest, input, ch))
3805 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003806 o_addchr(dest, ch);
3807 continue;
3808 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003809 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003810 if (!add_till_single_quote(dest, input))
3811 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003812 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003813 continue;
3814 }
3815 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003816 if (!add_till_double_quote(dest, input))
3817 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003818 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003819 continue;
3820 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003821 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003822 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3823 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003824 o_addchr(dest, ch);
3825 continue;
3826 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003827 if (ch == '\\') {
3828 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003829 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003830 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003831 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003832 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003833 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003834 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003835 continue;
3836 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003837 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003838 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003839}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003840#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003841
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003842/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003843#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003844#define parse_dollar(as_string, dest, input, quote_mask) \
3845 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003846#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003847#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003848static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003849 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003850 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003851{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003852 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003853
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003854 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003855 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003856 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003857 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003858 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003859 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003860 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003861 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003862 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003863 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003864 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003865 if (!isalnum(ch) && ch != '_')
3866 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003867 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003868 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003869 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003870 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003871 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003872 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003873 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003874 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003875 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003876 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003877 o_addchr(dest, ch | quote_mask);
3878 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003879 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003880 case '$': /* pid */
3881 case '!': /* last bg pid */
3882 case '?': /* last exit code */
3883 case '#': /* number of args */
3884 case '*': /* args */
3885 case '@': /* args */
3886 goto make_one_char_var;
3887 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003888 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3889
Denys Vlasenko74369502010-05-21 19:52:01 +02003890 ch = i_getch(input); /* eat '{' */
3891 nommu_addchr(as_string, ch);
3892
3893 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003894 /* It should be ${?}, or ${#var},
3895 * or even ${?+subst} - operator acting on a special variable,
3896 * or the beginning of variable name.
3897 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003898 if (ch == EOF
3899 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3900 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003901 bad_dollar_syntax:
3902 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003903 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3904 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02003905 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003906 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003907 ch |= quote_mask;
3908
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003909 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003910 * However, this regresses some of our testsuite cases
3911 * which check invalid constructs like ${%}.
3912 * Oh well... let's check that the var name part is fine... */
3913
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003914 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003915 unsigned pos;
3916
Denys Vlasenko74369502010-05-21 19:52:01 +02003917 o_addchr(dest, ch);
3918 debug_printf_parse(": '%c'\n", ch);
3919
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003920 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003921 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003922 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003923 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003924
Denys Vlasenko74369502010-05-21 19:52:01 +02003925 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003926 unsigned end_ch;
3927 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003928 /* handle parameter expansions
3929 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3930 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003931 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003932 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003933
3934 /* Eat everything until closing '}' (or ':') */
3935 end_ch = '}';
3936 if (ENABLE_HUSH_BASH_COMPAT
3937 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003938 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003939 ) {
3940 /* It's ${var:N[:M]} thing */
3941 end_ch = '}' * 0x100 + ':';
3942 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003943 if (ENABLE_HUSH_BASH_COMPAT
3944 && ch == '/'
3945 ) {
3946 /* It's ${var/[/]pattern[/repl]} thing */
3947 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3948 i_getch(input);
3949 nommu_addchr(as_string, '/');
3950 ch = '\\';
3951 }
3952 end_ch = '}' * 0x100 + '/';
3953 }
3954 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003955 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003956 if (!BB_MMU)
3957 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003958#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003959 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003960 if (last_ch == 0) /* error? */
3961 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003962#else
3963#error Simple code to only allow ${var} is not implemented
3964#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003965 if (as_string) {
3966 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003967 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003968 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003969
3970 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3971 /* close the first block: */
3972 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003973 /* while parsing N from ${var:N[:M]}
3974 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003975 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003976 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003977 end_ch = '}';
3978 goto again;
3979 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003980 /* got '}' */
3981 if (end_ch == '}' * 0x100 + ':') {
3982 /* it's ${var:N} - emulate :999999999 */
3983 o_addstr(dest, "999999999");
3984 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003985 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003986 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003987 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003988 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003989 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3990 break;
3991 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003992#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003993 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003994 unsigned pos;
3995
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003996 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003997 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003998# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003999 if (i_peek(input) == '(') {
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 Vlasenkoa24c8ca2009-04-04 15:24:40 +00004002 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4003 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004004 if (!BB_MMU)
4005 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004006 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4007 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004008 if (as_string) {
4009 o_addstr(as_string, dest->data + pos);
4010 o_addchr(as_string, ')');
4011 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004012 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004013 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004014 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004015 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004016# endif
4017# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004018 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4019 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004020 if (!BB_MMU)
4021 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004022 if (!add_till_closing_bracket(dest, input, ')'))
4023 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004024 if (as_string) {
4025 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004026 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004027 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004028 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004029# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004030 break;
4031 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004032#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004033 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004034 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004035 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004036 ch = i_peek(input);
4037 if (isalnum(ch)) { /* it's $_name or $_123 */
4038 ch = '_';
4039 goto make_var;
4040 }
4041 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004042 /* TODO: $_ and $-: */
4043 /* $_ Shell or shell script name; or last argument of last command
4044 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4045 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004046 /* $- Option flags set by set builtin or shell options (-i etc) */
4047 default:
4048 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004049 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004050 debug_printf_parse("parse_dollar return 1 (ok)\n");
4051 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004052#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004053}
4054
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004055#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004056# if ENABLE_HUSH_BASH_COMPAT
4057#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4058 encode_string(dest, input, dquote_end, process_bkslash)
4059# else
4060/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4061#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4062 encode_string(dest, input, dquote_end)
4063# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004064#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004065
4066#else /* !MMU */
4067
4068# if ENABLE_HUSH_BASH_COMPAT
4069/* all parameters are needed, no macro tricks */
4070# else
4071#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4072 encode_string(as_string, dest, input, dquote_end)
4073# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004074#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004075static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004076 o_string *dest,
4077 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004078 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004079 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004080{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004081#if !ENABLE_HUSH_BASH_COMPAT
4082 const int process_bkslash = 1;
4083#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004084 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004085 int next;
4086
4087 again:
4088 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004089 if (ch != EOF)
4090 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004091 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004092 debug_printf_parse("encode_string return 1 (ok)\n");
4093 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004094 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004095 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004096 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004097 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004098 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004099 }
4100 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004101 if (ch != '\n') {
4102 next = i_peek(input);
4103 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004104 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004105 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004106 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004107 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004108 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004109 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004110 }
4111 /* bash:
4112 * "The backslash retains its special meaning [in "..."]
4113 * only when followed by one of the following characters:
4114 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004115 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004116 * NB: in (unquoted) heredoc, above does not apply to ",
4117 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004118 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004119 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004120 ch = i_getch(input); /* eat next */
4121 if (ch == '\n')
4122 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004123 } /* else: ch remains == '\\', and we double it below: */
4124 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004125 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004126 goto again;
4127 }
4128 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004129 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4130 debug_printf_parse("encode_string return 0: "
4131 "parse_dollar returned 0 (error)\n");
4132 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004133 }
4134 goto again;
4135 }
4136#if ENABLE_HUSH_TICK
4137 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004138 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004139 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4140 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004141 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4142 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004143 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4144 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004145 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004146 }
4147#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004148 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004149 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004150#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004151}
4152
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004153/*
4154 * Scan input until EOF or end_trigger char.
4155 * Return a list of pipes to execute, or NULL on EOF
4156 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004157 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004158 * reset parsing machinery and start parsing anew,
4159 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004160 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004161static struct pipe *parse_stream(char **pstring,
4162 struct in_str *input,
4163 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004164{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004165 struct parse_context ctx;
4166 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004167 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004168
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004169 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004170 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004171 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004172 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004173 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004174 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004175
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004176 /* If very first arg is "" or '', dest.data may end up NULL.
4177 * Preventing this: */
4178 o_addchr(&dest, '\0');
4179 dest.length = 0;
4180
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004181 /* We used to separate words on $IFS here. This was wrong.
4182 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004183 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004184 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004185
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004186 if (MAYBE_ASSIGNMENT != 0)
4187 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004188 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004189 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004190 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004191 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004192 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004193 int ch;
4194 int next;
4195 int redir_fd;
4196 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004197
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004198 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004199 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004200 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004201 if (ch == EOF) {
4202 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004203
4204 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004205 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004206 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004207 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004208 /* end_trigger == '}' case errors out earlier,
4209 * checking only ')' */
4210 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004211 syntax_error_unterm_ch('(');
4212 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004213 }
4214
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004215 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004216 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004217 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004218 o_free(&dest);
4219 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004220 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004221 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004222 /* (this makes bare "&" cmd a no-op.
4223 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004224 if (pi->num_cmds == 0
4225 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4226 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004227 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004228 pi = NULL;
4229 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004230#if !BB_MMU
4231 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4232 if (pstring)
4233 *pstring = ctx.as_string.data;
4234 else
4235 o_free_unsafe(&ctx.as_string);
4236#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004237 debug_leave();
4238 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004239 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004240 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004241 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004242
4243 next = '\0';
4244 if (ch != '\n')
4245 next = i_peek(input);
4246
4247 is_special = "{}<>;&|()#'" /* special outside of "str" */
4248 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4249 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004250 if (ctx.command->argv /* word [word]{... - non-special */
4251 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004252 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004253 || (next != ';' /* }; - special */
4254 && next != ')' /* }) - special */
4255 && next != '&' /* }& and }&& ... - special */
4256 && next != '|' /* }|| ... - special */
4257 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004258 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004259 ) {
4260 /* They are not special, skip "{}" */
4261 is_special += 2;
4262 }
4263 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004264 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004265
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004266 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004267 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004268 o_addQchr(&dest, ch);
4269 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4270 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004271 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004272 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004273 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004274 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004275 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004276 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004277 continue;
4278 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004279
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004280 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004281 if (done_word(&dest, &ctx)) {
4282 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004283 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004284 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004285 /* Is this a case when newline is simply ignored?
4286 * Some examples:
4287 * "cmd | <newline> cmd ..."
4288 * "case ... in <newline> word) ..."
4289 */
4290 if (IS_NULL_CMD(ctx.command)
4291 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004292 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004293 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004294 * Without check #1, interactive shell
4295 * ignores even bare <newline>,
4296 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004297 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004298 * ps2> _ <=== wrong, should be ps1
4299 * Without check #2, "cmd & <newline>"
4300 * is similarly mistreated.
4301 * (BTW, this makes "cmd & cmd"
4302 * and "cmd && cmd" non-orthogonal.
4303 * Really, ask yourself, why
4304 * "cmd && <newline>" doesn't start
4305 * cmd but waits for more input?
4306 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004307 */
4308 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004309 if (pi->num_cmds != 0 /* check #1 */
4310 && pi->followup != PIPE_BG /* check #2 */
4311 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004312 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004313 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004314 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004315 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004316 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004317 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4318 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004319 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004320 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004321 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004322 heredoc_cnt = 0;
4323 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004324 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004325 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004326 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004327 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004328 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004329 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004330 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004331
4332 /* "cmd}" or "cmd }..." without semicolon or &:
4333 * } is an ordinary char in this case, even inside { cmd; }
4334 * Pathological example: { ""}; } should exec "}" cmd
4335 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004336 if (ch == '}') {
4337 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4338 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004339 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004340 ) {
4341 goto ordinary_char;
4342 }
4343 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4344 goto skip_end_trigger;
4345 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004346 }
4347
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004348 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004349 && (ch != ';' || heredoc_cnt == 0)
4350#if ENABLE_HUSH_CASE
4351 && (ch != ')'
4352 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004353 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004354 )
4355#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004356 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004357 if (heredoc_cnt) {
4358 /* This is technically valid:
4359 * { cat <<HERE; }; echo Ok
4360 * heredoc
4361 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004362 * HERE
4363 * but we don't support this.
4364 * We require heredoc to be in enclosing {}/(),
4365 * if any.
4366 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004367 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004368 goto parse_error;
4369 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004370 if (done_word(&dest, &ctx)) {
4371 goto parse_error;
4372 }
4373 done_pipe(&ctx, PIPE_SEQ);
4374 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004375 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004376 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004377 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004378 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004379 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004380 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004381#if !BB_MMU
4382 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4383 if (pstring)
4384 *pstring = ctx.as_string.data;
4385 else
4386 o_free_unsafe(&ctx.as_string);
4387#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004388 debug_leave();
4389 debug_printf_parse("parse_stream return %p: "
4390 "end_trigger char found\n",
4391 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004392 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004393 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004394 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004395 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004396 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004397 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004398
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004399 /* Catch <, > before deciding whether this word is
4400 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4401 switch (ch) {
4402 case '>':
4403 redir_fd = redirect_opt_num(&dest);
4404 if (done_word(&dest, &ctx)) {
4405 goto parse_error;
4406 }
4407 redir_style = REDIRECT_OVERWRITE;
4408 if (next == '>') {
4409 redir_style = REDIRECT_APPEND;
4410 ch = i_getch(input);
4411 nommu_addchr(&ctx.as_string, ch);
4412 }
4413#if 0
4414 else if (next == '(') {
4415 syntax_error(">(process) not supported");
4416 goto parse_error;
4417 }
4418#endif
4419 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4420 goto parse_error;
4421 continue; /* back to top of while (1) */
4422 case '<':
4423 redir_fd = redirect_opt_num(&dest);
4424 if (done_word(&dest, &ctx)) {
4425 goto parse_error;
4426 }
4427 redir_style = REDIRECT_INPUT;
4428 if (next == '<') {
4429 redir_style = REDIRECT_HEREDOC;
4430 heredoc_cnt++;
4431 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4432 ch = i_getch(input);
4433 nommu_addchr(&ctx.as_string, ch);
4434 } else if (next == '>') {
4435 redir_style = REDIRECT_IO;
4436 ch = i_getch(input);
4437 nommu_addchr(&ctx.as_string, ch);
4438 }
4439#if 0
4440 else if (next == '(') {
4441 syntax_error("<(process) not supported");
4442 goto parse_error;
4443 }
4444#endif
4445 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4446 goto parse_error;
4447 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004448 case '#':
4449 if (dest.length == 0 && !dest.has_quoted_part) {
4450 /* skip "#comment" */
4451 while (1) {
4452 ch = i_peek(input);
4453 if (ch == EOF || ch == '\n')
4454 break;
4455 i_getch(input);
4456 /* note: we do not add it to &ctx.as_string */
4457 }
4458 nommu_addchr(&ctx.as_string, '\n');
4459 continue; /* back to top of while (1) */
4460 }
4461 break;
4462 case '\\':
4463 if (next == '\n') {
4464 /* It's "\<newline>" */
4465#if !BB_MMU
4466 /* Remove trailing '\' from ctx.as_string */
4467 ctx.as_string.data[--ctx.as_string.length] = '\0';
4468#endif
4469 ch = i_getch(input); /* eat it */
4470 continue; /* back to top of while (1) */
4471 }
4472 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004473 }
4474
4475 if (dest.o_assignment == MAYBE_ASSIGNMENT
4476 /* check that we are not in word in "a=1 2>word b=1": */
4477 && !ctx.pending_redirect
4478 ) {
4479 /* ch is a special char and thus this word
4480 * cannot be an assignment */
4481 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004482 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004483 }
4484
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004485 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4486
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004487 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004488 case '#': /* non-comment #: "echo a#b" etc */
4489 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004490 break;
4491 case '\\':
4492 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004493 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004494 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004495 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004496 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004497 /* note: ch != '\n' (that case does not reach this place) */
4498 o_addchr(&dest, '\\');
4499 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4500 o_addchr(&dest, ch);
4501 nommu_addchr(&ctx.as_string, ch);
4502 /* Example: echo Hello \2>file
4503 * we need to know that word 2 is quoted */
4504 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004505 break;
4506 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004507 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004508 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004509 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004510 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004511 }
Eric Andersen25f27032001-04-26 23:22:31 +00004512 break;
4513 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004514 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004515 if (next == '\'' && !ctx.pending_redirect) {
4516 insert_empty_quoted_str_marker:
4517 nommu_addchr(&ctx.as_string, next);
4518 i_getch(input); /* eat second ' */
4519 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4520 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4521 } else {
4522 while (1) {
4523 ch = i_getch(input);
4524 if (ch == EOF) {
4525 syntax_error_unterm_ch('\'');
4526 goto parse_error;
4527 }
4528 nommu_addchr(&ctx.as_string, ch);
4529 if (ch == '\'')
4530 break;
4531 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004532 }
Eric Andersen25f27032001-04-26 23:22:31 +00004533 }
Eric Andersen25f27032001-04-26 23:22:31 +00004534 break;
4535 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004536 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004537 if (next == '"' && !ctx.pending_redirect)
4538 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004539 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004540 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004541 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004542 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004543 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004544 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004545#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004546 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004547 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004548
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004549 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4550 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004551 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004552 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4553 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004554# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004555 o_addstr(&ctx.as_string, dest.data + pos);
4556 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004557# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004558 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4559 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004560 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004561 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004562#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004563 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004564#if ENABLE_HUSH_CASE
4565 case_semi:
4566#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004567 if (done_word(&dest, &ctx)) {
4568 goto parse_error;
4569 }
4570 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004571#if ENABLE_HUSH_CASE
4572 /* Eat multiple semicolons, detect
4573 * whether it means something special */
4574 while (1) {
4575 ch = i_peek(input);
4576 if (ch != ';')
4577 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004578 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004579 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004580 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004581 ctx.ctx_dsemicolon = 1;
4582 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004583 break;
4584 }
4585 }
4586#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004587 new_cmd:
4588 /* We just finished a cmd. New one may start
4589 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004590 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004591 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004592 break;
4593 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004594 if (done_word(&dest, &ctx)) {
4595 goto parse_error;
4596 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004597 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004598 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004599 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004600 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004601 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004602 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004603 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004604 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004605 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004606 if (done_word(&dest, &ctx)) {
4607 goto parse_error;
4608 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004609#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004610 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004611 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004612#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004613 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004614 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004615 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004616 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004617 } else {
4618 /* we could pick up a file descriptor choice here
4619 * with redirect_opt_num(), but bash doesn't do it.
4620 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004621 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004622#if !BB_MMU
4623 o_reset_to_empty_unquoted(&ctx.as_string);
4624#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004625 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004626 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004627 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004628#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004629 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004630 if (ctx.ctx_res_w == RES_MATCH
4631 && ctx.command->argv == NULL /* not (word|(... */
4632 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004633 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004634 ) {
4635 continue;
4636 }
4637#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004638 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004639 if (parse_group(&dest, &ctx, input, ch) != 0) {
4640 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004641 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004642 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004643 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004644#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004645 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004646 goto case_semi;
4647#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004648 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004649 /* proper use of this character is caught by end_trigger:
4650 * if we see {, we call parse_group(..., end_trigger='}')
4651 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004652 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004653 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004654 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004655 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004656 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004657 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004658 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004659
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004660 parse_error:
4661 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004662 struct parse_context *pctx;
4663 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004664
4665 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004666 * Sample for finding leaks on syntax error recovery path.
4667 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004668 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004669 * Samples to catch leaks at execution:
4670 * while if (true | {true;}); then echo ok; fi; do break; done
4671 * 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 +00004672 */
4673 pctx = &ctx;
4674 do {
4675 /* Update pipe/command counts,
4676 * otherwise freeing may miss some */
4677 done_pipe(pctx, PIPE_SEQ);
4678 debug_printf_clean("freeing list %p from ctx %p\n",
4679 pctx->list_head, pctx);
4680 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004681 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004682 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004683#if !BB_MMU
4684 o_free_unsafe(&pctx->as_string);
4685#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004686 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004687 if (pctx != &ctx) {
4688 free(pctx);
4689 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004690 IF_HAS_KEYWORDS(pctx = p2;)
4691 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004692
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004693 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004694 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004695#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004696 if (pstring)
4697 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004698#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004699 debug_leave();
4700 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004701 }
Eric Andersen25f27032001-04-26 23:22:31 +00004702}
4703
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004704
4705/*** Execution routines ***/
4706
4707/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004708#if !ENABLE_HUSH_BASH_COMPAT
4709/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4710#define expand_string_to_string(str, do_unbackslash) \
4711 expand_string_to_string(str)
4712#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004713static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004714#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004715static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004716#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004717
4718/* expand_strvec_to_strvec() takes a list of strings, expands
4719 * all variable references within and returns a pointer to
4720 * a list of expanded strings, possibly with larger number
4721 * of strings. (Think VAR="a b"; echo $VAR).
4722 * This new list is allocated as a single malloc block.
4723 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004724 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004725 * Caller can deallocate entire list by single free(list). */
4726
Denys Vlasenko238081f2010-10-03 14:26:26 +02004727/* A horde of its helpers come first: */
4728
4729static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4730{
4731 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004732 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004733
Denys Vlasenko9e800222010-10-03 14:28:04 +02004734#if ENABLE_HUSH_BRACE_EXPANSION
4735 if (c == '{' || c == '}') {
4736 /* { -> \{, } -> \} */
4737 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004738 /* And now we want to add { or } and continue:
4739 * o_addchr(o, c);
4740 * continue;
4741 * luckily, just falling throught achieves this.
4742 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004743 }
4744#endif
4745 o_addchr(o, c);
4746 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004747 /* \z -> \\\z; \<eol> -> \\<eol> */
4748 o_addchr(o, '\\');
4749 if (len) {
4750 len--;
4751 o_addchr(o, '\\');
4752 o_addchr(o, *str++);
4753 }
4754 }
4755 }
4756}
4757
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004758/* Store given string, finalizing the word and starting new one whenever
4759 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004760 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4761 * Return in *ended_with_ifs:
4762 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4763 */
4764static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004765{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004766 int last_is_ifs = 0;
4767
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004768 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004769 int word_len;
4770
4771 if (!*str) /* EOL - do not finalize word */
4772 break;
4773 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004774 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004775 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02004776 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004777 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004778 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004779 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004780 * Example: "v='\*'; echo b$v" prints "b\*"
4781 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004782 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004783 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004784 /*/ Why can't we do it easier? */
4785 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4786 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4787 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004788 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004789 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004790 if (!*str) /* EOL - do not finalize word */
4791 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004792 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004793
4794 /* We know str here points to at least one IFS char */
4795 last_is_ifs = 1;
4796 str += strspn(str, G.ifs); /* skip IFS chars */
4797 if (!*str) /* EOL - do not finalize word */
4798 break;
4799
4800 /* Start new word... but not always! */
4801 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004802 if (output->has_quoted_part
4803 /* Case "v=' a'; echo $v":
4804 * here nothing precedes the space in $v expansion,
4805 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004806 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004807 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004808 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004809 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004810 o_addchr(output, '\0');
4811 debug_print_list("expand_on_ifs", output, n);
4812 n = o_save_ptr(output, n);
4813 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004814 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004815
4816 if (ended_with_ifs)
4817 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004818 debug_print_list("expand_on_ifs[1]", output, n);
4819 return n;
4820}
4821
4822/* Helper to expand $((...)) and heredoc body. These act as if
4823 * they are in double quotes, with the exception that they are not :).
4824 * Just the rules are similar: "expand only $var and `cmd`"
4825 *
4826 * Returns malloced string.
4827 * As an optimization, we return NULL if expansion is not needed.
4828 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004829#if !ENABLE_HUSH_BASH_COMPAT
4830/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4831#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4832 encode_then_expand_string(str)
4833#endif
4834static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004835{
4836 char *exp_str;
4837 struct in_str input;
4838 o_string dest = NULL_O_STRING;
4839
4840 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004841 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004842#if ENABLE_HUSH_TICK
4843 && !strchr(str, '`')
4844#endif
4845 ) {
4846 return NULL;
4847 }
4848
4849 /* We need to expand. Example:
4850 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4851 */
4852 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004853 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004854//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004855 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004856 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004857 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4858 o_free_unsafe(&dest);
4859 return exp_str;
4860}
4861
4862#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004863static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004864{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004865 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004866 arith_t res;
4867 char *exp_str;
4868
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004869 math_state.lookupvar = get_local_var_value;
4870 math_state.setvar = set_local_var_from_halves;
4871 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004872 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004873 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004874 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004875 if (errmsg_p)
4876 *errmsg_p = math_state.errmsg;
4877 if (math_state.errmsg)
4878 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004879 return res;
4880}
4881#endif
4882
4883#if ENABLE_HUSH_BASH_COMPAT
4884/* ${var/[/]pattern[/repl]} helpers */
4885static char *strstr_pattern(char *val, const char *pattern, int *size)
4886{
4887 while (1) {
4888 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4889 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4890 if (end) {
4891 *size = end - val;
4892 return val;
4893 }
4894 if (*val == '\0')
4895 return NULL;
4896 /* Optimization: if "*pat" did not match the start of "string",
4897 * we know that "tring", "ring" etc will not match too:
4898 */
4899 if (pattern[0] == '*')
4900 return NULL;
4901 val++;
4902 }
4903}
4904static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4905{
4906 char *result = NULL;
4907 unsigned res_len = 0;
4908 unsigned repl_len = strlen(repl);
4909
4910 while (1) {
4911 int size;
4912 char *s = strstr_pattern(val, pattern, &size);
4913 if (!s)
4914 break;
4915
4916 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4917 memcpy(result + res_len, val, s - val);
4918 res_len += s - val;
4919 strcpy(result + res_len, repl);
4920 res_len += repl_len;
4921 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4922
4923 val = s + size;
4924 if (exp_op == '/')
4925 break;
4926 }
4927 if (val[0] && result) {
4928 result = xrealloc(result, res_len + strlen(val) + 1);
4929 strcpy(result + res_len, val);
4930 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4931 }
4932 debug_printf_varexp("result:'%s'\n", result);
4933 return result;
4934}
4935#endif
4936
4937/* Helper:
4938 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4939 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004940static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004941{
4942 const char *val = NULL;
4943 char *to_be_freed = NULL;
4944 char *p = *pp;
4945 char *var;
4946 char first_char;
4947 char exp_op;
4948 char exp_save = exp_save; /* for compiler */
4949 char *exp_saveptr; /* points to expansion operator */
4950 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004951 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004952
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004953 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004954 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004955 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004956 arg0 = arg[0];
4957 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004958 exp_op = 0;
4959
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004960 if (first_char == '#' /* ${#... */
4961 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4962 ) {
4963 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004964 var++;
4965 exp_op = 'L';
4966 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004967 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004968 if (exp_saveptr /* if 2nd char is one of expansion operators */
4969 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4970 ) {
4971 /* ${?:0}, ${#[:]%0} etc */
4972 exp_saveptr = var + 1;
4973 } else {
4974 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4975 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4976 }
4977 exp_op = exp_save = *exp_saveptr;
4978 if (exp_op) {
4979 exp_word = exp_saveptr + 1;
4980 if (exp_op == ':') {
4981 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004982//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004983 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004984 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004985 ) {
4986 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4987 exp_op = ':';
4988 exp_word--;
4989 }
4990 }
4991 *exp_saveptr = '\0';
4992 } /* else: it's not an expansion op, but bare ${var} */
4993 }
4994
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004995 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004996 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004997 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004998 int n = xatoi_positive(var);
4999 if (n < G.global_argc)
5000 val = G.global_argv[n];
5001 /* else val remains NULL: $N with too big N */
5002 } else {
5003 switch (var[0]) {
5004 case '$': /* pid */
5005 val = utoa(G.root_pid);
5006 break;
5007 case '!': /* bg pid */
5008 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5009 break;
5010 case '?': /* exitcode */
5011 val = utoa(G.last_exitcode);
5012 break;
5013 case '#': /* argc */
5014 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5015 break;
5016 default:
5017 val = get_local_var_value(var);
5018 }
5019 }
5020
5021 /* Handle any expansions */
5022 if (exp_op == 'L') {
5023 debug_printf_expand("expand: length(%s)=", val);
5024 val = utoa(val ? strlen(val) : 0);
5025 debug_printf_expand("%s\n", val);
5026 } else if (exp_op) {
5027 if (exp_op == '%' || exp_op == '#') {
5028 /* Standard-mandated substring removal ops:
5029 * ${parameter%word} - remove smallest suffix pattern
5030 * ${parameter%%word} - remove largest suffix pattern
5031 * ${parameter#word} - remove smallest prefix pattern
5032 * ${parameter##word} - remove largest prefix pattern
5033 *
5034 * Word is expanded to produce a glob pattern.
5035 * Then var's value is matched to it and matching part removed.
5036 */
5037 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005038 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005039 char *exp_exp_word;
5040 char *loc;
5041 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005042 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005043 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005044 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005045 if (exp_exp_word)
5046 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005047 /* HACK ALERT. We depend here on the fact that
5048 * G.global_argv and results of utoa and get_local_var_value
5049 * are actually in writable memory:
5050 * scan_and_match momentarily stores NULs there. */
5051 t = (char*)val;
5052 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005053 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005054 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005055 free(exp_exp_word);
5056 if (loc) { /* match was found */
5057 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005058 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005059 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005060 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005061 }
5062 }
5063 }
5064#if ENABLE_HUSH_BASH_COMPAT
5065 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005066 /* It's ${var/[/]pattern[/repl]} thing.
5067 * Note that in encoded form it has TWO parts:
5068 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005069 * and if // is used, it is encoded as \:
5070 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005071 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005072 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005073 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005074 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005075 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005076 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005077 * by the usual expansion rules:
5078 * >az; >bz;
5079 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5080 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5081 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5082 * v='a bz'; echo ${v/a*z/\z} prints "z"
5083 * (note that a*z _pattern_ is never globbed!)
5084 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005085 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005086 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005087 if (!pattern)
5088 pattern = xstrdup(exp_word);
5089 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5090 *p++ = SPECIAL_VAR_SYMBOL;
5091 exp_word = p;
5092 p = strchr(p, SPECIAL_VAR_SYMBOL);
5093 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005094 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005095 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5096 /* HACK ALERT. We depend here on the fact that
5097 * G.global_argv and results of utoa and get_local_var_value
5098 * are actually in writable memory:
5099 * replace_pattern momentarily stores NULs there. */
5100 t = (char*)val;
5101 to_be_freed = replace_pattern(t,
5102 pattern,
5103 (repl ? repl : exp_word),
5104 exp_op);
5105 if (to_be_freed) /* at least one replace happened */
5106 val = to_be_freed;
5107 free(pattern);
5108 free(repl);
5109 }
5110 }
5111#endif
5112 else if (exp_op == ':') {
5113#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5114 /* It's ${var:N[:M]} bashism.
5115 * Note that in encoded form it has TWO parts:
5116 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5117 */
5118 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005119 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005120
Denys Vlasenko063847d2010-09-15 13:33:02 +02005121 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5122 if (errmsg)
5123 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005124 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5125 *p++ = SPECIAL_VAR_SYMBOL;
5126 exp_word = p;
5127 p = strchr(p, SPECIAL_VAR_SYMBOL);
5128 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005129 len = expand_and_evaluate_arith(exp_word, &errmsg);
5130 if (errmsg)
5131 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005132 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005133 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005134 if (beg < 0) /* bash compat */
5135 beg = 0;
5136 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005137 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005138 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005139 val = NULL;
5140 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005141 /* Paranoia. What if user entered 9999999999999
5142 * which fits in arith_t but not int? */
5143 if (len >= INT_MAX)
5144 len = INT_MAX;
5145 val = to_be_freed = xstrndup(val + beg, len);
5146 }
5147 debug_printf_varexp("val:'%s'\n", val);
5148 } else
5149#endif
5150 {
5151 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005152 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005153 }
5154 } else { /* one of "-=+?" */
5155 /* Standard-mandated substitution ops:
5156 * ${var?word} - indicate error if unset
5157 * If var is unset, word (or a message indicating it is unset
5158 * if word is null) is written to standard error
5159 * and the shell exits with a non-zero exit status.
5160 * Otherwise, the value of var is substituted.
5161 * ${var-word} - use default value
5162 * If var is unset, word is substituted.
5163 * ${var=word} - assign and use default value
5164 * If var is unset, word is assigned to var.
5165 * In all cases, final value of var is substituted.
5166 * ${var+word} - use alternative value
5167 * If var is unset, null is substituted.
5168 * Otherwise, word is substituted.
5169 *
5170 * Word is subjected to tilde expansion, parameter expansion,
5171 * command substitution, and arithmetic expansion.
5172 * If word is not needed, it is not expanded.
5173 *
5174 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5175 * but also treat null var as if it is unset.
5176 */
5177 int use_word = (!val || ((exp_save == ':') && !val[0]));
5178 if (exp_op == '+')
5179 use_word = !use_word;
5180 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5181 (exp_save == ':') ? "true" : "false", use_word);
5182 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005183 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005184 if (to_be_freed)
5185 exp_word = to_be_freed;
5186 if (exp_op == '?') {
5187 /* mimic bash message */
5188 die_if_script("%s: %s",
5189 var,
5190 exp_word[0] ? exp_word : "parameter null or not set"
5191 );
5192//TODO: how interactive bash aborts expansion mid-command?
5193 } else {
5194 val = exp_word;
5195 }
5196
5197 if (exp_op == '=') {
5198 /* ${var=[word]} or ${var:=[word]} */
5199 if (isdigit(var[0]) || var[0] == '#') {
5200 /* mimic bash message */
5201 die_if_script("$%s: cannot assign in this way", var);
5202 val = NULL;
5203 } else {
5204 char *new_var = xasprintf("%s=%s", var, val);
5205 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5206 }
5207 }
5208 }
5209 } /* one of "-=+?" */
5210
5211 *exp_saveptr = exp_save;
5212 } /* if (exp_op) */
5213
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005214 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005215
5216 *pp = p;
5217 *to_be_freed_pp = to_be_freed;
5218 return val;
5219}
5220
5221/* Expand all variable references in given string, adding words to list[]
5222 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5223 * to be filled). This routine is extremely tricky: has to deal with
5224 * variables/parameters with whitespace, $* and $@, and constructs like
5225 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005226static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005227{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005228 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005229 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005230 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005231 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005232 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005233 char *p;
5234
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005235 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5236 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005237 debug_print_list("expand_vars_to_list", output, n);
5238 n = o_save_ptr(output, n);
5239 debug_print_list("expand_vars_to_list[0]", output, n);
5240
5241 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5242 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005243 char *to_be_freed = NULL;
5244 const char *val = NULL;
5245#if ENABLE_HUSH_TICK
5246 o_string subst_result = NULL_O_STRING;
5247#endif
5248#if ENABLE_SH_MATH_SUPPORT
5249 char arith_buf[sizeof(arith_t)*3 + 2];
5250#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005251
5252 if (ended_in_ifs) {
5253 o_addchr(output, '\0');
5254 n = o_save_ptr(output, n);
5255 ended_in_ifs = 0;
5256 }
5257
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005258 o_addblock(output, arg, p - arg);
5259 debug_print_list("expand_vars_to_list[1]", output, n);
5260 arg = ++p;
5261 p = strchr(p, SPECIAL_VAR_SYMBOL);
5262
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005263 /* Fetch special var name (if it is indeed one of them)
5264 * and quote bit, force the bit on if singleword expansion -
5265 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005266 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005267
5268 /* Is this variable quoted and thus expansion can't be null?
5269 * "$@" is special. Even if quoted, it can still
5270 * expand to nothing (not even an empty string),
5271 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005272 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005273 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005274
5275 switch (first_ch & 0x7f) {
5276 /* Highest bit in first_ch indicates that var is double-quoted */
5277 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005278 case '@': {
5279 int i;
5280 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005281 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005282 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005283 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005284 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005285 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005286 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005287 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5288 if (G.global_argv[i++][0] && G.global_argv[i]) {
5289 /* this argv[] is not empty and not last:
5290 * put terminating NUL, start new word */
5291 o_addchr(output, '\0');
5292 debug_print_list("expand_vars_to_list[2]", output, n);
5293 n = o_save_ptr(output, n);
5294 debug_print_list("expand_vars_to_list[3]", output, n);
5295 }
5296 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005297 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005298 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005299 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005300 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005301 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005302 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005303 while (1) {
5304 o_addQstr(output, G.global_argv[i]);
5305 if (++i >= G.global_argc)
5306 break;
5307 o_addchr(output, '\0');
5308 debug_print_list("expand_vars_to_list[4]", output, n);
5309 n = o_save_ptr(output, n);
5310 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005311 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005312 while (1) {
5313 o_addQstr(output, G.global_argv[i]);
5314 if (!G.global_argv[++i])
5315 break;
5316 if (G.ifs[0])
5317 o_addchr(output, G.ifs[0]);
5318 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005319 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005320 }
5321 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005322 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005323 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5324 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005325 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005326 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005327 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005328 break;
5329#if ENABLE_HUSH_TICK
5330 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005331 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005332 arg++;
5333 /* Can't just stuff it into output o_string,
5334 * expanded result may need to be globbed
5335 * and $IFS-splitted */
5336 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5337 G.last_exitcode = process_command_subs(&subst_result, arg);
5338 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5339 val = subst_result.data;
5340 goto store_val;
5341#endif
5342#if ENABLE_SH_MATH_SUPPORT
5343 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5344 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005345
5346 arg++; /* skip '+' */
5347 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5348 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005349 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005350 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5351 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005352 val = arith_buf;
5353 break;
5354 }
5355#endif
5356 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005357 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005358 IF_HUSH_TICK(store_val:)
5359 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005360 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5361 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005362 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005363 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005364 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005365 }
5366 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005367 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005368 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5369 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005370 }
5371 break;
5372
5373 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5374
5375 if (val && val[0]) {
5376 o_addQstr(output, val);
5377 }
5378 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005379
5380 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5381 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005382 if (*p != SPECIAL_VAR_SYMBOL)
5383 *p = SPECIAL_VAR_SYMBOL;
5384
5385#if ENABLE_HUSH_TICK
5386 o_free(&subst_result);
5387#endif
5388 arg = ++p;
5389 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5390
5391 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005392 if (ended_in_ifs) {
5393 o_addchr(output, '\0');
5394 n = o_save_ptr(output, n);
5395 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005396 debug_print_list("expand_vars_to_list[a]", output, n);
5397 /* this part is literal, and it was already pre-quoted
5398 * if needed (much earlier), do not use o_addQstr here! */
5399 o_addstr_with_NUL(output, arg);
5400 debug_print_list("expand_vars_to_list[b]", output, n);
5401 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005402 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005403 ) {
5404 n--;
5405 /* allow to reuse list[n] later without re-growth */
5406 output->has_empty_slot = 1;
5407 } else {
5408 o_addchr(output, '\0');
5409 }
5410
5411 return n;
5412}
5413
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005414static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005415{
5416 int n;
5417 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005418 o_string output = NULL_O_STRING;
5419
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005420 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005421
5422 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005423 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005424 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005425 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005426 }
5427 debug_print_list("expand_variables", &output, n);
5428
5429 /* output.data (malloced in one block) gets returned in "list" */
5430 list = o_finalize_list(&output, n);
5431 debug_print_strings("expand_variables[1]", list);
5432 return list;
5433}
5434
5435static char **expand_strvec_to_strvec(char **argv)
5436{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005437 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005438}
5439
5440#if ENABLE_HUSH_BASH_COMPAT
5441static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5442{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005443 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005444}
5445#endif
5446
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005447/* Used for expansion of right hand of assignments,
5448 * $((...)), heredocs, variable espansion parts.
5449 *
5450 * NB: should NOT do globbing!
5451 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5452 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005453static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005454{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005455#if !ENABLE_HUSH_BASH_COMPAT
5456 const int do_unbackslash = 1;
5457#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005458 char *argv[2], **list;
5459
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005460 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005461 /* This is generally an optimization, but it also
5462 * handles "", which otherwise trips over !list[0] check below.
5463 * (is this ever happens that we actually get str="" here?)
5464 */
5465 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5466 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005467 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005468 return xstrdup(str);
5469 }
5470
5471 argv[0] = (char*)str;
5472 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005473 list = expand_variables(argv, do_unbackslash
5474 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5475 : EXP_FLAG_SINGLEWORD
5476 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005477 if (HUSH_DEBUG)
5478 if (!list[0] || list[1])
5479 bb_error_msg_and_die("BUG in varexp2");
5480 /* actually, just move string 2*sizeof(char*) bytes back */
5481 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005482 if (do_unbackslash)
5483 unbackslash((char*)list);
5484 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005485 return (char*)list;
5486}
5487
5488/* Used for "eval" builtin */
5489static char* expand_strvec_to_string(char **argv)
5490{
5491 char **list;
5492
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005493 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005494 /* Convert all NULs to spaces */
5495 if (list[0]) {
5496 int n = 1;
5497 while (list[n]) {
5498 if (HUSH_DEBUG)
5499 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5500 bb_error_msg_and_die("BUG in varexp3");
5501 /* bash uses ' ' regardless of $IFS contents */
5502 list[n][-1] = ' ';
5503 n++;
5504 }
5505 }
5506 overlapping_strcpy((char*)list, list[0]);
5507 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5508 return (char*)list;
5509}
5510
5511static char **expand_assignments(char **argv, int count)
5512{
5513 int i;
5514 char **p;
5515
5516 G.expanded_assignments = p = NULL;
5517 /* Expand assignments into one string each */
5518 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005519 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005520 }
5521 G.expanded_assignments = NULL;
5522 return p;
5523}
5524
5525
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005526static void switch_off_special_sigs(unsigned mask)
5527{
5528 unsigned sig = 0;
5529 while ((mask >>= 1) != 0) {
5530 sig++;
5531 if (!(mask & 1))
5532 continue;
5533 if (G.traps) {
5534 if (G.traps[sig] && !G.traps[sig][0])
5535 /* trap is '', has to remain SIG_IGN */
5536 continue;
5537 free(G.traps[sig]);
5538 G.traps[sig] = NULL;
5539 }
5540 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005541 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005542 }
5543}
5544
Denys Vlasenkob347df92011-08-09 22:49:15 +02005545#if BB_MMU
5546/* never called */
5547void re_execute_shell(char ***to_free, const char *s,
5548 char *g_argv0, char **g_argv,
5549 char **builtin_argv) NORETURN;
5550
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005551static void reset_traps_to_defaults(void)
5552{
5553 /* This function is always called in a child shell
5554 * after fork (not vfork, NOMMU doesn't use this function).
5555 */
5556 unsigned sig;
5557 unsigned mask;
5558
5559 /* Child shells are not interactive.
5560 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5561 * Testcase: (while :; do :; done) + ^Z should background.
5562 * Same goes for SIGTERM, SIGHUP, SIGINT.
5563 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005564 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5565 if (!G.traps && !mask)
5566 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005567
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005568 /* Switch off special sigs */
5569 switch_off_special_sigs(mask);
5570#if ENABLE_HUSH_JOB
5571 G_fatal_sig_mask = 0;
5572#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005573 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005574 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5575 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005576
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005577 if (!G.traps)
5578 return;
5579
5580 /* Reset all sigs to default except ones with empty traps */
5581 for (sig = 0; sig < NSIG; sig++) {
5582 if (!G.traps[sig])
5583 continue; /* no trap: nothing to do */
5584 if (!G.traps[sig][0])
5585 continue; /* empty trap: has to remain SIG_IGN */
5586 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005587 free(G.traps[sig]);
5588 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005589 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005590 if (sig == 0)
5591 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005592 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005593 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005594}
5595
5596#else /* !BB_MMU */
5597
5598static void re_execute_shell(char ***to_free, const char *s,
5599 char *g_argv0, char **g_argv,
5600 char **builtin_argv) NORETURN;
5601static void re_execute_shell(char ***to_free, const char *s,
5602 char *g_argv0, char **g_argv,
5603 char **builtin_argv)
5604{
5605# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5606 /* delims + 2 * (number of bytes in printed hex numbers) */
5607 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5608 char *heredoc_argv[4];
5609 struct variable *cur;
5610# if ENABLE_HUSH_FUNCTIONS
5611 struct function *funcp;
5612# endif
5613 char **argv, **pp;
5614 unsigned cnt;
5615 unsigned long long empty_trap_mask;
5616
5617 if (!g_argv0) { /* heredoc */
5618 argv = heredoc_argv;
5619 argv[0] = (char *) G.argv0_for_re_execing;
5620 argv[1] = (char *) "-<";
5621 argv[2] = (char *) s;
5622 argv[3] = NULL;
5623 pp = &argv[3]; /* used as pointer to empty environment */
5624 goto do_exec;
5625 }
5626
5627 cnt = 0;
5628 pp = builtin_argv;
5629 if (pp) while (*pp++)
5630 cnt++;
5631
5632 empty_trap_mask = 0;
5633 if (G.traps) {
5634 int sig;
5635 for (sig = 1; sig < NSIG; sig++) {
5636 if (G.traps[sig] && !G.traps[sig][0])
5637 empty_trap_mask |= 1LL << sig;
5638 }
5639 }
5640
5641 sprintf(param_buf, NOMMU_HACK_FMT
5642 , (unsigned) G.root_pid
5643 , (unsigned) G.root_ppid
5644 , (unsigned) G.last_bg_pid
5645 , (unsigned) G.last_exitcode
5646 , cnt
5647 , empty_trap_mask
5648 IF_HUSH_LOOPS(, G.depth_of_loop)
5649 );
5650# undef NOMMU_HACK_FMT
5651 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5652 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5653 */
5654 cnt += 6;
5655 for (cur = G.top_var; cur; cur = cur->next) {
5656 if (!cur->flg_export || cur->flg_read_only)
5657 cnt += 2;
5658 }
5659# if ENABLE_HUSH_FUNCTIONS
5660 for (funcp = G.top_func; funcp; funcp = funcp->next)
5661 cnt += 3;
5662# endif
5663 pp = g_argv;
5664 while (*pp++)
5665 cnt++;
5666 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5667 *pp++ = (char *) G.argv0_for_re_execing;
5668 *pp++ = param_buf;
5669 for (cur = G.top_var; cur; cur = cur->next) {
5670 if (strcmp(cur->varstr, hush_version_str) == 0)
5671 continue;
5672 if (cur->flg_read_only) {
5673 *pp++ = (char *) "-R";
5674 *pp++ = cur->varstr;
5675 } else if (!cur->flg_export) {
5676 *pp++ = (char *) "-V";
5677 *pp++ = cur->varstr;
5678 }
5679 }
5680# if ENABLE_HUSH_FUNCTIONS
5681 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5682 *pp++ = (char *) "-F";
5683 *pp++ = funcp->name;
5684 *pp++ = funcp->body_as_string;
5685 }
5686# endif
5687 /* We can pass activated traps here. Say, -Tnn:trap_string
5688 *
5689 * However, POSIX says that subshells reset signals with traps
5690 * to SIG_DFL.
5691 * I tested bash-3.2 and it not only does that with true subshells
5692 * of the form ( list ), but with any forked children shells.
5693 * I set trap "echo W" WINCH; and then tried:
5694 *
5695 * { echo 1; sleep 20; echo 2; } &
5696 * while true; do echo 1; sleep 20; echo 2; break; done &
5697 * true | { echo 1; sleep 20; echo 2; } | cat
5698 *
5699 * In all these cases sending SIGWINCH to the child shell
5700 * did not run the trap. If I add trap "echo V" WINCH;
5701 * _inside_ group (just before echo 1), it works.
5702 *
5703 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005704 */
5705 *pp++ = (char *) "-c";
5706 *pp++ = (char *) s;
5707 if (builtin_argv) {
5708 while (*++builtin_argv)
5709 *pp++ = *builtin_argv;
5710 *pp++ = (char *) "";
5711 }
5712 *pp++ = g_argv0;
5713 while (*g_argv)
5714 *pp++ = *g_argv++;
5715 /* *pp = NULL; - is already there */
5716 pp = environ;
5717
5718 do_exec:
5719 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02005720 /* Don't propagate SIG_IGN to the child */
5721 if (SPECIAL_JOBSTOP_SIGS != 0)
5722 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005723 execve(bb_busybox_exec_path, argv, pp);
5724 /* Fallback. Useful for init=/bin/hush usage etc */
5725 if (argv[0][0] == '/')
5726 execve(argv[0], argv, pp);
5727 xfunc_error_retval = 127;
5728 bb_error_msg_and_die("can't re-execute the shell");
5729}
5730#endif /* !BB_MMU */
5731
5732
5733static int run_and_free_list(struct pipe *pi);
5734
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005735/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005736 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5737 * end_trigger controls how often we stop parsing
5738 * NUL: parse all, execute, return
5739 * ';': parse till ';' or newline, execute, repeat till EOF
5740 */
5741static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005742{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005743 /* Why we need empty flag?
5744 * An obscure corner case "false; ``; echo $?":
5745 * empty command in `` should still set $? to 0.
5746 * But we can't just set $? to 0 at the start,
5747 * this breaks "false; echo `echo $?`" case.
5748 */
5749 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005750 while (1) {
5751 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005752
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005753#if ENABLE_HUSH_INTERACTIVE
5754 if (end_trigger == ';')
5755 inp->promptmode = 0; /* PS1 */
5756#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005757 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005758 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5759 /* If we are in "big" script
5760 * (not in `cmd` or something similar)...
5761 */
5762 if (pipe_list == ERR_PTR && end_trigger == ';') {
5763 /* Discard cached input (rest of line) */
5764 int ch = inp->last_char;
5765 while (ch != EOF && ch != '\n') {
5766 //bb_error_msg("Discarded:'%c'", ch);
5767 ch = i_getch(inp);
5768 }
5769 /* Force prompt */
5770 inp->p = NULL;
5771 /* This stream isn't empty */
5772 empty = 0;
5773 continue;
5774 }
5775 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01005776 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005777 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005778 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005779 debug_print_tree(pipe_list, 0);
5780 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5781 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005782 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005783#if ENABLE_HUSH_FUNCTIONS
5784 if (G.flag_return_in_progress == 1)
5785 break;
5786#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005787 }
Eric Andersen25f27032001-04-26 23:22:31 +00005788}
5789
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005790static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005791{
5792 struct in_str input;
5793 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005794 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005795}
5796
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005797static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005798{
Eric Andersen25f27032001-04-26 23:22:31 +00005799 struct in_str input;
5800 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005801 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005802}
5803
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005804#if ENABLE_HUSH_TICK
5805static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5806{
5807 pid_t pid;
5808 int channel[2];
5809# if !BB_MMU
5810 char **to_free = NULL;
5811# endif
5812
5813 xpipe(channel);
5814 pid = BB_MMU ? xfork() : xvfork();
5815 if (pid == 0) { /* child */
5816 disable_restore_tty_pgrp_on_exit();
5817 /* Process substitution is not considered to be usual
5818 * 'command execution'.
5819 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5820 */
5821 bb_signals(0
5822 + (1 << SIGTSTP)
5823 + (1 << SIGTTIN)
5824 + (1 << SIGTTOU)
5825 , SIG_IGN);
5826 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5827 close(channel[0]); /* NB: close _first_, then move fd! */
5828 xmove_fd(channel[1], 1);
5829 /* Prevent it from trying to handle ctrl-z etc */
5830 IF_HUSH_JOB(G.run_list_level = 1;)
5831 /* Awful hack for `trap` or $(trap).
5832 *
5833 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5834 * contains an example where "trap" is executed in a subshell:
5835 *
5836 * save_traps=$(trap)
5837 * ...
5838 * eval "$save_traps"
5839 *
5840 * Standard does not say that "trap" in subshell shall print
5841 * parent shell's traps. It only says that its output
5842 * must have suitable form, but then, in the above example
5843 * (which is not supposed to be normative), it implies that.
5844 *
5845 * bash (and probably other shell) does implement it
5846 * (traps are reset to defaults, but "trap" still shows them),
5847 * but as a result, "trap" logic is hopelessly messed up:
5848 *
5849 * # trap
5850 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5851 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5852 * # true | trap <--- trap is in subshell - no output (ditto)
5853 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5854 * trap -- 'echo Ho' SIGWINCH
5855 * # echo `(trap)` <--- in subshell in subshell - output
5856 * trap -- 'echo Ho' SIGWINCH
5857 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5858 * trap -- 'echo Ho' SIGWINCH
5859 *
5860 * The rules when to forget and when to not forget traps
5861 * get really complex and nonsensical.
5862 *
5863 * Our solution: ONLY bare $(trap) or `trap` is special.
5864 */
5865 s = skip_whitespace(s);
5866 if (strncmp(s, "trap", 4) == 0
5867 && skip_whitespace(s + 4)[0] == '\0'
5868 ) {
5869 static const char *const argv[] = { NULL, NULL };
5870 builtin_trap((char**)argv);
5871 exit(0); /* not _exit() - we need to fflush */
5872 }
5873# if BB_MMU
5874 reset_traps_to_defaults();
5875 parse_and_run_string(s);
5876 _exit(G.last_exitcode);
5877# else
5878 /* We re-execute after vfork on NOMMU. This makes this script safe:
5879 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5880 * huge=`cat BIG` # was blocking here forever
5881 * echo OK
5882 */
5883 re_execute_shell(&to_free,
5884 s,
5885 G.global_argv[0],
5886 G.global_argv + 1,
5887 NULL);
5888# endif
5889 }
5890
5891 /* parent */
5892 *pid_p = pid;
5893# if ENABLE_HUSH_FAST
5894 G.count_SIGCHLD++;
5895//bb_error_msg("[%d] fork in generate_stream_from_string:"
5896// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5897// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5898# endif
5899 enable_restore_tty_pgrp_on_exit();
5900# if !BB_MMU
5901 free(to_free);
5902# endif
5903 close(channel[1]);
5904 close_on_exec_on(channel[0]);
5905 return xfdopen_for_read(channel[0]);
5906}
5907
5908/* Return code is exit status of the process that is run. */
5909static int process_command_subs(o_string *dest, const char *s)
5910{
5911 FILE *fp;
5912 struct in_str pipe_str;
5913 pid_t pid;
5914 int status, ch, eol_cnt;
5915
5916 fp = generate_stream_from_string(s, &pid);
5917
5918 /* Now send results of command back into original context */
5919 setup_file_in_str(&pipe_str, fp);
5920 eol_cnt = 0;
5921 while ((ch = i_getch(&pipe_str)) != EOF) {
5922 if (ch == '\n') {
5923 eol_cnt++;
5924 continue;
5925 }
5926 while (eol_cnt) {
5927 o_addchr(dest, '\n');
5928 eol_cnt--;
5929 }
5930 o_addQchr(dest, ch);
5931 }
5932
5933 debug_printf("done reading from `cmd` pipe, closing it\n");
5934 fclose(fp);
5935 /* We need to extract exitcode. Test case
5936 * "true; echo `sleep 1; false` $?"
5937 * should print 1 */
5938 safe_waitpid(pid, &status, 0);
5939 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5940 return WEXITSTATUS(status);
5941}
5942#endif /* ENABLE_HUSH_TICK */
5943
5944
5945static void setup_heredoc(struct redir_struct *redir)
5946{
5947 struct fd_pair pair;
5948 pid_t pid;
5949 int len, written;
5950 /* the _body_ of heredoc (misleading field name) */
5951 const char *heredoc = redir->rd_filename;
5952 char *expanded;
5953#if !BB_MMU
5954 char **to_free;
5955#endif
5956
5957 expanded = NULL;
5958 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005959 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005960 if (expanded)
5961 heredoc = expanded;
5962 }
5963 len = strlen(heredoc);
5964
5965 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5966 xpiped_pair(pair);
5967 xmove_fd(pair.rd, redir->rd_fd);
5968
5969 /* Try writing without forking. Newer kernels have
5970 * dynamically growing pipes. Must use non-blocking write! */
5971 ndelay_on(pair.wr);
5972 while (1) {
5973 written = write(pair.wr, heredoc, len);
5974 if (written <= 0)
5975 break;
5976 len -= written;
5977 if (len == 0) {
5978 close(pair.wr);
5979 free(expanded);
5980 return;
5981 }
5982 heredoc += written;
5983 }
5984 ndelay_off(pair.wr);
5985
5986 /* Okay, pipe buffer was not big enough */
5987 /* Note: we must not create a stray child (bastard? :)
5988 * for the unsuspecting parent process. Child creates a grandchild
5989 * and exits before parent execs the process which consumes heredoc
5990 * (that exec happens after we return from this function) */
5991#if !BB_MMU
5992 to_free = NULL;
5993#endif
5994 pid = xvfork();
5995 if (pid == 0) {
5996 /* child */
5997 disable_restore_tty_pgrp_on_exit();
5998 pid = BB_MMU ? xfork() : xvfork();
5999 if (pid != 0)
6000 _exit(0);
6001 /* grandchild */
6002 close(redir->rd_fd); /* read side of the pipe */
6003#if BB_MMU
6004 full_write(pair.wr, heredoc, len); /* may loop or block */
6005 _exit(0);
6006#else
6007 /* Delegate blocking writes to another process */
6008 xmove_fd(pair.wr, STDOUT_FILENO);
6009 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6010#endif
6011 }
6012 /* parent */
6013#if ENABLE_HUSH_FAST
6014 G.count_SIGCHLD++;
6015//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6016#endif
6017 enable_restore_tty_pgrp_on_exit();
6018#if !BB_MMU
6019 free(to_free);
6020#endif
6021 close(pair.wr);
6022 free(expanded);
6023 wait(NULL); /* wait till child has died */
6024}
6025
6026/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6027 * and stderr if they are redirected. */
6028static int setup_redirects(struct command *prog, int squirrel[])
6029{
6030 int openfd, mode;
6031 struct redir_struct *redir;
6032
6033 for (redir = prog->redirects; redir; redir = redir->next) {
6034 if (redir->rd_type == REDIRECT_HEREDOC2) {
6035 /* rd_fd<<HERE case */
6036 if (squirrel && redir->rd_fd < 3
6037 && squirrel[redir->rd_fd] < 0
6038 ) {
6039 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6040 }
6041 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6042 * of the heredoc */
6043 debug_printf_parse("set heredoc '%s'\n",
6044 redir->rd_filename);
6045 setup_heredoc(redir);
6046 continue;
6047 }
6048
6049 if (redir->rd_dup == REDIRFD_TO_FILE) {
6050 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6051 char *p;
6052 if (redir->rd_filename == NULL) {
6053 /* Something went wrong in the parse.
6054 * Pretend it didn't happen */
6055 bb_error_msg("bug in redirect parse");
6056 continue;
6057 }
6058 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006059 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006060 openfd = open_or_warn(p, mode);
6061 free(p);
6062 if (openfd < 0) {
6063 /* this could get lost if stderr has been redirected, but
6064 * bash and ash both lose it as well (though zsh doesn't!) */
6065//what the above comment tries to say?
6066 return 1;
6067 }
6068 } else {
6069 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6070 openfd = redir->rd_dup;
6071 }
6072
6073 if (openfd != redir->rd_fd) {
6074 if (squirrel && redir->rd_fd < 3
6075 && squirrel[redir->rd_fd] < 0
6076 ) {
6077 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6078 }
6079 if (openfd == REDIRFD_CLOSE) {
6080 /* "n>-" means "close me" */
6081 close(redir->rd_fd);
6082 } else {
6083 xdup2(openfd, redir->rd_fd);
6084 if (redir->rd_dup == REDIRFD_TO_FILE)
6085 close(openfd);
6086 }
6087 }
6088 }
6089 return 0;
6090}
6091
6092static void restore_redirects(int squirrel[])
6093{
6094 int i, fd;
6095 for (i = 0; i < 3; i++) {
6096 fd = squirrel[i];
6097 if (fd != -1) {
6098 /* We simply die on error */
6099 xmove_fd(fd, i);
6100 }
6101 }
6102}
6103
6104static char *find_in_path(const char *arg)
6105{
6106 char *ret = NULL;
6107 const char *PATH = get_local_var_value("PATH");
6108
6109 if (!PATH)
6110 return NULL;
6111
6112 while (1) {
6113 const char *end = strchrnul(PATH, ':');
6114 int sz = end - PATH; /* must be int! */
6115
6116 free(ret);
6117 if (sz != 0) {
6118 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6119 } else {
6120 /* We have xxx::yyyy in $PATH,
6121 * it means "use current dir" */
6122 ret = xstrdup(arg);
6123 }
6124 if (access(ret, F_OK) == 0)
6125 break;
6126
6127 if (*end == '\0') {
6128 free(ret);
6129 return NULL;
6130 }
6131 PATH = end + 1;
6132 }
6133
6134 return ret;
6135}
6136
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006137static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006138 const struct built_in_command *x,
6139 const struct built_in_command *end)
6140{
6141 while (x != end) {
6142 if (strcmp(name, x->b_cmd) != 0) {
6143 x++;
6144 continue;
6145 }
6146 debug_printf_exec("found builtin '%s'\n", name);
6147 return x;
6148 }
6149 return NULL;
6150}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006151static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006152{
6153 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6154}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006155static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006156{
6157 const struct built_in_command *x = find_builtin1(name);
6158 if (x)
6159 return x;
6160 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6161}
6162
6163#if ENABLE_HUSH_FUNCTIONS
6164static struct function **find_function_slot(const char *name)
6165{
6166 struct function **funcpp = &G.top_func;
6167 while (*funcpp) {
6168 if (strcmp(name, (*funcpp)->name) == 0) {
6169 break;
6170 }
6171 funcpp = &(*funcpp)->next;
6172 }
6173 return funcpp;
6174}
6175
6176static const struct function *find_function(const char *name)
6177{
6178 const struct function *funcp = *find_function_slot(name);
6179 if (funcp)
6180 debug_printf_exec("found function '%s'\n", name);
6181 return funcp;
6182}
6183
6184/* Note: takes ownership on name ptr */
6185static struct function *new_function(char *name)
6186{
6187 struct function **funcpp = find_function_slot(name);
6188 struct function *funcp = *funcpp;
6189
6190 if (funcp != NULL) {
6191 struct command *cmd = funcp->parent_cmd;
6192 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6193 if (!cmd) {
6194 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6195 free(funcp->name);
6196 /* Note: if !funcp->body, do not free body_as_string!
6197 * This is a special case of "-F name body" function:
6198 * body_as_string was not malloced! */
6199 if (funcp->body) {
6200 free_pipe_list(funcp->body);
6201# if !BB_MMU
6202 free(funcp->body_as_string);
6203# endif
6204 }
6205 } else {
6206 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6207 cmd->argv[0] = funcp->name;
6208 cmd->group = funcp->body;
6209# if !BB_MMU
6210 cmd->group_as_string = funcp->body_as_string;
6211# endif
6212 }
6213 } else {
6214 debug_printf_exec("remembering new function '%s'\n", name);
6215 funcp = *funcpp = xzalloc(sizeof(*funcp));
6216 /*funcp->next = NULL;*/
6217 }
6218
6219 funcp->name = name;
6220 return funcp;
6221}
6222
6223static void unset_func(const char *name)
6224{
6225 struct function **funcpp = find_function_slot(name);
6226 struct function *funcp = *funcpp;
6227
6228 if (funcp != NULL) {
6229 debug_printf_exec("freeing function '%s'\n", funcp->name);
6230 *funcpp = funcp->next;
6231 /* funcp is unlinked now, deleting it.
6232 * Note: if !funcp->body, the function was created by
6233 * "-F name body", do not free ->body_as_string
6234 * and ->name as they were not malloced. */
6235 if (funcp->body) {
6236 free_pipe_list(funcp->body);
6237 free(funcp->name);
6238# if !BB_MMU
6239 free(funcp->body_as_string);
6240# endif
6241 }
6242 free(funcp);
6243 }
6244}
6245
6246# if BB_MMU
6247#define exec_function(to_free, funcp, argv) \
6248 exec_function(funcp, argv)
6249# endif
6250static void exec_function(char ***to_free,
6251 const struct function *funcp,
6252 char **argv) NORETURN;
6253static void exec_function(char ***to_free,
6254 const struct function *funcp,
6255 char **argv)
6256{
6257# if BB_MMU
6258 int n = 1;
6259
6260 argv[0] = G.global_argv[0];
6261 G.global_argv = argv;
6262 while (*++argv)
6263 n++;
6264 G.global_argc = n;
6265 /* On MMU, funcp->body is always non-NULL */
6266 n = run_list(funcp->body);
6267 fflush_all();
6268 _exit(n);
6269# else
6270 re_execute_shell(to_free,
6271 funcp->body_as_string,
6272 G.global_argv[0],
6273 argv + 1,
6274 NULL);
6275# endif
6276}
6277
6278static int run_function(const struct function *funcp, char **argv)
6279{
6280 int rc;
6281 save_arg_t sv;
6282 smallint sv_flg;
6283
6284 save_and_replace_G_args(&sv, argv);
6285
6286 /* "we are in function, ok to use return" */
6287 sv_flg = G.flag_return_in_progress;
6288 G.flag_return_in_progress = -1;
6289# if ENABLE_HUSH_LOCAL
6290 G.func_nest_level++;
6291# endif
6292
6293 /* On MMU, funcp->body is always non-NULL */
6294# if !BB_MMU
6295 if (!funcp->body) {
6296 /* Function defined by -F */
6297 parse_and_run_string(funcp->body_as_string);
6298 rc = G.last_exitcode;
6299 } else
6300# endif
6301 {
6302 rc = run_list(funcp->body);
6303 }
6304
6305# if ENABLE_HUSH_LOCAL
6306 {
6307 struct variable *var;
6308 struct variable **var_pp;
6309
6310 var_pp = &G.top_var;
6311 while ((var = *var_pp) != NULL) {
6312 if (var->func_nest_level < G.func_nest_level) {
6313 var_pp = &var->next;
6314 continue;
6315 }
6316 /* Unexport */
6317 if (var->flg_export)
6318 bb_unsetenv(var->varstr);
6319 /* Remove from global list */
6320 *var_pp = var->next;
6321 /* Free */
6322 if (!var->max_len)
6323 free(var->varstr);
6324 free(var);
6325 }
6326 G.func_nest_level--;
6327 }
6328# endif
6329 G.flag_return_in_progress = sv_flg;
6330
6331 restore_G_args(&sv, argv);
6332
6333 return rc;
6334}
6335#endif /* ENABLE_HUSH_FUNCTIONS */
6336
6337
6338#if BB_MMU
6339#define exec_builtin(to_free, x, argv) \
6340 exec_builtin(x, argv)
6341#else
6342#define exec_builtin(to_free, x, argv) \
6343 exec_builtin(to_free, argv)
6344#endif
6345static void exec_builtin(char ***to_free,
6346 const struct built_in_command *x,
6347 char **argv) NORETURN;
6348static void exec_builtin(char ***to_free,
6349 const struct built_in_command *x,
6350 char **argv)
6351{
6352#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006353 int rcode;
6354 fflush_all();
6355 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006356 fflush_all();
6357 _exit(rcode);
6358#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006359 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006360 /* On NOMMU, we must never block!
6361 * Example: { sleep 99 | read line; } & echo Ok
6362 */
6363 re_execute_shell(to_free,
6364 argv[0],
6365 G.global_argv[0],
6366 G.global_argv + 1,
6367 argv);
6368#endif
6369}
6370
6371
6372static void execvp_or_die(char **argv) NORETURN;
6373static void execvp_or_die(char **argv)
6374{
6375 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006376 /* Don't propagate SIG_IGN to the child */
6377 if (SPECIAL_JOBSTOP_SIGS != 0)
6378 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006379 execvp(argv[0], argv);
6380 bb_perror_msg("can't execute '%s'", argv[0]);
6381 _exit(127); /* bash compat */
6382}
6383
6384#if ENABLE_HUSH_MODE_X
6385static void dump_cmd_in_x_mode(char **argv)
6386{
6387 if (G_x_mode && argv) {
6388 /* We want to output the line in one write op */
6389 char *buf, *p;
6390 int len;
6391 int n;
6392
6393 len = 3;
6394 n = 0;
6395 while (argv[n])
6396 len += strlen(argv[n++]) + 1;
6397 buf = xmalloc(len);
6398 buf[0] = '+';
6399 p = buf + 1;
6400 n = 0;
6401 while (argv[n])
6402 p += sprintf(p, " %s", argv[n++]);
6403 *p++ = '\n';
6404 *p = '\0';
6405 fputs(buf, stderr);
6406 free(buf);
6407 }
6408}
6409#else
6410# define dump_cmd_in_x_mode(argv) ((void)0)
6411#endif
6412
6413#if BB_MMU
6414#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6415 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6416#define pseudo_exec(nommu_save, command, argv_expanded) \
6417 pseudo_exec(command, argv_expanded)
6418#endif
6419
6420/* Called after [v]fork() in run_pipe, or from builtin_exec.
6421 * Never returns.
6422 * Don't exit() here. If you don't exec, use _exit instead.
6423 * The at_exit handlers apparently confuse the calling process,
6424 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6425static void pseudo_exec_argv(nommu_save_t *nommu_save,
6426 char **argv, int assignment_cnt,
6427 char **argv_expanded) NORETURN;
6428static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6429 char **argv, int assignment_cnt,
6430 char **argv_expanded)
6431{
6432 char **new_env;
6433
6434 new_env = expand_assignments(argv, assignment_cnt);
6435 dump_cmd_in_x_mode(new_env);
6436
6437 if (!argv[assignment_cnt]) {
6438 /* Case when we are here: ... | var=val | ...
6439 * (note that we do not exit early, i.e., do not optimize out
6440 * expand_assignments(): think about ... | var=`sleep 1` | ...
6441 */
6442 free_strings(new_env);
6443 _exit(EXIT_SUCCESS);
6444 }
6445
6446#if BB_MMU
6447 set_vars_and_save_old(new_env);
6448 free(new_env); /* optional */
6449 /* we can also destroy set_vars_and_save_old's return value,
6450 * to save memory */
6451#else
6452 nommu_save->new_env = new_env;
6453 nommu_save->old_vars = set_vars_and_save_old(new_env);
6454#endif
6455
6456 if (argv_expanded) {
6457 argv = argv_expanded;
6458 } else {
6459 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6460#if !BB_MMU
6461 nommu_save->argv = argv;
6462#endif
6463 }
6464 dump_cmd_in_x_mode(argv);
6465
6466#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6467 if (strchr(argv[0], '/') != NULL)
6468 goto skip;
6469#endif
6470
6471 /* Check if the command matches any of the builtins.
6472 * Depending on context, this might be redundant. But it's
6473 * easier to waste a few CPU cycles than it is to figure out
6474 * if this is one of those cases.
6475 */
6476 {
6477 /* On NOMMU, it is more expensive to re-execute shell
6478 * just in order to run echo or test builtin.
6479 * It's better to skip it here and run corresponding
6480 * non-builtin later. */
6481 const struct built_in_command *x;
6482 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6483 if (x) {
6484 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6485 }
6486 }
6487#if ENABLE_HUSH_FUNCTIONS
6488 /* Check if the command matches any functions */
6489 {
6490 const struct function *funcp = find_function(argv[0]);
6491 if (funcp) {
6492 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6493 }
6494 }
6495#endif
6496
6497#if ENABLE_FEATURE_SH_STANDALONE
6498 /* Check if the command matches any busybox applets */
6499 {
6500 int a = find_applet_by_name(argv[0]);
6501 if (a >= 0) {
6502# if BB_MMU /* see above why on NOMMU it is not allowed */
6503 if (APPLET_IS_NOEXEC(a)) {
6504 debug_printf_exec("running applet '%s'\n", argv[0]);
6505 run_applet_no_and_exit(a, argv);
6506 }
6507# endif
6508 /* Re-exec ourselves */
6509 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006510 /* Don't propagate SIG_IGN to the child */
6511 if (SPECIAL_JOBSTOP_SIGS != 0)
6512 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006513 execv(bb_busybox_exec_path, argv);
6514 /* If they called chroot or otherwise made the binary no longer
6515 * executable, fall through */
6516 }
6517 }
6518#endif
6519
6520#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6521 skip:
6522#endif
6523 execvp_or_die(argv);
6524}
6525
6526/* Called after [v]fork() in run_pipe
6527 */
6528static void pseudo_exec(nommu_save_t *nommu_save,
6529 struct command *command,
6530 char **argv_expanded) NORETURN;
6531static void pseudo_exec(nommu_save_t *nommu_save,
6532 struct command *command,
6533 char **argv_expanded)
6534{
6535 if (command->argv) {
6536 pseudo_exec_argv(nommu_save, command->argv,
6537 command->assignment_cnt, argv_expanded);
6538 }
6539
6540 if (command->group) {
6541 /* Cases when we are here:
6542 * ( list )
6543 * { list } &
6544 * ... | ( list ) | ...
6545 * ... | { list } | ...
6546 */
6547#if BB_MMU
6548 int rcode;
6549 debug_printf_exec("pseudo_exec: run_list\n");
6550 reset_traps_to_defaults();
6551 rcode = run_list(command->group);
6552 /* OK to leak memory by not calling free_pipe_list,
6553 * since this process is about to exit */
6554 _exit(rcode);
6555#else
6556 re_execute_shell(&nommu_save->argv_from_re_execing,
6557 command->group_as_string,
6558 G.global_argv[0],
6559 G.global_argv + 1,
6560 NULL);
6561#endif
6562 }
6563
6564 /* Case when we are here: ... | >file */
6565 debug_printf_exec("pseudo_exec'ed null command\n");
6566 _exit(EXIT_SUCCESS);
6567}
6568
6569#if ENABLE_HUSH_JOB
6570static const char *get_cmdtext(struct pipe *pi)
6571{
6572 char **argv;
6573 char *p;
6574 int len;
6575
6576 /* This is subtle. ->cmdtext is created only on first backgrounding.
6577 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6578 * On subsequent bg argv is trashed, but we won't use it */
6579 if (pi->cmdtext)
6580 return pi->cmdtext;
6581 argv = pi->cmds[0].argv;
6582 if (!argv || !argv[0]) {
6583 pi->cmdtext = xzalloc(1);
6584 return pi->cmdtext;
6585 }
6586
6587 len = 0;
6588 do {
6589 len += strlen(*argv) + 1;
6590 } while (*++argv);
6591 p = xmalloc(len);
6592 pi->cmdtext = p;
6593 argv = pi->cmds[0].argv;
6594 do {
6595 len = strlen(*argv);
6596 memcpy(p, *argv, len);
6597 p += len;
6598 *p++ = ' ';
6599 } while (*++argv);
6600 p[-1] = '\0';
6601 return pi->cmdtext;
6602}
6603
6604static void insert_bg_job(struct pipe *pi)
6605{
6606 struct pipe *job, **jobp;
6607 int i;
6608
6609 /* Linear search for the ID of the job to use */
6610 pi->jobid = 1;
6611 for (job = G.job_list; job; job = job->next)
6612 if (job->jobid >= pi->jobid)
6613 pi->jobid = job->jobid + 1;
6614
6615 /* Add job to the list of running jobs */
6616 jobp = &G.job_list;
6617 while ((job = *jobp) != NULL)
6618 jobp = &job->next;
6619 job = *jobp = xmalloc(sizeof(*job));
6620
6621 *job = *pi; /* physical copy */
6622 job->next = NULL;
6623 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6624 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6625 for (i = 0; i < pi->num_cmds; i++) {
6626 job->cmds[i].pid = pi->cmds[i].pid;
6627 /* all other fields are not used and stay zero */
6628 }
6629 job->cmdtext = xstrdup(get_cmdtext(pi));
6630
6631 if (G_interactive_fd)
6632 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6633 G.last_jobid = job->jobid;
6634}
6635
6636static void remove_bg_job(struct pipe *pi)
6637{
6638 struct pipe *prev_pipe;
6639
6640 if (pi == G.job_list) {
6641 G.job_list = pi->next;
6642 } else {
6643 prev_pipe = G.job_list;
6644 while (prev_pipe->next != pi)
6645 prev_pipe = prev_pipe->next;
6646 prev_pipe->next = pi->next;
6647 }
6648 if (G.job_list)
6649 G.last_jobid = G.job_list->jobid;
6650 else
6651 G.last_jobid = 0;
6652}
6653
6654/* Remove a backgrounded job */
6655static void delete_finished_bg_job(struct pipe *pi)
6656{
6657 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006658 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006659}
6660#endif /* JOB */
6661
6662/* Check to see if any processes have exited -- if they
6663 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006664static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006665{
6666 int attributes;
6667 int status;
6668#if ENABLE_HUSH_JOB
6669 struct pipe *pi;
6670#endif
6671 pid_t childpid;
6672 int rcode = 0;
6673
6674 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6675
6676 attributes = WUNTRACED;
6677 if (fg_pipe == NULL)
6678 attributes |= WNOHANG;
6679
6680 errno = 0;
6681#if ENABLE_HUSH_FAST
6682 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6683//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6684//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6685 /* There was neither fork nor SIGCHLD since last waitpid */
6686 /* Avoid doing waitpid syscall if possible */
6687 if (!G.we_have_children) {
6688 errno = ECHILD;
6689 return -1;
6690 }
6691 if (fg_pipe == NULL) { /* is WNOHANG set? */
6692 /* We have children, but they did not exit
6693 * or stop yet (we saw no SIGCHLD) */
6694 return 0;
6695 }
6696 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6697 }
6698#endif
6699
6700/* Do we do this right?
6701 * bash-3.00# sleep 20 | false
6702 * <ctrl-Z pressed>
6703 * [3]+ Stopped sleep 20 | false
6704 * bash-3.00# echo $?
6705 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6706 * [hush 1.14.0: yes we do it right]
6707 */
6708 wait_more:
6709 while (1) {
6710 int i;
6711 int dead;
6712
6713#if ENABLE_HUSH_FAST
6714 i = G.count_SIGCHLD;
6715#endif
6716 childpid = waitpid(-1, &status, attributes);
6717 if (childpid <= 0) {
6718 if (childpid && errno != ECHILD)
6719 bb_perror_msg("waitpid");
6720#if ENABLE_HUSH_FAST
6721 else { /* Until next SIGCHLD, waitpid's are useless */
6722 G.we_have_children = (childpid == 0);
6723 G.handled_SIGCHLD = i;
6724//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6725 }
6726#endif
6727 break;
6728 }
6729 dead = WIFEXITED(status) || WIFSIGNALED(status);
6730
6731#if DEBUG_JOBS
6732 if (WIFSTOPPED(status))
6733 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6734 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6735 if (WIFSIGNALED(status))
6736 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6737 childpid, WTERMSIG(status), WEXITSTATUS(status));
6738 if (WIFEXITED(status))
6739 debug_printf_jobs("pid %d exited, exitcode %d\n",
6740 childpid, WEXITSTATUS(status));
6741#endif
6742 /* Were we asked to wait for fg pipe? */
6743 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006744 i = fg_pipe->num_cmds;
6745 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006746 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6747 if (fg_pipe->cmds[i].pid != childpid)
6748 continue;
6749 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006750 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006751 fg_pipe->cmds[i].pid = 0;
6752 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006753 ex = WEXITSTATUS(status);
6754 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006755 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006756 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6757 */
6758 if (WIFSIGNALED(status)) {
6759 int sig = WTERMSIG(status);
6760 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006761 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6762 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6763 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006764 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6765 * Maybe we need to use sig | 128? */
6766 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006767 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006768 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006769 } else {
6770 fg_pipe->cmds[i].is_stopped = 1;
6771 fg_pipe->stopped_cmds++;
6772 }
6773 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6774 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006775 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006776 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006777 i = fg_pipe->num_cmds;
6778 while (--i >= 0) {
6779 rcode = fg_pipe->cmds[i].cmd_exitcode;
6780 /* usually last process gives overall exitstatus,
6781 * but with "set -o pipefail", last *failed* process does */
6782 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6783 break;
6784 }
6785 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006786/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6787 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6788 * and "killall -STOP cat" */
6789 if (G_interactive_fd) {
6790#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006791 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006792 insert_bg_job(fg_pipe);
6793#endif
6794 return rcode;
6795 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006796 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006797 return rcode;
6798 }
6799 /* There are still running processes in the fg pipe */
6800 goto wait_more; /* do waitpid again */
6801 }
6802 /* it wasnt fg_pipe, look for process in bg pipes */
6803 }
6804
6805#if ENABLE_HUSH_JOB
6806 /* We asked to wait for bg or orphaned children */
6807 /* No need to remember exitcode in this case */
6808 for (pi = G.job_list; pi; pi = pi->next) {
6809 for (i = 0; i < pi->num_cmds; i++) {
6810 if (pi->cmds[i].pid == childpid)
6811 goto found_pi_and_prognum;
6812 }
6813 }
6814 /* Happens when shell is used as init process (init=/bin/sh) */
6815 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6816 continue; /* do waitpid again */
6817
6818 found_pi_and_prognum:
6819 if (dead) {
6820 /* child exited */
6821 pi->cmds[i].pid = 0;
6822 pi->alive_cmds--;
6823 if (!pi->alive_cmds) {
6824 if (G_interactive_fd)
6825 printf(JOB_STATUS_FORMAT, pi->jobid,
6826 "Done", pi->cmdtext);
6827 delete_finished_bg_job(pi);
6828 }
6829 } else {
6830 /* child stopped */
6831 pi->cmds[i].is_stopped = 1;
6832 pi->stopped_cmds++;
6833 }
6834#endif
6835 } /* while (waitpid succeeds)... */
6836
6837 return rcode;
6838}
6839
6840#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006841static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006842{
6843 pid_t p;
6844 int rcode = checkjobs(fg_pipe);
6845 if (G_saved_tty_pgrp) {
6846 /* Job finished, move the shell to the foreground */
6847 p = getpgrp(); /* our process group id */
6848 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6849 tcsetpgrp(G_interactive_fd, p);
6850 }
6851 return rcode;
6852}
6853#endif
6854
6855/* Start all the jobs, but don't wait for anything to finish.
6856 * See checkjobs().
6857 *
6858 * Return code is normally -1, when the caller has to wait for children
6859 * to finish to determine the exit status of the pipe. If the pipe
6860 * is a simple builtin command, however, the action is done by the
6861 * time run_pipe returns, and the exit code is provided as the
6862 * return value.
6863 *
6864 * Returns -1 only if started some children. IOW: we have to
6865 * mask out retvals of builtins etc with 0xff!
6866 *
6867 * The only case when we do not need to [v]fork is when the pipe
6868 * is single, non-backgrounded, non-subshell command. Examples:
6869 * cmd ; ... { list } ; ...
6870 * cmd && ... { list } && ...
6871 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006872 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006873 * or (if SH_STANDALONE) an applet, and we can run the { list }
6874 * with run_list. If it isn't one of these, we fork and exec cmd.
6875 *
6876 * Cases when we must fork:
6877 * non-single: cmd | cmd
6878 * backgrounded: cmd & { list } &
6879 * subshell: ( list ) [&]
6880 */
6881#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006882#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006883 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6884#endif
6885static int redirect_and_varexp_helper(char ***new_env_p,
6886 struct variable **old_vars_p,
6887 struct command *command,
6888 int squirrel[3],
6889 char **argv_expanded)
6890{
6891 /* setup_redirects acts on file descriptors, not FILEs.
6892 * This is perfect for work that comes after exec().
6893 * Is it really safe for inline use? Experimentally,
6894 * things seem to work. */
6895 int rcode = setup_redirects(command, squirrel);
6896 if (rcode == 0) {
6897 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6898 *new_env_p = new_env;
6899 dump_cmd_in_x_mode(new_env);
6900 dump_cmd_in_x_mode(argv_expanded);
6901 if (old_vars_p)
6902 *old_vars_p = set_vars_and_save_old(new_env);
6903 }
6904 return rcode;
6905}
6906static NOINLINE int run_pipe(struct pipe *pi)
6907{
6908 static const char *const null_ptr = NULL;
6909
6910 int cmd_no;
6911 int next_infd;
6912 struct command *command;
6913 char **argv_expanded;
6914 char **argv;
6915 /* it is not always needed, but we aim to smaller code */
6916 int squirrel[] = { -1, -1, -1 };
6917 int rcode;
6918
6919 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6920 debug_enter();
6921
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006922 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6923 * Result should be 3 lines: q w e, qwe, q w e
6924 */
6925 G.ifs = get_local_var_value("IFS");
6926 if (!G.ifs)
6927 G.ifs = defifs;
6928
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006929 IF_HUSH_JOB(pi->pgrp = -1;)
6930 pi->stopped_cmds = 0;
6931 command = &pi->cmds[0];
6932 argv_expanded = NULL;
6933
6934 if (pi->num_cmds != 1
6935 || pi->followup == PIPE_BG
6936 || command->cmd_type == CMD_SUBSHELL
6937 ) {
6938 goto must_fork;
6939 }
6940
6941 pi->alive_cmds = 1;
6942
6943 debug_printf_exec(": group:%p argv:'%s'\n",
6944 command->group, command->argv ? command->argv[0] : "NONE");
6945
6946 if (command->group) {
6947#if ENABLE_HUSH_FUNCTIONS
6948 if (command->cmd_type == CMD_FUNCDEF) {
6949 /* "executing" func () { list } */
6950 struct function *funcp;
6951
6952 funcp = new_function(command->argv[0]);
6953 /* funcp->name is already set to argv[0] */
6954 funcp->body = command->group;
6955# if !BB_MMU
6956 funcp->body_as_string = command->group_as_string;
6957 command->group_as_string = NULL;
6958# endif
6959 command->group = NULL;
6960 command->argv[0] = NULL;
6961 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6962 funcp->parent_cmd = command;
6963 command->child_func = funcp;
6964
6965 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6966 debug_leave();
6967 return EXIT_SUCCESS;
6968 }
6969#endif
6970 /* { list } */
6971 debug_printf("non-subshell group\n");
6972 rcode = 1; /* exitcode if redir failed */
6973 if (setup_redirects(command, squirrel) == 0) {
6974 debug_printf_exec(": run_list\n");
6975 rcode = run_list(command->group) & 0xff;
6976 }
6977 restore_redirects(squirrel);
6978 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6979 debug_leave();
6980 debug_printf_exec("run_pipe: return %d\n", rcode);
6981 return rcode;
6982 }
6983
6984 argv = command->argv ? command->argv : (char **) &null_ptr;
6985 {
6986 const struct built_in_command *x;
6987#if ENABLE_HUSH_FUNCTIONS
6988 const struct function *funcp;
6989#else
6990 enum { funcp = 0 };
6991#endif
6992 char **new_env = NULL;
6993 struct variable *old_vars = NULL;
6994
6995 if (argv[command->assignment_cnt] == NULL) {
6996 /* Assignments, but no command */
6997 /* Ensure redirects take effect (that is, create files).
6998 * Try "a=t >file" */
6999#if 0 /* A few cases in testsuite fail with this code. FIXME */
7000 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7001 /* Set shell variables */
7002 if (new_env) {
7003 argv = new_env;
7004 while (*argv) {
7005 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7006 /* Do we need to flag set_local_var() errors?
7007 * "assignment to readonly var" and "putenv error"
7008 */
7009 argv++;
7010 }
7011 }
7012 /* Redirect error sets $? to 1. Otherwise,
7013 * if evaluating assignment value set $?, retain it.
7014 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7015 if (rcode == 0)
7016 rcode = G.last_exitcode;
7017 /* Exit, _skipping_ variable restoring code: */
7018 goto clean_up_and_ret0;
7019
7020#else /* Older, bigger, but more correct code */
7021
7022 rcode = setup_redirects(command, squirrel);
7023 restore_redirects(squirrel);
7024 /* Set shell variables */
7025 if (G_x_mode)
7026 bb_putchar_stderr('+');
7027 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007028 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007029 if (G_x_mode)
7030 fprintf(stderr, " %s", p);
7031 debug_printf_exec("set shell var:'%s'->'%s'\n",
7032 *argv, p);
7033 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7034 /* Do we need to flag set_local_var() errors?
7035 * "assignment to readonly var" and "putenv error"
7036 */
7037 argv++;
7038 }
7039 if (G_x_mode)
7040 bb_putchar_stderr('\n');
7041 /* Redirect error sets $? to 1. Otherwise,
7042 * if evaluating assignment value set $?, retain it.
7043 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7044 if (rcode == 0)
7045 rcode = G.last_exitcode;
7046 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7047 debug_leave();
7048 debug_printf_exec("run_pipe: return %d\n", rcode);
7049 return rcode;
7050#endif
7051 }
7052
7053 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007054#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007055 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007056 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007057 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007058#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007059 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007060 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7061 }
7062
7063 /* if someone gives us an empty string: `cmd with empty output` */
7064 if (!argv_expanded[0]) {
7065 free(argv_expanded);
7066 debug_leave();
7067 return G.last_exitcode;
7068 }
7069
7070 x = find_builtin(argv_expanded[0]);
7071#if ENABLE_HUSH_FUNCTIONS
7072 funcp = NULL;
7073 if (!x)
7074 funcp = find_function(argv_expanded[0]);
7075#endif
7076 if (x || funcp) {
7077 if (!funcp) {
7078 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7079 debug_printf("exec with redirects only\n");
7080 rcode = setup_redirects(command, NULL);
7081 goto clean_up_and_ret1;
7082 }
7083 }
7084 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7085 if (rcode == 0) {
7086 if (!funcp) {
7087 debug_printf_exec(": builtin '%s' '%s'...\n",
7088 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007089 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007090 rcode = x->b_function(argv_expanded) & 0xff;
7091 fflush_all();
7092 }
7093#if ENABLE_HUSH_FUNCTIONS
7094 else {
7095# if ENABLE_HUSH_LOCAL
7096 struct variable **sv;
7097 sv = G.shadowed_vars_pp;
7098 G.shadowed_vars_pp = &old_vars;
7099# endif
7100 debug_printf_exec(": function '%s' '%s'...\n",
7101 funcp->name, argv_expanded[1]);
7102 rcode = run_function(funcp, argv_expanded) & 0xff;
7103# if ENABLE_HUSH_LOCAL
7104 G.shadowed_vars_pp = sv;
7105# endif
7106 }
7107#endif
7108 }
7109 clean_up_and_ret:
7110 unset_vars(new_env);
7111 add_vars(old_vars);
7112/* clean_up_and_ret0: */
7113 restore_redirects(squirrel);
7114 clean_up_and_ret1:
7115 free(argv_expanded);
7116 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7117 debug_leave();
7118 debug_printf_exec("run_pipe return %d\n", rcode);
7119 return rcode;
7120 }
7121
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007122 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007123 int n = find_applet_by_name(argv_expanded[0]);
7124 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7125 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7126 if (rcode == 0) {
7127 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7128 argv_expanded[0], argv_expanded[1]);
7129 rcode = run_nofork_applet(n, argv_expanded);
7130 }
7131 goto clean_up_and_ret;
7132 }
7133 }
7134 /* It is neither builtin nor applet. We must fork. */
7135 }
7136
7137 must_fork:
7138 /* NB: argv_expanded may already be created, and that
7139 * might include `cmd` runs! Do not rerun it! We *must*
7140 * use argv_expanded if it's non-NULL */
7141
7142 /* Going to fork a child per each pipe member */
7143 pi->alive_cmds = 0;
7144 next_infd = 0;
7145
7146 cmd_no = 0;
7147 while (cmd_no < pi->num_cmds) {
7148 struct fd_pair pipefds;
7149#if !BB_MMU
7150 volatile nommu_save_t nommu_save;
7151 nommu_save.new_env = NULL;
7152 nommu_save.old_vars = NULL;
7153 nommu_save.argv = NULL;
7154 nommu_save.argv_from_re_execing = NULL;
7155#endif
7156 command = &pi->cmds[cmd_no];
7157 cmd_no++;
7158 if (command->argv) {
7159 debug_printf_exec(": pipe member '%s' '%s'...\n",
7160 command->argv[0], command->argv[1]);
7161 } else {
7162 debug_printf_exec(": pipe member with no argv\n");
7163 }
7164
7165 /* pipes are inserted between pairs of commands */
7166 pipefds.rd = 0;
7167 pipefds.wr = 1;
7168 if (cmd_no < pi->num_cmds)
7169 xpiped_pair(pipefds);
7170
7171 command->pid = BB_MMU ? fork() : vfork();
7172 if (!command->pid) { /* child */
7173#if ENABLE_HUSH_JOB
7174 disable_restore_tty_pgrp_on_exit();
7175 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7176
7177 /* Every child adds itself to new process group
7178 * with pgid == pid_of_first_child_in_pipe */
7179 if (G.run_list_level == 1 && G_interactive_fd) {
7180 pid_t pgrp;
7181 pgrp = pi->pgrp;
7182 if (pgrp < 0) /* true for 1st process only */
7183 pgrp = getpid();
7184 if (setpgid(0, pgrp) == 0
7185 && pi->followup != PIPE_BG
7186 && G_saved_tty_pgrp /* we have ctty */
7187 ) {
7188 /* We do it in *every* child, not just first,
7189 * to avoid races */
7190 tcsetpgrp(G_interactive_fd, pgrp);
7191 }
7192 }
7193#endif
7194 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7195 /* 1st cmd in backgrounded pipe
7196 * should have its stdin /dev/null'ed */
7197 close(0);
7198 if (open(bb_dev_null, O_RDONLY))
7199 xopen("/", O_RDONLY);
7200 } else {
7201 xmove_fd(next_infd, 0);
7202 }
7203 xmove_fd(pipefds.wr, 1);
7204 if (pipefds.rd > 1)
7205 close(pipefds.rd);
7206 /* Like bash, explicit redirects override pipes,
7207 * and the pipe fd is available for dup'ing. */
7208 if (setup_redirects(command, NULL))
7209 _exit(1);
7210
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007211 /* Stores to nommu_save list of env vars putenv'ed
7212 * (NOMMU, on MMU we don't need that) */
7213 /* cast away volatility... */
7214 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7215 /* pseudo_exec() does not return */
7216 }
7217
7218 /* parent or error */
7219#if ENABLE_HUSH_FAST
7220 G.count_SIGCHLD++;
7221//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7222#endif
7223 enable_restore_tty_pgrp_on_exit();
7224#if !BB_MMU
7225 /* Clean up after vforked child */
7226 free(nommu_save.argv);
7227 free(nommu_save.argv_from_re_execing);
7228 unset_vars(nommu_save.new_env);
7229 add_vars(nommu_save.old_vars);
7230#endif
7231 free(argv_expanded);
7232 argv_expanded = NULL;
7233 if (command->pid < 0) { /* [v]fork failed */
7234 /* Clearly indicate, was it fork or vfork */
7235 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7236 } else {
7237 pi->alive_cmds++;
7238#if ENABLE_HUSH_JOB
7239 /* Second and next children need to know pid of first one */
7240 if (pi->pgrp < 0)
7241 pi->pgrp = command->pid;
7242#endif
7243 }
7244
7245 if (cmd_no > 1)
7246 close(next_infd);
7247 if (cmd_no < pi->num_cmds)
7248 close(pipefds.wr);
7249 /* Pass read (output) pipe end to next iteration */
7250 next_infd = pipefds.rd;
7251 }
7252
7253 if (!pi->alive_cmds) {
7254 debug_leave();
7255 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7256 return 1;
7257 }
7258
7259 debug_leave();
7260 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7261 return -1;
7262}
7263
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007264/* NB: called by pseudo_exec, and therefore must not modify any
7265 * global data until exec/_exit (we can be a child after vfork!) */
7266static int run_list(struct pipe *pi)
7267{
7268#if ENABLE_HUSH_CASE
7269 char *case_word = NULL;
7270#endif
7271#if ENABLE_HUSH_LOOPS
7272 struct pipe *loop_top = NULL;
7273 char **for_lcur = NULL;
7274 char **for_list = NULL;
7275#endif
7276 smallint last_followup;
7277 smalluint rcode;
7278#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7279 smalluint cond_code = 0;
7280#else
7281 enum { cond_code = 0 };
7282#endif
7283#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007284 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007285 smallint last_rword; /* ditto */
7286#endif
7287
7288 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7289 debug_enter();
7290
7291#if ENABLE_HUSH_LOOPS
7292 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007293 {
7294 struct pipe *cpipe;
7295 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7296 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7297 continue;
7298 /* current word is FOR or IN (BOLD in comments below) */
7299 if (cpipe->next == NULL) {
7300 syntax_error("malformed for");
7301 debug_leave();
7302 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7303 return 1;
7304 }
7305 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7306 if (cpipe->next->res_word == RES_DO)
7307 continue;
7308 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7309 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7310 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7311 ) {
7312 syntax_error("malformed for");
7313 debug_leave();
7314 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7315 return 1;
7316 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007317 }
7318 }
7319#endif
7320
7321 /* Past this point, all code paths should jump to ret: label
7322 * in order to return, no direct "return" statements please.
7323 * This helps to ensure that no memory is leaked. */
7324
7325#if ENABLE_HUSH_JOB
7326 G.run_list_level++;
7327#endif
7328
7329#if HAS_KEYWORDS
7330 rword = RES_NONE;
7331 last_rword = RES_XXXX;
7332#endif
7333 last_followup = PIPE_SEQ;
7334 rcode = G.last_exitcode;
7335
7336 /* Go through list of pipes, (maybe) executing them. */
7337 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7338 if (G.flag_SIGINT)
7339 break;
7340
7341 IF_HAS_KEYWORDS(rword = pi->res_word;)
7342 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7343 rword, cond_code, last_rword);
7344#if ENABLE_HUSH_LOOPS
7345 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7346 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7347 ) {
7348 /* start of a loop: remember where loop starts */
7349 loop_top = pi;
7350 G.depth_of_loop++;
7351 }
7352#endif
7353 /* Still in the same "if...", "then..." or "do..." branch? */
7354 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7355 if ((rcode == 0 && last_followup == PIPE_OR)
7356 || (rcode != 0 && last_followup == PIPE_AND)
7357 ) {
7358 /* It is "<true> || CMD" or "<false> && CMD"
7359 * and we should not execute CMD */
7360 debug_printf_exec("skipped cmd because of || or &&\n");
7361 last_followup = pi->followup;
7362 continue;
7363 }
7364 }
7365 last_followup = pi->followup;
7366 IF_HAS_KEYWORDS(last_rword = rword;)
7367#if ENABLE_HUSH_IF
7368 if (cond_code) {
7369 if (rword == RES_THEN) {
7370 /* if false; then ... fi has exitcode 0! */
7371 G.last_exitcode = rcode = EXIT_SUCCESS;
7372 /* "if <false> THEN cmd": skip cmd */
7373 continue;
7374 }
7375 } else {
7376 if (rword == RES_ELSE || rword == RES_ELIF) {
7377 /* "if <true> then ... ELSE/ELIF cmd":
7378 * skip cmd and all following ones */
7379 break;
7380 }
7381 }
7382#endif
7383#if ENABLE_HUSH_LOOPS
7384 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7385 if (!for_lcur) {
7386 /* first loop through for */
7387
7388 static const char encoded_dollar_at[] ALIGN1 = {
7389 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7390 }; /* encoded representation of "$@" */
7391 static const char *const encoded_dollar_at_argv[] = {
7392 encoded_dollar_at, NULL
7393 }; /* argv list with one element: "$@" */
7394 char **vals;
7395
7396 vals = (char**)encoded_dollar_at_argv;
7397 if (pi->next->res_word == RES_IN) {
7398 /* if no variable values after "in" we skip "for" */
7399 if (!pi->next->cmds[0].argv) {
7400 G.last_exitcode = rcode = EXIT_SUCCESS;
7401 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7402 break;
7403 }
7404 vals = pi->next->cmds[0].argv;
7405 } /* else: "for var; do..." -> assume "$@" list */
7406 /* create list of variable values */
7407 debug_print_strings("for_list made from", vals);
7408 for_list = expand_strvec_to_strvec(vals);
7409 for_lcur = for_list;
7410 debug_print_strings("for_list", for_list);
7411 }
7412 if (!*for_lcur) {
7413 /* "for" loop is over, clean up */
7414 free(for_list);
7415 for_list = NULL;
7416 for_lcur = NULL;
7417 break;
7418 }
7419 /* Insert next value from for_lcur */
7420 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7421 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7422 continue;
7423 }
7424 if (rword == RES_IN) {
7425 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7426 }
7427 if (rword == RES_DONE) {
7428 continue; /* "done" has no cmds too */
7429 }
7430#endif
7431#if ENABLE_HUSH_CASE
7432 if (rword == RES_CASE) {
7433 case_word = expand_strvec_to_string(pi->cmds->argv);
7434 continue;
7435 }
7436 if (rword == RES_MATCH) {
7437 char **argv;
7438
7439 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7440 break;
7441 /* all prev words didn't match, does this one match? */
7442 argv = pi->cmds->argv;
7443 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007444 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007445 /* TODO: which FNM_xxx flags to use? */
7446 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7447 free(pattern);
7448 if (cond_code == 0) { /* match! we will execute this branch */
7449 free(case_word); /* make future "word)" stop */
7450 case_word = NULL;
7451 break;
7452 }
7453 argv++;
7454 }
7455 continue;
7456 }
7457 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7458 if (cond_code != 0)
7459 continue; /* not matched yet, skip this pipe */
7460 }
7461#endif
7462 /* Just pressing <enter> in shell should check for jobs.
7463 * OTOH, in non-interactive shell this is useless
7464 * and only leads to extra job checks */
7465 if (pi->num_cmds == 0) {
7466 if (G_interactive_fd)
7467 goto check_jobs_and_continue;
7468 continue;
7469 }
7470
7471 /* After analyzing all keywords and conditions, we decided
7472 * to execute this pipe. NB: have to do checkjobs(NULL)
7473 * after run_pipe to collect any background children,
7474 * even if list execution is to be stopped. */
7475 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7476 {
7477 int r;
7478#if ENABLE_HUSH_LOOPS
7479 G.flag_break_continue = 0;
7480#endif
7481 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7482 if (r != -1) {
7483 /* We ran a builtin, function, or group.
7484 * rcode is already known
7485 * and we don't need to wait for anything. */
7486 G.last_exitcode = rcode;
7487 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007488 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007489#if ENABLE_HUSH_LOOPS
7490 /* Was it "break" or "continue"? */
7491 if (G.flag_break_continue) {
7492 smallint fbc = G.flag_break_continue;
7493 /* We might fall into outer *loop*,
7494 * don't want to break it too */
7495 if (loop_top) {
7496 G.depth_break_continue--;
7497 if (G.depth_break_continue == 0)
7498 G.flag_break_continue = 0;
7499 /* else: e.g. "continue 2" should *break* once, *then* continue */
7500 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7501 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7502 goto check_jobs_and_break;
7503 /* "continue": simulate end of loop */
7504 rword = RES_DONE;
7505 continue;
7506 }
7507#endif
7508#if ENABLE_HUSH_FUNCTIONS
7509 if (G.flag_return_in_progress == 1) {
7510 /* same as "goto check_jobs_and_break" */
7511 checkjobs(NULL);
7512 break;
7513 }
7514#endif
7515 } else if (pi->followup == PIPE_BG) {
7516 /* What does bash do with attempts to background builtins? */
7517 /* even bash 3.2 doesn't do that well with nested bg:
7518 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7519 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007520 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007521#if ENABLE_HUSH_JOB
7522 if (G.run_list_level == 1)
7523 insert_bg_job(pi);
7524#endif
7525 /* Last command's pid goes to $! */
7526 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7527 G.last_exitcode = rcode = EXIT_SUCCESS;
7528 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7529 } else {
7530#if ENABLE_HUSH_JOB
7531 if (G.run_list_level == 1 && G_interactive_fd) {
7532 /* Waits for completion, then fg's main shell */
7533 rcode = checkjobs_and_fg_shell(pi);
7534 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007535 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007536 } else
7537#endif
7538 { /* This one just waits for completion */
7539 rcode = checkjobs(pi);
7540 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007541 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007542 }
7543 G.last_exitcode = rcode;
7544 }
7545 }
7546
7547 /* Analyze how result affects subsequent commands */
7548#if ENABLE_HUSH_IF
7549 if (rword == RES_IF || rword == RES_ELIF)
7550 cond_code = rcode;
7551#endif
7552#if ENABLE_HUSH_LOOPS
7553 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007554 if (pi->next
7555 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02007556 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007557 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007558 if (rword == RES_WHILE) {
7559 if (rcode) {
7560 /* "while false; do...done" - exitcode 0 */
7561 G.last_exitcode = rcode = EXIT_SUCCESS;
7562 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7563 goto check_jobs_and_break;
7564 }
7565 }
7566 if (rword == RES_UNTIL) {
7567 if (!rcode) {
7568 debug_printf_exec(": until expr is true: breaking\n");
7569 check_jobs_and_break:
7570 checkjobs(NULL);
7571 break;
7572 }
7573 }
7574 }
7575#endif
7576
7577 check_jobs_and_continue:
7578 checkjobs(NULL);
7579 } /* for (pi) */
7580
7581#if ENABLE_HUSH_JOB
7582 G.run_list_level--;
7583#endif
7584#if ENABLE_HUSH_LOOPS
7585 if (loop_top)
7586 G.depth_of_loop--;
7587 free(for_list);
7588#endif
7589#if ENABLE_HUSH_CASE
7590 free(case_word);
7591#endif
7592 debug_leave();
7593 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7594 return rcode;
7595}
7596
7597/* Select which version we will use */
7598static int run_and_free_list(struct pipe *pi)
7599{
7600 int rcode = 0;
7601 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007602 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007603 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7604 rcode = run_list(pi);
7605 }
7606 /* free_pipe_list has the side effect of clearing memory.
7607 * In the long run that function can be merged with run_list,
7608 * but doing that now would hobble the debugging effort. */
7609 free_pipe_list(pi);
7610 debug_printf_exec("run_and_free_list return %d\n", rcode);
7611 return rcode;
7612}
7613
7614
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007615static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007616{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007617 sighandler_t old_handler;
7618 unsigned sig = 0;
7619 while ((mask >>= 1) != 0) {
7620 sig++;
7621 if (!(mask & 1))
7622 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007623 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007624 /* POSIX allows shell to re-enable SIGCHLD
7625 * even if it was SIG_IGN on entry.
7626 * Therefore we skip IGN check for it:
7627 */
7628 if (sig == SIGCHLD)
7629 continue;
7630 if (old_handler == SIG_IGN) {
7631 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007632 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007633 if (!G.traps)
7634 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7635 free(G.traps[sig]);
7636 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7637 }
7638 }
7639}
7640
7641/* Called a few times only (or even once if "sh -c") */
7642static void install_special_sighandlers(void)
7643{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007644 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007645
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007646 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007647 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007648 if (G_interactive_fd) {
7649 mask |= SPECIAL_INTERACTIVE_SIGS;
7650 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007651 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007652 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007653 /* Careful, do not re-install handlers we already installed */
7654 if (G.special_sig_mask != mask) {
7655 unsigned diff = mask & ~G.special_sig_mask;
7656 G.special_sig_mask = mask;
7657 install_sighandlers(diff);
7658 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007659}
7660
7661#if ENABLE_HUSH_JOB
7662/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007663/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007664static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007665{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007666 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007667
7668 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007669 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007670 + (1 << SIGILL ) * HUSH_DEBUG
7671 + (1 << SIGFPE ) * HUSH_DEBUG
7672 + (1 << SIGBUS ) * HUSH_DEBUG
7673 + (1 << SIGSEGV) * HUSH_DEBUG
7674 + (1 << SIGTRAP) * HUSH_DEBUG
7675 + (1 << SIGABRT)
7676 /* bash 3.2 seems to handle these just like 'fatal' ones */
7677 + (1 << SIGPIPE)
7678 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007679 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007680 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007681 * we never want to restore pgrp on exit, and this fn is not called
7682 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007683 /*+ (1 << SIGHUP )*/
7684 /*+ (1 << SIGTERM)*/
7685 /*+ (1 << SIGINT )*/
7686 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007687 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007688
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007689 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007690}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007691#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007692
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007693static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007694{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007695 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007696 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007697 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007698 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007699 break;
7700 case 'x':
7701 IF_HUSH_MODE_X(G_x_mode = state;)
7702 break;
7703 case 'o':
7704 if (!o_opt) {
7705 /* "set -+o" without parameter.
7706 * in bash, set -o produces this output:
7707 * pipefail off
7708 * and set +o:
7709 * set +o pipefail
7710 * We always use the second form.
7711 */
7712 const char *p = o_opt_strings;
7713 idx = 0;
7714 while (*p) {
7715 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7716 idx++;
7717 p += strlen(p) + 1;
7718 }
7719 break;
7720 }
7721 idx = index_in_strings(o_opt_strings, o_opt);
7722 if (idx >= 0) {
7723 G.o_opt[idx] = state;
7724 break;
7725 }
7726 default:
7727 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007728 }
7729 return EXIT_SUCCESS;
7730}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007731
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007732int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007733int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007734{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007735 enum {
7736 OPT_login = (1 << 0),
7737 };
7738 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00007739 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007740 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007741 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007742 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007743 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007744
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007745 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02007746 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007747 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenko10c01312011-05-11 11:49:21 +02007748#if ENABLE_HUSH_FAST
7749 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7750#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007751#if !BB_MMU
7752 G.argv0_for_re_execing = argv[0];
7753#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007754 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007755 shell_ver = xzalloc(sizeof(*shell_ver));
7756 shell_ver->flg_export = 1;
7757 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007758 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007759 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007760 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007761 /* Create shell local variables from the values
7762 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007763 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007764 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007765 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007766 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007767 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007768 if (e) while (*e) {
7769 char *value = strchr(*e, '=');
7770 if (value) { /* paranoia */
7771 cur_var->next = xzalloc(sizeof(*cur_var));
7772 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007773 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007774 cur_var->max_len = strlen(*e);
7775 cur_var->flg_export = 1;
7776 }
7777 e++;
7778 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007779 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007780 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7781 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007782
7783 /* Export PWD */
7784 set_pwd_var(/*exp:*/ 1);
7785 /* bash also exports SHLVL and _,
7786 * and sets (but doesn't export) the following variables:
7787 * BASH=/bin/bash
7788 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7789 * BASH_VERSION='3.2.0(1)-release'
7790 * HOSTTYPE=i386
7791 * MACHTYPE=i386-pc-linux-gnu
7792 * OSTYPE=linux-gnu
7793 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007794 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007795 * EUID=<NNNNN>
7796 * UID=<NNNNN>
7797 * GROUPS=()
7798 * LINES=<NNN>
7799 * COLUMNS=<NNN>
7800 * BASH_ARGC=()
7801 * BASH_ARGV=()
7802 * BASH_LINENO=()
7803 * BASH_SOURCE=()
7804 * DIRSTACK=()
7805 * PIPESTATUS=([0]="0")
7806 * HISTFILE=/<xxx>/.bash_history
7807 * HISTFILESIZE=500
7808 * HISTSIZE=500
7809 * MAILCHECK=60
7810 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7811 * SHELL=/bin/bash
7812 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7813 * TERM=dumb
7814 * OPTERR=1
7815 * OPTIND=1
7816 * IFS=$' \t\n'
7817 * PS1='\s-\v\$ '
7818 * PS2='> '
7819 * PS4='+ '
7820 */
7821
Denis Vlasenko38f63192007-01-22 09:03:07 +00007822#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02007823 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007824#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007825
Eric Andersen94ac2442001-05-22 19:05:18 +00007826 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007827 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007828
Denis Vlasenkoed782372009-04-10 00:45:02 +00007829 if (setjmp(die_jmp)) {
7830 /* xfunc has failed! die die die */
7831 /* no EXIT traps, this is an escape hatch! */
7832 G.exiting = 1;
7833 hush_exit(xfunc_error_retval);
7834 }
7835
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007836 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007837 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007838 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007839 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007840 * in order to intercept (more) signals.
7841 */
7842
7843 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007844 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007845 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007846 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007847 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007848 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007849#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007850 "<:$:R:V:"
7851# if ENABLE_HUSH_FUNCTIONS
7852 "F:"
7853# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007854#endif
7855 );
7856 if (opt <= 0)
7857 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007858 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007859 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007860 /* Possibilities:
7861 * sh ... -c 'script'
7862 * sh ... -c 'script' ARG0 [ARG1...]
7863 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007864 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007865 * "" needs to be replaced with NULL
7866 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007867 * Note: the form without ARG0 never happens:
7868 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007869 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007870 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007871 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007872 G.root_ppid = getppid();
7873 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007874 G.global_argv = argv + optind;
7875 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007876 if (builtin_argc) {
7877 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7878 const struct built_in_command *x;
7879
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007880 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007881 x = find_builtin(optarg);
7882 if (x) { /* paranoia */
7883 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7884 G.global_argv += builtin_argc;
7885 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007886 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007887 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007888 }
7889 goto final_return;
7890 }
7891 if (!G.global_argv[0]) {
7892 /* -c 'script' (no params): prevent empty $0 */
7893 G.global_argv--; /* points to argv[i] of 'script' */
7894 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007895 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007896 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007897 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007898 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007899 goto final_return;
7900 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007901 /* Well, we cannot just declare interactiveness,
7902 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007903 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007904 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007905 case 's':
7906 /* "-s" means "read from stdin", but this is how we always
7907 * operate, so simply do nothing here. */
7908 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007909 case 'l':
7910 flags |= OPT_login;
7911 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007912#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007913 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007914 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007915 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007916 case '$': {
7917 unsigned long long empty_trap_mask;
7918
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007919 G.root_pid = bb_strtou(optarg, &optarg, 16);
7920 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007921 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7922 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007923 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7924 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007925 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007926 optarg++;
7927 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007928 optarg++;
7929 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7930 if (empty_trap_mask != 0) {
7931 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007932 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007933 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7934 for (sig = 1; sig < NSIG; sig++) {
7935 if (empty_trap_mask & (1LL << sig)) {
7936 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007937 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007938 }
7939 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007940 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007941# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007942 optarg++;
7943 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007944# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007945 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007946 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007947 case 'R':
7948 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007949 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007950 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007951# if ENABLE_HUSH_FUNCTIONS
7952 case 'F': {
7953 struct function *funcp = new_function(optarg);
7954 /* funcp->name is already set to optarg */
7955 /* funcp->body is set to NULL. It's a special case. */
7956 funcp->body_as_string = argv[optind];
7957 optind++;
7958 break;
7959 }
7960# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007961#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007962 case 'n':
7963 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007964 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007965 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007966 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007967#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007968 fprintf(stderr, "Usage: sh [FILE]...\n"
7969 " or: sh -c command [args]...\n\n");
7970 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007971#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007972 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007973#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007974 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007975 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007976
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007977 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7978 G.global_argc = argc - (optind - 1);
7979 G.global_argv = argv + (optind - 1);
7980 G.global_argv[0] = argv[0];
7981
Denys Vlasenkodea47882009-10-09 15:40:49 +02007982 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007983 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007984 G.root_ppid = getppid();
7985 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007986
7987 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007988 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007989 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007990 debug_printf("sourcing /etc/profile\n");
7991 input = fopen_for_read("/etc/profile");
7992 if (input != NULL) {
7993 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007994 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007995 parse_and_run_file(input);
7996 fclose(input);
7997 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007998 /* bash: after sourcing /etc/profile,
7999 * tries to source (in the given order):
8000 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008001 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008002 * bash also sources ~/.bash_logout on exit.
8003 * If called as sh, skips .bash_XXX files.
8004 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008005 }
8006
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008007 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008008 FILE *input;
8009 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008010 * "bash <script>" (which is never interactive (unless -i?))
8011 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008012 * If called as sh, does the same but with $ENV.
8013 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008014 G.global_argc--;
8015 G.global_argv++;
8016 debug_printf("running script '%s'\n", G.global_argv[0]);
8017 input = xfopen_for_read(G.global_argv[0]);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008018 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008019 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008020 parse_and_run_file(input);
8021#if ENABLE_FEATURE_CLEAN_UP
8022 fclose(input);
8023#endif
8024 goto final_return;
8025 }
8026
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008027 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008028 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008029 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008030
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008031 /* A shell is interactive if the '-i' flag was given,
8032 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008033 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008034 * no arguments remaining or the -s flag given
8035 * standard input is a terminal
8036 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008037 * Refer to Posix.2, the description of the 'sh' utility.
8038 */
8039#if ENABLE_HUSH_JOB
8040 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008041 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8042 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8043 if (G_saved_tty_pgrp < 0)
8044 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008045
8046 /* try to dup stdin to high fd#, >= 255 */
8047 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8048 if (G_interactive_fd < 0) {
8049 /* try to dup to any fd */
8050 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008051 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008052 /* give up */
8053 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008054 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008055 }
8056 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008057// TODO: track & disallow any attempts of user
8058// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008059 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008060 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008061 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008062 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008063
Mike Frysinger38478a62009-05-20 04:48:06 -04008064 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008065 /* If we were run as 'hush &', sleep until we are
8066 * in the foreground (tty pgrp == our pgrp).
8067 * If we get started under a job aware app (like bash),
8068 * make sure we are now in charge so we don't fight over
8069 * who gets the foreground */
8070 while (1) {
8071 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008072 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8073 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008074 break;
8075 /* send TTIN to ourself (should stop us) */
8076 kill(- shell_pgrp, SIGTTIN);
8077 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008078 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008079
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008080 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008081 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008082
Mike Frysinger38478a62009-05-20 04:48:06 -04008083 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008084 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008085 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008086 /* Put ourselves in our own process group
8087 * (bash, too, does this only if ctty is available) */
8088 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8089 /* Grab control of the terminal */
8090 tcsetpgrp(G_interactive_fd, getpid());
8091 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00008092 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00008093 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00008094 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008095
8096# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8097 {
8098 const char *hp = get_local_var_value("HISTFILE");
8099 if (!hp) {
8100 hp = get_local_var_value("HOME");
8101 if (hp)
8102 hp = concat_path_file(hp, ".hush_history");
8103 } else {
8104 hp = xstrdup(hp);
8105 }
8106 if (hp) {
8107 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008108 //set_local_var(xasprintf("HISTFILE=%s", ...));
8109 }
8110# if ENABLE_FEATURE_SH_HISTFILESIZE
8111 hp = get_local_var_value("HISTFILESIZE");
8112 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8113# endif
8114 }
8115# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008116 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008117 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008118 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008119#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008120 /* No job control compiled in, only prompt/line editing */
8121 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008122 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8123 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008124 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008125 G_interactive_fd = dup(STDIN_FILENO);
8126 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008127 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008128 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008129 }
8130 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008131 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008132 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008133 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008134 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008135#else
8136 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008137 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008138#endif
8139 /* bash:
8140 * if interactive but not a login shell, sources ~/.bashrc
8141 * (--norc turns this off, --rcfile <file> overrides)
8142 */
8143
8144 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008145 /* note: ash and hush share this string */
8146 printf("\n\n%s %s\n"
8147 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8148 "\n",
8149 bb_banner,
8150 "hush - the humble shell"
8151 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008152 }
8153
Denis Vlasenkof9375282009-04-05 19:13:39 +00008154 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008155
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008156 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008157 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008158}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008159
8160
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008161#if ENABLE_MSH
8162int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8163int msh_main(int argc, char **argv)
8164{
8165 //bb_error_msg("msh is deprecated, please use hush instead");
8166 return hush_main(argc, argv);
8167}
8168#endif
8169
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008170
8171/*
8172 * Built-ins
8173 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008174static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008175{
8176 return 0;
8177}
8178
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008179static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008180{
8181 int argc = 0;
8182 while (*argv) {
8183 argc++;
8184 argv++;
8185 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008186 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008187}
8188
8189static int FAST_FUNC builtin_test(char **argv)
8190{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008191 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008192}
8193
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008194static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008195{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008196 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008197}
8198
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008199#if ENABLE_PRINTF
8200static int FAST_FUNC builtin_printf(char **argv)
8201{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008202 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008203}
8204#endif
8205
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008206static char **skip_dash_dash(char **argv)
8207{
8208 argv++;
8209 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8210 argv++;
8211 return argv;
8212}
8213
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008214static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008215{
8216 int rcode = EXIT_SUCCESS;
8217
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008218 argv = skip_dash_dash(argv);
8219 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008220 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008221 /* bash:
8222 * eval "echo Hi; done" ("done" is syntax error):
8223 * "echo Hi" will not execute too.
8224 */
8225 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008226 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008227 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008228 }
8229 return rcode;
8230}
8231
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008232static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008233{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008234 const char *newdir;
8235
8236 argv = skip_dash_dash(argv);
8237 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008238 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008239 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008240 * bash says "bash: cd: HOME not set" and does nothing
8241 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008242 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008243 const char *home = get_local_var_value("HOME");
8244 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008245 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008246 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008247 /* Mimic bash message exactly */
8248 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008249 return EXIT_FAILURE;
8250 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008251 /* Read current dir (get_cwd(1) is inside) and set PWD.
8252 * Note: do not enforce exporting. If PWD was unset or unexported,
8253 * set it again, but do not export. bash does the same.
8254 */
8255 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008256 return EXIT_SUCCESS;
8257}
8258
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008259static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008260{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008261 argv = skip_dash_dash(argv);
8262 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008263 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008264
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008265 /* Careful: we can end up here after [v]fork. Do not restore
8266 * tty pgrp then, only top-level shell process does that */
8267 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8268 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8269
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008270 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008271 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008272 * and tcsetpgrp, and this is inherently racy.
8273 */
8274 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008275}
8276
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008277static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008278{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008279 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008280
8281 /* interactive bash:
8282 * # trap "echo EEE" EXIT
8283 * # exit
8284 * exit
8285 * There are stopped jobs.
8286 * (if there are _stopped_ jobs, running ones don't count)
8287 * # exit
8288 * exit
8289 # EEE (then bash exits)
8290 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008291 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008292 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008293
8294 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008295 argv = skip_dash_dash(argv);
8296 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008297 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008298 /* mimic bash: exit 123abc == exit 255 + error msg */
8299 xfunc_error_retval = 255;
8300 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008301 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008302}
8303
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008304static void print_escaped(const char *s)
8305{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008306 if (*s == '\'')
8307 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008308 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008309 const char *p = strchrnul(s, '\'');
8310 /* print 'xxxx', possibly just '' */
8311 printf("'%.*s'", (int)(p - s), s);
8312 if (*p == '\0')
8313 break;
8314 s = p;
8315 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008316 /* s points to '; print "'''...'''" */
8317 putchar('"');
8318 do putchar('\''); while (*++s == '\'');
8319 putchar('"');
8320 } while (*s);
8321}
8322
Denys Vlasenko295fef82009-06-03 12:47:26 +02008323#if !ENABLE_HUSH_LOCAL
8324#define helper_export_local(argv, exp, lvl) \
8325 helper_export_local(argv, exp)
8326#endif
8327static void helper_export_local(char **argv, int exp, int lvl)
8328{
8329 do {
8330 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008331 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008332
8333 /* So far we do not check that name is valid (TODO?) */
8334
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008335 if (*name_end == '\0') {
8336 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008337
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008338 vpp = get_ptr_to_local_var(name, name_end - name);
8339 var = vpp ? *vpp : NULL;
8340
Denys Vlasenko295fef82009-06-03 12:47:26 +02008341 if (exp == -1) { /* unexporting? */
8342 /* export -n NAME (without =VALUE) */
8343 if (var) {
8344 var->flg_export = 0;
8345 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8346 unsetenv(name);
8347 } /* else: export -n NOT_EXISTING_VAR: no-op */
8348 continue;
8349 }
8350 if (exp == 1) { /* exporting? */
8351 /* export NAME (without =VALUE) */
8352 if (var) {
8353 var->flg_export = 1;
8354 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8355 putenv(var->varstr);
8356 continue;
8357 }
8358 }
8359 /* Exporting non-existing variable.
8360 * bash does not put it in environment,
8361 * but remembers that it is exported,
8362 * and does put it in env when it is set later.
8363 * We just set it to "" and export. */
8364 /* Or, it's "local NAME" (without =VALUE).
8365 * bash sets the value to "". */
8366 name = xasprintf("%s=", name);
8367 } else {
8368 /* (Un)exporting/making local NAME=VALUE */
8369 name = xstrdup(name);
8370 }
8371 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8372 } while (*++argv);
8373}
8374
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008375static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008376{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008377 unsigned opt_unexport;
8378
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008379#if ENABLE_HUSH_EXPORT_N
8380 /* "!": do not abort on errors */
8381 opt_unexport = getopt32(argv, "!n");
8382 if (opt_unexport == (uint32_t)-1)
8383 return EXIT_FAILURE;
8384 argv += optind;
8385#else
8386 opt_unexport = 0;
8387 argv++;
8388#endif
8389
8390 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008391 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008392 if (e) {
8393 while (*e) {
8394#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008395 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008396#else
8397 /* ash emits: export VAR='VAL'
8398 * bash: declare -x VAR="VAL"
8399 * we follow ash example */
8400 const char *s = *e++;
8401 const char *p = strchr(s, '=');
8402
8403 if (!p) /* wtf? take next variable */
8404 continue;
8405 /* export var= */
8406 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008407 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008408 putchar('\n');
8409#endif
8410 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008411 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008412 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008413 return EXIT_SUCCESS;
8414 }
8415
Denys Vlasenko295fef82009-06-03 12:47:26 +02008416 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008417
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008418 return EXIT_SUCCESS;
8419}
8420
Denys Vlasenko295fef82009-06-03 12:47:26 +02008421#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008422static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008423{
8424 if (G.func_nest_level == 0) {
8425 bb_error_msg("%s: not in a function", argv[0]);
8426 return EXIT_FAILURE; /* bash compat */
8427 }
8428 helper_export_local(argv, 0, G.func_nest_level);
8429 return EXIT_SUCCESS;
8430}
8431#endif
8432
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008433static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008434{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008435 int sig;
8436 char *new_cmd;
8437
8438 if (!G.traps)
8439 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8440
8441 argv++;
8442 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008443 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008444 /* No args: print all trapped */
8445 for (i = 0; i < NSIG; ++i) {
8446 if (G.traps[i]) {
8447 printf("trap -- ");
8448 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008449 /* note: bash adds "SIG", but only if invoked
8450 * as "bash". If called as "sh", or if set -o posix,
8451 * then it prints short signal names.
8452 * We are printing short names: */
8453 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008454 }
8455 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008456 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008457 return EXIT_SUCCESS;
8458 }
8459
8460 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008461 /* If first arg is a number: reset all specified signals */
8462 sig = bb_strtou(*argv, NULL, 10);
8463 if (errno == 0) {
8464 int ret;
8465 process_sig_list:
8466 ret = EXIT_SUCCESS;
8467 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008468 sighandler_t handler;
8469
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008470 sig = get_signum(*argv++);
8471 if (sig < 0 || sig >= NSIG) {
8472 ret = EXIT_FAILURE;
8473 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008474 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008475 continue;
8476 }
8477
8478 free(G.traps[sig]);
8479 G.traps[sig] = xstrdup(new_cmd);
8480
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008481 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008482 get_signame(sig), sig, G.traps[sig]);
8483
8484 /* There is no signal for 0 (EXIT) */
8485 if (sig == 0)
8486 continue;
8487
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008488 if (new_cmd)
8489 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8490 else
8491 /* We are removing trap handler */
8492 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02008493 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008494 }
8495 return ret;
8496 }
8497
8498 if (!argv[1]) { /* no second arg */
8499 bb_error_msg("trap: invalid arguments");
8500 return EXIT_FAILURE;
8501 }
8502
8503 /* First arg is "-": reset all specified to default */
8504 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8505 /* Everything else: set arg as signal handler
8506 * (includes "" case, which ignores signal) */
8507 if (argv[0][0] == '-') {
8508 if (argv[0][1] == '\0') { /* "-" */
8509 /* new_cmd remains NULL: "reset these sigs" */
8510 goto reset_traps;
8511 }
8512 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8513 argv++;
8514 }
8515 /* else: "-something", no special meaning */
8516 }
8517 new_cmd = *argv;
8518 reset_traps:
8519 argv++;
8520 goto process_sig_list;
8521}
8522
Mike Frysinger93cadc22009-05-27 17:06:25 -04008523/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008524static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008525{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008526 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008527
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008528 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008529 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008530 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008531
8532 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008533 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008534 type = "an alias";*/
8535#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008536 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008537 type = "a function";
8538#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008539 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008540 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008541 else if ((path = find_in_path(*argv)) != NULL)
8542 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008543 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008544 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008545 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008546 continue;
8547 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008548
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008549 printf("%s is %s\n", *argv, type);
8550 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008551 }
8552
8553 return ret;
8554}
8555
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008556#if ENABLE_HUSH_JOB
8557/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008558static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008559{
8560 int i, jobnum;
8561 struct pipe *pi;
8562
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008563 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008564 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008565
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008566 /* If they gave us no args, assume they want the last backgrounded task */
8567 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008568 for (pi = G.job_list; pi; pi = pi->next) {
8569 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008570 goto found;
8571 }
8572 }
8573 bb_error_msg("%s: no current job", argv[0]);
8574 return EXIT_FAILURE;
8575 }
8576 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8577 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8578 return EXIT_FAILURE;
8579 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008580 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008581 if (pi->jobid == jobnum) {
8582 goto found;
8583 }
8584 }
8585 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8586 return EXIT_FAILURE;
8587 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008588 /* TODO: bash prints a string representation
8589 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008590 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008591 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008592 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008593 }
8594
8595 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008596 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8597 for (i = 0; i < pi->num_cmds; i++) {
8598 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8599 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008600 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008601 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008602
8603 i = kill(- pi->pgrp, SIGCONT);
8604 if (i < 0) {
8605 if (errno == ESRCH) {
8606 delete_finished_bg_job(pi);
8607 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008608 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008609 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008610 }
8611
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008612 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008613 remove_bg_job(pi);
8614 return checkjobs_and_fg_shell(pi);
8615 }
8616 return EXIT_SUCCESS;
8617}
8618#endif
8619
8620#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008621static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008622{
8623 const struct built_in_command *x;
8624
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008625 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008626 "Built-in commands:\n"
8627 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008628 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008629 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008630 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008631 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008632 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008633 return EXIT_SUCCESS;
8634}
8635#endif
8636
8637#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008638static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008639{
8640 struct pipe *job;
8641 const char *status_string;
8642
Denis Vlasenko87a86552008-07-29 19:43:10 +00008643 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008644 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008645 status_string = "Stopped";
8646 else
8647 status_string = "Running";
8648
8649 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8650 }
8651 return EXIT_SUCCESS;
8652}
8653#endif
8654
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008655#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008656static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008657{
8658 void *p;
8659 unsigned long l;
8660
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008661# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008662 /* Optional. Reduces probability of false positives */
8663 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008664# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008665 /* Crude attempt to find where "free memory" starts,
8666 * sans fragmentation. */
8667 p = malloc(240);
8668 l = (unsigned long)p;
8669 free(p);
8670 p = malloc(3400);
8671 if (l < (unsigned long)p) l = (unsigned long)p;
8672 free(p);
8673
8674 if (!G.memleak_value)
8675 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008676
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008677 l -= G.memleak_value;
8678 if ((long)l < 0)
8679 l = 0;
8680 l /= 1024;
8681 if (l > 127)
8682 l = 127;
8683
8684 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8685 return l;
8686}
8687#endif
8688
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008689static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008690{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008691 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008692 return EXIT_SUCCESS;
8693}
8694
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008695/* Interruptibility of read builtin in bash
8696 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8697 *
8698 * Empty trap makes read ignore corresponding signal, for any signal.
8699 *
8700 * SIGINT:
8701 * - terminates non-interactive shell;
8702 * - interrupts read in interactive shell;
8703 * if it has non-empty trap:
8704 * - executes trap and returns to command prompt in interactive shell;
8705 * - executes trap and returns to read in non-interactive shell;
8706 * SIGTERM:
8707 * - is ignored (does not interrupt) read in interactive shell;
8708 * - terminates non-interactive shell;
8709 * if it has non-empty trap:
8710 * - executes trap and returns to read;
8711 * SIGHUP:
8712 * - terminates shell (regardless of interactivity);
8713 * if it has non-empty trap:
8714 * - executes trap and returns to read;
8715 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008716static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008717{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008718 const char *r;
8719 char *opt_n = NULL;
8720 char *opt_p = NULL;
8721 char *opt_t = NULL;
8722 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008723 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01008724 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008725
Denys Vlasenko03dad222010-01-12 23:29:57 +01008726 /* "!": do not abort on errors.
8727 * Option string must start with "sr" to match BUILTIN_READ_xxx
8728 */
8729 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8730 if (read_flags == (uint32_t)-1)
8731 return EXIT_FAILURE;
8732 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008733 ifs = get_local_var_value("IFS"); /* can be NULL */
8734
8735 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01008736 r = shell_builtin_read(set_local_var_from_halves,
8737 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008738 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01008739 read_flags,
8740 opt_n,
8741 opt_p,
8742 opt_t,
8743 opt_u
8744 );
8745
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008746 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008747 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008748 if (sig && sig != SIGINT)
8749 goto again;
8750 }
8751
Denys Vlasenko03dad222010-01-12 23:29:57 +01008752 if ((uintptr_t)r > 1) {
8753 bb_error_msg("%s", r);
8754 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008755 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008756
Denys Vlasenko03dad222010-01-12 23:29:57 +01008757 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008758}
8759
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008760/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8761 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008762 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008763 * set [-abCefhmnuvx] [-o option] [argument...]
8764 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008765 * set -- [argument...]
8766 * set -o
8767 * set +o
8768 * Implementations shall support the options in both their hyphen and
8769 * plus-sign forms. These options can also be specified as options to sh.
8770 * Examples:
8771 * Write out all variables and their values: set
8772 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8773 * Turn on the -x and -v options: set -xv
8774 * Unset all positional parameters: set --
8775 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8776 * Set the positional parameters to the expansion of x, even if x expands
8777 * with a leading '-' or '+': set -- $x
8778 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008779 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008780 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008781static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008782{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008783 int n;
8784 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008785 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008786
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008787 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008788 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008789 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008790 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008791 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008792 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008793
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008794 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008795 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008796 ++argv;
8797 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008798 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008799 if (arg[0] != '+' && arg[0] != '-')
8800 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008801 for (n = 1; arg[n]; ++n) {
8802 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008803 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008804 if (arg[n] == 'o' && argv[1])
8805 argv++;
8806 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008807 } while ((arg = *++argv) != NULL);
8808 /* Now argv[0] is 1st argument */
8809
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008810 if (arg == NULL)
8811 return EXIT_SUCCESS;
8812 set_argv:
8813
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008814 /* NB: G.global_argv[0] ($0) is never freed/changed */
8815 g_argv = G.global_argv;
8816 if (G.global_args_malloced) {
8817 pp = g_argv;
8818 while (*++pp)
8819 free(*pp);
8820 g_argv[1] = NULL;
8821 } else {
8822 G.global_args_malloced = 1;
8823 pp = xzalloc(sizeof(pp[0]) * 2);
8824 pp[0] = g_argv[0]; /* retain $0 */
8825 g_argv = pp;
8826 }
8827 /* This realloc's G.global_argv */
8828 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8829
8830 n = 1;
8831 while (*++pp)
8832 n++;
8833 G.global_argc = n;
8834
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008835 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008836
8837 /* Nothing known, so abort */
8838 error:
8839 bb_error_msg("set: %s: invalid option", arg);
8840 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008841}
8842
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008843static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008844{
8845 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008846 argv = skip_dash_dash(argv);
8847 if (argv[0]) {
8848 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008849 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008850 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008851 if (G.global_args_malloced) {
8852 int m = 1;
8853 while (m <= n)
8854 free(G.global_argv[m++]);
8855 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008856 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008857 memmove(&G.global_argv[1], &G.global_argv[n+1],
8858 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008859 return EXIT_SUCCESS;
8860 }
8861 return EXIT_FAILURE;
8862}
8863
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008864static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008865{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008866 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008867 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008868 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008869#if ENABLE_HUSH_FUNCTIONS
8870 smallint sv_flg;
8871#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008872
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008873 argv = skip_dash_dash(argv);
8874 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008875 if (!filename) {
8876 /* bash says: "bash: .: filename argument required" */
8877 return 2; /* bash compat */
8878 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008879 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008880 if (!strchr(filename, '/')) {
8881 arg_path = find_in_path(filename);
8882 if (arg_path)
8883 filename = arg_path;
8884 }
8885 input = fopen_or_warn(filename, "r");
8886 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008887 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008888 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008889 return EXIT_FAILURE;
8890 }
8891 close_on_exec_on(fileno(input));
8892
Mike Frysinger885b6f22009-04-18 21:04:25 +00008893#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008894 sv_flg = G.flag_return_in_progress;
8895 /* "we are inside sourced file, ok to use return" */
8896 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008897#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008898 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008899
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008900 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008901 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008902
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008903 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008904#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008905 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008906#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008907
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008908 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008909}
8910
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008911static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008912{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008913 int rc;
8914 mode_t mask;
8915
8916 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008917 argv = skip_dash_dash(argv);
8918 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008919 mode_t old_mask = mask;
8920
8921 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008922 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008923 mask ^= 0777;
8924 if (rc == 0) {
8925 mask = old_mask;
8926 /* bash messages:
8927 * bash: umask: 'q': invalid symbolic mode operator
8928 * bash: umask: 999: octal number out of range
8929 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008930 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008931 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008932 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008933 rc = 1;
8934 /* Mimic bash */
8935 printf("%04o\n", (unsigned) mask);
8936 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008937 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008938 umask(mask);
8939
8940 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008941}
8942
Mike Frysingerd690f682009-03-30 06:50:54 +00008943/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008944static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008945{
Mike Frysingerd690f682009-03-30 06:50:54 +00008946 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008947 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008948
Denis Vlasenko28e67962009-04-26 23:22:40 +00008949 /* "!": do not abort on errors */
8950 /* "+": stop at 1st non-option */
8951 opts = getopt32(argv, "!+vf");
8952 if (opts == (unsigned)-1)
8953 return EXIT_FAILURE;
8954 if (opts == 3) {
8955 bb_error_msg("unset: -v and -f are exclusive");
8956 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008957 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008958 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008959
8960 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008961 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008962 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008963 if (unset_local_var(*argv)) {
8964 /* unset <nonexistent_var> doesn't fail.
8965 * Error is when one tries to unset RO var.
8966 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008967 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008968 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008969 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008970#if ENABLE_HUSH_FUNCTIONS
8971 else {
8972 unset_func(*argv);
8973 }
8974#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008975 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008976 }
8977 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008978}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008979
Mike Frysinger56bdea12009-03-28 20:01:58 +00008980/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008981static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008982{
8983 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008984 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008985
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008986 argv = skip_dash_dash(argv);
8987 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008988 /* Don't care about wait results */
8989 /* Note 1: must wait until there are no more children */
8990 /* Note 2: must be interruptible */
8991 /* Examples:
8992 * $ sleep 3 & sleep 6 & wait
8993 * [1] 30934 sleep 3
8994 * [2] 30935 sleep 6
8995 * [1] Done sleep 3
8996 * [2] Done sleep 6
8997 * $ sleep 3 & sleep 6 & wait
8998 * [1] 30936 sleep 3
8999 * [2] 30937 sleep 6
9000 * [1] Done sleep 3
9001 * ^C <-- after ~4 sec from keyboard
9002 * $
9003 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009004 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009005 int sig;
9006 sigset_t oldset, allsigs;
9007
9008 /* waitpid is not interruptible by SA_RESTARTed
9009 * signals which we use. Thus, this ugly dance:
9010 */
9011
9012 /* Make sure possible SIGCHLD is stored in kernel's
9013 * pending signal mask before we call waitpid.
9014 * Or else we may race with SIGCHLD, lose it,
9015 * and get stuck in sigwaitinfo...
9016 */
9017 sigfillset(&allsigs);
9018 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9019
9020 if (!sigisemptyset(&G.pending_set)) {
9021 /* Crap! we raced with some signal! */
9022 // sig = 0;
9023 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009024 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009025
9026 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9027 if (errno == ECHILD) {
9028 sigprocmask(SIG_SETMASK, &oldset, NULL);
9029 break;
9030 }
9031
9032 /* Wait for SIGCHLD or any other signal */
9033 //sig = sigwaitinfo(&allsigs, NULL);
9034 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9035 /* Note: sigsuspend invokes signal handler */
9036 sigsuspend(&oldset);
9037 restore:
9038 sigprocmask(SIG_SETMASK, &oldset, NULL);
9039
9040 /* So, did we get a signal? */
9041 //if (sig > 0)
9042 // raise(sig); /* run handler */
9043 sig = check_and_run_traps();
9044 if (sig /*&& sig != SIGCHLD - always true */) {
9045 /* see note 2 */
9046 ret = 128 + sig;
9047 break;
9048 }
9049 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009050 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009051 return ret;
9052 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009053
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009054 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009055 while (*argv) {
9056 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00009057 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009058 /* mimic bash message */
9059 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009060 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009061 }
9062 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00009063 if (WIFSIGNALED(status))
9064 ret = 128 + WTERMSIG(status);
9065 else if (WIFEXITED(status))
9066 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00009067 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00009068 ret = EXIT_FAILURE;
9069 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009070 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009071 ret = 127;
9072 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00009073 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009074 }
9075
9076 return ret;
9077}
9078
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009079#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9080static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9081{
9082 if (argv[1]) {
9083 def = bb_strtou(argv[1], NULL, 10);
9084 if (errno || def < def_min || argv[2]) {
9085 bb_error_msg("%s: bad arguments", argv[0]);
9086 def = UINT_MAX;
9087 }
9088 }
9089 return def;
9090}
9091#endif
9092
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009093#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009094static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009095{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009096 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009097 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009098 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009099 return EXIT_SUCCESS; /* bash compat */
9100 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009101 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009102
9103 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9104 if (depth == UINT_MAX)
9105 G.flag_break_continue = BC_BREAK;
9106 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009107 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009108
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009109 return EXIT_SUCCESS;
9110}
9111
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009112static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009113{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009114 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9115 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009116}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009117#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009118
9119#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009120static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009121{
9122 int rc;
9123
9124 if (G.flag_return_in_progress != -1) {
9125 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9126 return EXIT_FAILURE; /* bash compat */
9127 }
9128
9129 G.flag_return_in_progress = 1;
9130
9131 /* bash:
9132 * out of range: wraps around at 256, does not error out
9133 * non-numeric param:
9134 * f() { false; return qwe; }; f; echo $?
9135 * bash: return: qwe: numeric argument required <== we do this
9136 * 255 <== we also do this
9137 */
9138 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9139 return rc;
9140}
9141#endif