blob: 1082738a2ddcb43f843203dd83a1fe07afbfefc2 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
45 * tilde expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000046 * aliases
Denys Vlasenko349ef962010-05-21 15:46:24 +020047 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020050 * make complex ${var%...} constructs support optional
51 * make here documents optional
Mike Frysinger25a6ca02009-03-28 13:59:26 +000052 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020053 * Bash compat TODO:
54 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020055 * reserved words: function select
56 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020057 * process substitution: <(list) and >(list)
58 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020059 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020060 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020063 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020064 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020066 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenkobbecd742010-10-03 17:22:52 +020067 *
68 * Won't do:
69 * In bash, export builtin is special, its arguments are assignments
Denys Vlasenko08218012009-06-03 14:43:56 +020070 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
72 * compare with:
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020076 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020077 * Note2: bash 3.2.33(1) does this only if export word itself
78 * is not quoted:
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
80 * aaa bbb
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
82 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000083 */
Denys Vlasenko8da415e2010-12-05 01:30:14 +010084#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85 || defined(__APPLE__) \
86 )
87# include <malloc.h> /* for malloc_trim */
88#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +000089#include <glob.h>
90/* #include <dmalloc.h> */
91#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000092# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000093#endif
Denys Vlasenko03dad222010-01-12 23:29:57 +010094
Denys Vlasenko20704f02011-03-23 17:59:27 +010095#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
96#include "unicode.h"
Denys Vlasenko03dad222010-01-12 23:29:57 +010097#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000098#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000099#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +0200100#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200101# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +0200102#else
103# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200104#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000105#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200106# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000107#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000108
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200109/* Not every libc has sighandler_t. Fix it */
110typedef void (*hush_sighandler_t)(int);
111#define sighandler_t hush_sighandler_t
112
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:config HUSH
114//config: bool "hush"
115//config: default y
116//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200117//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200118//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119//config: case/esac. Redirections, here documents, $((arithmetic))
120//config: and functions are supported.
121//config:
122//config: It will compile and work on no-mmu systems.
123//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +0200124//config: It does not handle select, aliases, tilde expansion,
125//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200126//config:
127//config:config HUSH_BASH_COMPAT
128//config: bool "bash-compatible extensions"
129//config: default y
130//config: depends on HUSH
131//config: help
132//config: Enable bash-compatible extensions.
133//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200134//config:config HUSH_BRACE_EXPANSION
135//config: bool "Brace expansion"
136//config: default y
137//config: depends on HUSH_BASH_COMPAT
138//config: help
139//config: Enable {abc,def} extension.
140//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200141//config:config HUSH_HELP
142//config: bool "help builtin"
143//config: default y
144//config: depends on HUSH
145//config: help
146//config: Enable help builtin in hush. Code size + ~1 kbyte.
147//config:
148//config:config HUSH_INTERACTIVE
149//config: bool "Interactive mode"
150//config: default y
151//config: depends on HUSH
152//config: help
153//config: Enable interactive mode (prompt and command editing).
154//config: Without this, hush simply reads and executes commands
155//config: from stdin just like a shell script from a file.
156//config: No prompt, no PS1/PS2 magic shell variables.
157//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200158//config:config HUSH_SAVEHISTORY
159//config: bool "Save command history to .hush_history"
160//config: default y
161//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
162//config: help
163//config: Enable history saving in hush.
164//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config:config HUSH_JOB
166//config: bool "Job control"
167//config: default y
168//config: depends on HUSH_INTERACTIVE
169//config: help
170//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
171//config: command (not entire shell), fg/bg builtins work. Without this option,
172//config: "cmd &" still works by simply spawning a process and immediately
173//config: prompting for next command (or executing next command in a script),
174//config: but no separate process group is formed.
175//config:
176//config:config HUSH_TICK
177//config: bool "Process substitution"
178//config: default y
179//config: depends on HUSH
180//config: help
181//config: Enable process substitution `command` and $(command) in hush.
182//config:
183//config:config HUSH_IF
184//config: bool "Support if/then/elif/else/fi"
185//config: default y
186//config: depends on HUSH
187//config: help
188//config: Enable if/then/elif/else/fi in hush.
189//config:
190//config:config HUSH_LOOPS
191//config: bool "Support for, while and until loops"
192//config: default y
193//config: depends on HUSH
194//config: help
195//config: Enable for, while and until loops in hush.
196//config:
197//config:config HUSH_CASE
198//config: bool "Support case ... esac statement"
199//config: default y
200//config: depends on HUSH
201//config: help
202//config: Enable case ... esac statement in hush. +400 bytes.
203//config:
204//config:config HUSH_FUNCTIONS
205//config: bool "Support funcname() { commands; } syntax"
206//config: default y
207//config: depends on HUSH
208//config: help
209//config: Enable support for shell functions in hush. +800 bytes.
210//config:
211//config:config HUSH_LOCAL
212//config: bool "Support local builtin"
213//config: default y
214//config: depends on HUSH_FUNCTIONS
215//config: help
216//config: Enable support for local variables in functions.
217//config:
218//config:config HUSH_RANDOM_SUPPORT
219//config: bool "Pseudorandom generator and $RANDOM variable"
220//config: default y
221//config: depends on HUSH
222//config: help
223//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
224//config: Each read of "$RANDOM" will generate a new pseudorandom value.
225//config:
226//config:config HUSH_EXPORT_N
227//config: bool "Support 'export -n' option"
228//config: default y
229//config: depends on HUSH
230//config: help
231//config: export -n unexports variables. It is a bash extension.
232//config:
233//config:config HUSH_MODE_X
234//config: bool "Support 'hush -x' option and 'set -x' command"
235//config: default y
236//config: depends on HUSH
237//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200238//config: This instructs hush to print commands before execution.
239//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200240//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200241//config:config MSH
242//config: bool "msh (deprecated: aliased to hush)"
243//config: default n
244//config: select HUSH
245//config: help
246//config: msh is deprecated and will be removed, please migrate to hush.
247//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200248
Denys Vlasenko20704f02011-03-23 17:59:27 +0100249//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
250//applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
251//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
252//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
253
254//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
255//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
256
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100257/* -i (interactive) and -s (read stdin) are also accepted,
258 * but currently do nothing, therefore aren't shown in help.
259 * NOMMU-specific options are not meant to be used by users,
260 * therefore we don't show them either.
261 */
262//usage:#define hush_trivial_usage
Denys Vlasenkof58f7052011-05-12 02:10:33 +0200263//usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100264//usage:#define hush_full_usage "\n\n"
265//usage: "Unix shell interpreter"
266
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100267//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100268//usage:#define msh_full_usage hush_full_usage
269
270//usage:#if ENABLE_FEATURE_SH_IS_HUSH
271//usage:# define sh_trivial_usage hush_trivial_usage
272//usage:# define sh_full_usage hush_full_usage
273//usage:#endif
274//usage:#if ENABLE_FEATURE_BASH_IS_HUSH
275//usage:# define bash_trivial_usage hush_trivial_usage
276//usage:# define bash_full_usage hush_full_usage
277//usage:#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200278
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000279
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200280/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000281#define LEAK_HUNTING 0
282#define BUILD_AS_NOMMU 0
283/* Enable/disable sanity checks. Ok to enable in production,
284 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
285 * Keeping 1 for now even in released versions.
286 */
287#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200288/* Slightly bigger (+200 bytes), but faster hush.
289 * So far it only enables a trick with counting SIGCHLDs and forks,
290 * which allows us to do fewer waitpid's.
291 * (we can detect a case where neither forks were done nor SIGCHLDs happened
292 * and therefore waitpid will return the same result as last time)
293 */
294#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200295/* TODO: implement simplified code for users which do not need ${var%...} ops
296 * So far ${var%...} ops are always enabled:
297 */
298#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000299
300
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000301#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000302# undef BB_MMU
303# undef USE_FOR_NOMMU
304# undef USE_FOR_MMU
305# define BB_MMU 0
306# define USE_FOR_NOMMU(...) __VA_ARGS__
307# define USE_FOR_MMU(...)
308#endif
309
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200310#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100311#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000312/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000313# undef CONFIG_FEATURE_SH_STANDALONE
314# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000315# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100316# undef IF_NOT_FEATURE_SH_STANDALONE
317# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000318# define IF_FEATURE_SH_STANDALONE(...)
319# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000320#endif
321
Denis Vlasenko05743d72008-02-10 12:10:08 +0000322#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000323# undef ENABLE_FEATURE_EDITING
324# define ENABLE_FEATURE_EDITING 0
325# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
326# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000327#endif
328
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000329/* Do we support ANY keywords? */
330#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000331# define HAS_KEYWORDS 1
332# define IF_HAS_KEYWORDS(...) __VA_ARGS__
333# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000334#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000335# define HAS_KEYWORDS 0
336# define IF_HAS_KEYWORDS(...)
337# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000338#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000339
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000340/* If you comment out one of these below, it will be #defined later
341 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000342#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000343/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000344#define debug_printf_parse(...) do {} while (0)
345#define debug_print_tree(a, b) do {} while (0)
346#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000347#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000348#define debug_printf_jobs(...) do {} while (0)
349#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200350#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000351#define debug_printf_glob(...) do {} while (0)
352#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000353#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000354#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000355
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000356#define ERR_PTR ((void*)(long)1)
357
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200358#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000359
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200360#define _SPECIAL_VARS_STR "_*@$!?#"
361#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
362#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200363#if ENABLE_HUSH_BASH_COMPAT
364/* Support / and // replace ops */
365/* Note that // is stored as \ in "encoded" string representation */
366# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
367# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
368# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
369#else
370# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
371# define VAR_SUBST_OPS "%#:-=+?"
372# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
373#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200374
375#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000376
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200377struct variable;
378
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000379static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
380
381/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000382 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000383 */
384#if !BB_MMU
385typedef struct nommu_save_t {
386 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200387 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000388 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000389 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000390} nommu_save_t;
391#endif
392
Denys Vlasenko9b782552010-09-08 13:33:26 +0200393enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000394 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000395#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000396 RES_IF ,
397 RES_THEN ,
398 RES_ELIF ,
399 RES_ELSE ,
400 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000401#endif
402#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000403 RES_FOR ,
404 RES_WHILE ,
405 RES_UNTIL ,
406 RES_DO ,
407 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000408#endif
409#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000410 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000411#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000412#if ENABLE_HUSH_CASE
413 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200414 /* three pseudo-keywords support contrived "case" syntax: */
415 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
416 RES_MATCH , /* "word)" */
417 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000418 RES_ESAC ,
419#endif
420 RES_XXXX ,
421 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200422};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000423
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000424typedef struct o_string {
425 char *data;
426 int length; /* position where data is appended */
427 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200428 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000429 /* At least some part of the string was inside '' or "",
430 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200431 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000432 smallint has_empty_slot;
433 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
434} o_string;
435enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200436 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
437 EXP_FLAG_GLOB = 0x2,
438 /* Protect newly added chars against globbing
439 * by prepending \ to *, ?, [, \ */
440 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
441};
442enum {
443 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000444 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200445 NOT_ASSIGNMENT = 2,
446 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
447 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000448};
449/* Used for initialization: o_string foo = NULL_O_STRING; */
450#define NULL_O_STRING { NULL }
451
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200452#ifndef debug_printf_parse
453static const char *const assignment_flag[] = {
454 "MAYBE_ASSIGNMENT",
455 "DEFINITELY_ASSIGNMENT",
456 "NOT_ASSIGNMENT",
457 "WORD_IS_KEYWORD",
458};
459#endif
460
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000461typedef struct in_str {
462 const char *p;
463 /* eof_flag=1: last char in ->p is really an EOF */
464 char eof_flag; /* meaningless if ->p == NULL */
465 char peek_buf[2];
466#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000467 smallint promptmode; /* 0: PS1, 1: PS2 */
468#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200469 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000470 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200471 int (*get) (struct in_str *) FAST_FUNC;
472 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000473} in_str;
474#define i_getch(input) ((input)->get(input))
475#define i_peek(input) ((input)->peek(input))
476
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200477/* The descrip member of this structure is only used to make
478 * debugging output pretty */
479static const struct {
480 int mode;
481 signed char default_fd;
482 char descrip[3];
483} redir_table[] = {
484 { O_RDONLY, 0, "<" },
485 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
486 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
487 { O_CREAT|O_RDWR, 1, "<>" },
488 { O_RDONLY, 0, "<<" },
489/* Should not be needed. Bogus default_fd helps in debugging */
490/* { O_RDONLY, 77, "<<" }, */
491};
492
Eric Andersen25f27032001-04-26 23:22:31 +0000493struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000494 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000495 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000496 int rd_fd; /* fd to redirect */
497 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
498 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000499 smallint rd_type; /* (enum redir_type) */
500 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000501 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200502 * bit 0: do we need to trim leading tabs?
503 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000504 */
Eric Andersen25f27032001-04-26 23:22:31 +0000505};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000506typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200507 REDIRECT_INPUT = 0,
508 REDIRECT_OVERWRITE = 1,
509 REDIRECT_APPEND = 2,
510 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000511 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200512 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000513
514 REDIRFD_CLOSE = -3,
515 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000516 REDIRFD_TO_FILE = -1,
517 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000518
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000519 HEREDOC_SKIPTABS = 1,
520 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000521} redir_type;
522
Eric Andersen25f27032001-04-26 23:22:31 +0000523
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000524struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000525 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000526 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000527 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200528 smallint cmd_type; /* CMD_xxx */
529#define CMD_NORMAL 0
530#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200531#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200532/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200533# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000534#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200535#if ENABLE_HUSH_FUNCTIONS
536# define CMD_FUNCDEF 3
537#endif
538
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100539 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200540 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
541 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000542#if !BB_MMU
543 char *group_as_string;
544#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000545#if ENABLE_HUSH_FUNCTIONS
546 struct function *child_func;
547/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200548 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000549 * When we execute "f1() {a;}" cmd, we create new function and clear
550 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200551 * When we execute "f1() {b;}", we notice that f1 exists,
552 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000553 * we put those fields back into cmd->xxx
554 * (struct function has ->parent_cmd ptr to facilitate that).
555 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
556 * Without this trick, loop would execute a;b;b;b;...
557 * instead of correct sequence a;b;a;b;...
558 * When command is freed, it severs the link
559 * (sets ->child_func->parent_cmd to NULL).
560 */
561#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000562 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000563/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
564 * and on execution these are substituted with their values.
565 * Substitution can make _several_ words out of one argv[n]!
566 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000567 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000568 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000569 struct redir_struct *redirects; /* I/O redirections */
570};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000571/* Is there anything in this command at all? */
572#define IS_NULL_CMD(cmd) \
573 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
574
Eric Andersen25f27032001-04-26 23:22:31 +0000575struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000576 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000577 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000578 int alive_cmds; /* number of commands running (not exited) */
579 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000580#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000581 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000582 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000583 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000584#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000585 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000586 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000587 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
588 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000589};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000590typedef enum pipe_style {
591 PIPE_SEQ = 1,
592 PIPE_AND = 2,
593 PIPE_OR = 3,
594 PIPE_BG = 4,
595} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000596/* Is there anything in this pipe at all? */
597#define IS_NULL_PIPE(pi) \
598 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000599
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000600/* This holds pointers to the various results of parsing */
601struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000602 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000603 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000604 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000605 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000606 /* last command in pipe (being constructed right now) */
607 struct command *command;
608 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000609 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000610#if !BB_MMU
611 o_string as_string;
612#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000613#if HAS_KEYWORDS
614 smallint ctx_res_w;
615 smallint ctx_inverted; /* "! cmd | cmd" */
616#if ENABLE_HUSH_CASE
617 smallint ctx_dsemicolon; /* ";;" seen */
618#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000619 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
620 int old_flag;
621 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000622 * example: "if pipe1; pipe2; then pipe3; fi"
623 * when we see "if" or "then", we malloc and copy current context,
624 * and make ->stack point to it. then we parse pipeN.
625 * when closing "then" / fi" / whatever is found,
626 * we move list_head into ->stack->command->group,
627 * copy ->stack into current context, and delete ->stack.
628 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000629 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000630 struct parse_context *stack;
631#endif
632};
633
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000634/* On program start, environ points to initial environment.
635 * putenv adds new pointers into it, unsetenv removes them.
636 * Neither of these (de)allocates the strings.
637 * setenv allocates new strings in malloc space and does putenv,
638 * and thus setenv is unusable (leaky) for shell's purposes */
639#define setenv(...) setenv_is_leaky_dont_use()
640struct variable {
641 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000642 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200643#if ENABLE_HUSH_LOCAL
644 unsigned func_nest_level;
645#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000646 int max_len; /* if > 0, name is part of initial env; else name is malloced */
647 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000648 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000649};
650
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000651enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000652 BC_BREAK = 1,
653 BC_CONTINUE = 2,
654};
655
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000656#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000657struct function {
658 struct function *next;
659 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000660 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000661 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200662# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000663 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200664# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000665};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000666#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000667
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000668
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100669/* set -/+o OPT support. (TODO: make it optional)
670 * bash supports the following opts:
671 * allexport off
672 * braceexpand on
673 * emacs on
674 * errexit off
675 * errtrace off
676 * functrace off
677 * hashall on
678 * histexpand off
679 * history on
680 * ignoreeof off
681 * interactive-comments on
682 * keyword off
683 * monitor on
684 * noclobber off
685 * noexec off
686 * noglob off
687 * nolog off
688 * notify off
689 * nounset off
690 * onecmd off
691 * physical off
692 * pipefail off
693 * posix off
694 * privileged off
695 * verbose off
696 * vi off
697 * xtrace off
698 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800699static const char o_opt_strings[] ALIGN1 =
700 "pipefail\0"
701 "noexec\0"
702#if ENABLE_HUSH_MODE_X
703 "xtrace\0"
704#endif
705 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100706enum {
707 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800708 OPT_O_NOEXEC,
709#if ENABLE_HUSH_MODE_X
710 OPT_O_XTRACE,
711#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100712 NUM_OPT_O
713};
714
715
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000716/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000717/* Sorted roughly by size (smaller offsets == smaller code) */
718struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000719 /* interactive_fd != 0 means we are an interactive shell.
720 * If we are, then saved_tty_pgrp can also be != 0, meaning
721 * that controlling tty is available. With saved_tty_pgrp == 0,
722 * job control still works, but terminal signals
723 * (^C, ^Z, ^Y, ^\) won't work at all, and background
724 * process groups can only be created with "cmd &".
725 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
726 * to give tty to the foreground process group,
727 * and will take it back when the group is stopped (^Z)
728 * or killed (^C).
729 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000730#if ENABLE_HUSH_INTERACTIVE
731 /* 'interactive_fd' is a fd# open to ctty, if we have one
732 * _AND_ if we decided to act interactively */
733 int interactive_fd;
734 const char *PS1;
735 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000736# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000737#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000738# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000739#endif
740#if ENABLE_FEATURE_EDITING
741 line_input_t *line_input_state;
742#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000743 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200744 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000745 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200746#if ENABLE_HUSH_RANDOM_SUPPORT
747 random_t random_gen;
748#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000749#if ENABLE_HUSH_JOB
750 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000751 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000752 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000753 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400754# define G_saved_tty_pgrp (G.saved_tty_pgrp)
755#else
756# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000757#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100758 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100759#if ENABLE_HUSH_MODE_X
760# define G_x_mode (G.o_opt[OPT_O_XTRACE])
761#else
762# define G_x_mode 0
763#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000764 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000765#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000766 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000767#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000768#if ENABLE_HUSH_FUNCTIONS
769 /* 0: outside of a function (or sourced file)
770 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000771 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000772 */
773 smallint flag_return_in_progress;
774#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000775 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000776 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000777 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000778 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000779 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000780 /* how many non-NULL argv's we have. NB: $# + 1 */
781 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000782 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000783#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000784 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000785#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000786#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000787 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000788 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000789#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000790 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000791 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200792 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200793 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000794#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000795 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200796# if ENABLE_HUSH_LOCAL
797 struct variable **shadowed_vars_pp;
798 unsigned func_nest_level;
799# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000800#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000801 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200802#if ENABLE_HUSH_FAST
803 unsigned count_SIGCHLD;
804 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200805 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200806#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +0200807 /* Which signals have non-DFL handler (even with no traps set)?
808 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200809 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200810 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200811 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200812 * Other than these two times, never modified.
813 */
814 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200815#if ENABLE_HUSH_JOB
816 unsigned fatal_sig_mask;
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200817# define G_fatal_sig_mask G.fatal_sig_mask
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200818#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200819# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200820#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000821 char **traps; /* char *traps[NSIG] */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200822 sigset_t pending_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000823#if HUSH_DEBUG
824 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000825 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000826#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200827 struct sigaction sa;
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200828 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000829};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000830#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000831/* Not #defining name to G.name - this quickly gets unwieldy
832 * (too many defines). Also, I actually prefer to see when a variable
833 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000834#define INIT_G() do { \
835 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200836 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
837 sigfillset(&G.sa.sa_mask); \
838 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000839} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000840
841
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000842/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200843static int builtin_cd(char **argv) FAST_FUNC;
844static int builtin_echo(char **argv) FAST_FUNC;
845static int builtin_eval(char **argv) FAST_FUNC;
846static int builtin_exec(char **argv) FAST_FUNC;
847static int builtin_exit(char **argv) FAST_FUNC;
848static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000849#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200850static int builtin_fg_bg(char **argv) FAST_FUNC;
851static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000852#endif
853#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200854static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000855#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200856#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200857static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200858#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000859#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200860static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000861#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400862#if ENABLE_PRINTF
863static int builtin_printf(char **argv) FAST_FUNC;
864#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200865static int builtin_pwd(char **argv) FAST_FUNC;
866static int builtin_read(char **argv) FAST_FUNC;
867static int builtin_set(char **argv) FAST_FUNC;
868static int builtin_shift(char **argv) FAST_FUNC;
869static int builtin_source(char **argv) FAST_FUNC;
870static int builtin_test(char **argv) FAST_FUNC;
871static int builtin_trap(char **argv) FAST_FUNC;
872static int builtin_type(char **argv) FAST_FUNC;
873static int builtin_true(char **argv) FAST_FUNC;
874static int builtin_umask(char **argv) FAST_FUNC;
875static int builtin_unset(char **argv) FAST_FUNC;
876static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000877#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200878static int builtin_break(char **argv) FAST_FUNC;
879static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000880#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000881#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200882static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000883#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000884
885/* Table of built-in functions. They can be forked or not, depending on
886 * context: within pipes, they fork. As simple commands, they do not.
887 * When used in non-forking context, they can change global variables
888 * in the parent shell process. If forked, of course they cannot.
889 * For example, 'unset foo | whatever' will parse and run, but foo will
890 * still be set at the end. */
891struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100892 const char *b_cmd;
893 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000894#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100895 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200896# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000897#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200898# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000899#endif
900};
901
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200902static const struct built_in_command bltins1[] = {
903 BLTIN("." , builtin_source , "Run commands in a file"),
904 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000905#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200906 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000907#endif
908#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200909 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000910#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200911 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000912#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200913 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000914#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200915 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
916 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
917 BLTIN("exit" , builtin_exit , "Exit"),
918 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000919#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200920 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000921#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000922#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200923 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000924#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000925#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200926 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000927#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200928#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200929 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200930#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000931#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200932 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000933#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200934 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000935#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200936 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000937#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200938 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
939 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200940#if ENABLE_HUSH_BASH_COMPAT
941 BLTIN("source" , builtin_source , "Run commands in a file"),
942#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200943 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100944 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100945 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200946 BLTIN("umask" , builtin_umask , "Set file creation mask"),
947 BLTIN("unset" , builtin_unset , "Unset variables"),
948 BLTIN("wait" , builtin_wait , "Wait for process"),
949};
950/* For now, echo and test are unconditionally enabled.
951 * Maybe make it configurable? */
952static const struct built_in_command bltins2[] = {
953 BLTIN("[" , builtin_test , NULL),
954 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400955#if ENABLE_PRINTF
956 BLTIN("printf" , builtin_printf , NULL),
957#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200958 BLTIN("pwd" , builtin_pwd , NULL),
959 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000960};
961
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000962
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000963/* Debug printouts.
964 */
965#if HUSH_DEBUG
966/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100967# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000968# define debug_enter() (G.debug_indent++)
969# define debug_leave() (G.debug_indent--)
970#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200971# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000972# define debug_enter() ((void)0)
973# define debug_leave() ((void)0)
974#endif
975
976#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100977# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000978#endif
979
980#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100981# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000982#endif
983
984#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100985#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000986#endif
987
988#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100989# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000990#endif
991
992#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100993# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000994# define DEBUG_JOBS 1
995#else
996# define DEBUG_JOBS 0
997#endif
998
999#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001000# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001001# define DEBUG_EXPAND 1
1002#else
1003# define DEBUG_EXPAND 0
1004#endif
1005
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001006#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001007# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001008#endif
1009
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001010#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001011# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001012# define DEBUG_GLOB 1
1013#else
1014# define DEBUG_GLOB 0
1015#endif
1016
1017#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001018# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001019#endif
1020
1021#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001022# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001023#endif
1024
1025#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001026# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001027# define DEBUG_CLEAN 1
1028#else
1029# define DEBUG_CLEAN 0
1030#endif
1031
1032#if DEBUG_EXPAND
1033static void debug_print_strings(const char *prefix, char **vv)
1034{
1035 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001036 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001037 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001038 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001039}
1040#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001041# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001042#endif
1043
1044
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001045/* Leak hunting. Use hush_leaktool.sh for post-processing.
1046 */
1047#if LEAK_HUNTING
1048static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001049{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001050 void *ptr = xmalloc((size + 0xff) & ~0xff);
1051 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1052 return ptr;
1053}
1054static void *xxrealloc(int lineno, void *ptr, size_t size)
1055{
1056 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1057 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1058 return ptr;
1059}
1060static char *xxstrdup(int lineno, const char *str)
1061{
1062 char *ptr = xstrdup(str);
1063 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1064 return ptr;
1065}
1066static void xxfree(void *ptr)
1067{
1068 fdprintf(2, "free %p\n", ptr);
1069 free(ptr);
1070}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001071# define xmalloc(s) xxmalloc(__LINE__, s)
1072# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1073# define xstrdup(s) xxstrdup(__LINE__, s)
1074# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001075#endif
1076
1077
1078/* Syntax and runtime errors. They always abort scripts.
1079 * In interactive use they usually discard unparsed and/or unexecuted commands
1080 * and return to the prompt.
1081 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1082 */
1083#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001084# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001085# define syntax_error(lineno, msg) syntax_error(msg)
1086# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1087# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1088# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1089# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001090#endif
1091
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001092static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001093{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001094 va_list p;
1095
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001096#if HUSH_DEBUG >= 2
1097 bb_error_msg("hush.c:%u", lineno);
1098#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001099 va_start(p, fmt);
1100 bb_verror_msg(fmt, p, NULL);
1101 va_end(p);
1102 if (!G_interactive_fd)
1103 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001104}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001105
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001106static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001107{
1108 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001109 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001110 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001111 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001112}
1113
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001114static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001115{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001116 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001117}
1118
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001119static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001120{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001121 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001122}
1123
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001124static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001125{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001126 char msg[2] = { ch, '\0' };
1127 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001128}
1129
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001130static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001131{
1132 char msg[2];
1133 msg[0] = ch;
1134 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001135 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001136}
1137
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001138#if HUSH_DEBUG < 2
1139# undef die_if_script
1140# undef syntax_error
1141# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001142# undef syntax_error_unterm_ch
1143# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001144# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001145#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001146# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001147# define syntax_error(msg) syntax_error(__LINE__, msg)
1148# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1149# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1150# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1151# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001152#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001153
Denis Vlasenko552433b2009-04-04 19:29:21 +00001154
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001155#if ENABLE_HUSH_INTERACTIVE
1156static void cmdedit_update_prompt(void);
1157#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001158# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001159#endif
1160
1161
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001162/* Utility functions
1163 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001164/* Replace each \x with x in place, return ptr past NUL. */
1165static char *unbackslash(char *src)
1166{
Denys Vlasenko71885402009-09-24 01:44:13 +02001167 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001168 while (1) {
1169 if (*src == '\\')
1170 src++;
1171 if ((*dst++ = *src++) == '\0')
1172 break;
1173 }
1174 return dst;
1175}
1176
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001177static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001178{
1179 int i;
1180 unsigned count1;
1181 unsigned count2;
1182 char **v;
1183
1184 v = strings;
1185 count1 = 0;
1186 if (v) {
1187 while (*v) {
1188 count1++;
1189 v++;
1190 }
1191 }
1192 count2 = 0;
1193 v = add;
1194 while (*v) {
1195 count2++;
1196 v++;
1197 }
1198 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1199 v[count1 + count2] = NULL;
1200 i = count2;
1201 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001202 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001203 return v;
1204}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001205#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001206static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1207{
1208 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1209 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1210 return ptr;
1211}
1212#define add_strings_to_strings(strings, add, need_to_dup) \
1213 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1214#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001215
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001216/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001217static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001218{
1219 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001220 v[0] = add;
1221 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001222 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001223}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001224#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001225static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1226{
1227 char **ptr = add_string_to_strings(strings, add);
1228 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1229 return ptr;
1230}
1231#define add_string_to_strings(strings, add) \
1232 xx_add_string_to_strings(__LINE__, strings, add)
1233#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001234
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001235static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001236{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001237 char **v;
1238
1239 if (!strings)
1240 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001241 v = strings;
1242 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001243 free(*v);
1244 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001245 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001246 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001247}
1248
Denis Vlasenko76d50412008-06-10 16:19:39 +00001249
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001250/* Helpers for setting new $n and restoring them back
1251 */
1252typedef struct save_arg_t {
1253 char *sv_argv0;
1254 char **sv_g_argv;
1255 int sv_g_argc;
1256 smallint sv_g_malloced;
1257} save_arg_t;
1258
1259static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1260{
1261 int n;
1262
1263 sv->sv_argv0 = argv[0];
1264 sv->sv_g_argv = G.global_argv;
1265 sv->sv_g_argc = G.global_argc;
1266 sv->sv_g_malloced = G.global_args_malloced;
1267
1268 argv[0] = G.global_argv[0]; /* retain $0 */
1269 G.global_argv = argv;
1270 G.global_args_malloced = 0;
1271
1272 n = 1;
1273 while (*++argv)
1274 n++;
1275 G.global_argc = n;
1276}
1277
1278static void restore_G_args(save_arg_t *sv, char **argv)
1279{
1280 char **pp;
1281
1282 if (G.global_args_malloced) {
1283 /* someone ran "set -- arg1 arg2 ...", undo */
1284 pp = G.global_argv;
1285 while (*++pp) /* note: does not free $0 */
1286 free(*pp);
1287 free(G.global_argv);
1288 }
1289 argv[0] = sv->sv_argv0;
1290 G.global_argv = sv->sv_g_argv;
1291 G.global_argc = sv->sv_g_argc;
1292 G.global_args_malloced = sv->sv_g_malloced;
1293}
1294
1295
Denis Vlasenkod5762932009-03-31 11:22:57 +00001296/* Basic theory of signal handling in shell
1297 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001298 * This does not describe what hush does, rather, it is current understanding
1299 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001300 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1301 *
1302 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1303 * is finished or backgrounded. It is the same in interactive and
1304 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001305 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001306 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001307 * backgrounds (i.e. stops) or kills all members of currently running
1308 * pipe.
1309 *
1310 * Wait builtin in interruptible by signals for which user trap is set
1311 * or by SIGINT in interactive shell.
1312 *
1313 * Trap handlers will execute even within trap handlers. (right?)
1314 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001315 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1316 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001317 *
1318 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001319 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001320 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001321 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001322 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001323 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001324 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001325 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001326 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001327 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001328 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001329 *
1330 * SIGQUIT: ignore
1331 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001332 * SIGHUP (interactive):
1333 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001334 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001335 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1336 * that all pipe members are stopped. Try this in bash:
1337 * while :; do :; done - ^Z does not background it
1338 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001339 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001340 * of the command line, show prompt. NB: ^C does not send SIGINT
1341 * to interactive shell while shell is waiting for a pipe,
1342 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001343 * Example 1: this waits 5 sec, but does not execute ls:
1344 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1345 * Example 2: this does not wait and does not execute ls:
1346 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1347 * Example 3: this does not wait 5 sec, but executes ls:
1348 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001349 * Example 4: this does not wait and does not execute ls:
1350 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001351 *
1352 * (What happens to signals which are IGN on shell start?)
1353 * (What happens with signal mask on shell start?)
1354 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001355 * Old implementation
1356 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001357 * We use in-kernel pending signal mask to determine which signals were sent.
1358 * We block all signals which we don't want to take action immediately,
1359 * i.e. we block all signals which need to have special handling as described
1360 * above, and all signals which have traps set.
1361 * After each pipe execution, we extract any pending signals via sigtimedwait()
1362 * and act on them.
1363 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001364 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001365 * sigset_t blocked_set: current blocked signal set
1366 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001367 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001368 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001369 * "trap 'cmd' SIGxxx":
1370 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001371 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001372 * unblock signals with special interactive handling
1373 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001374 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001375 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001376 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001377 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001378 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001379 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001380 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001381 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001382 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001383 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001384 * Standard says "When a subshell is entered, traps that are not being ignored
1385 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001386 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001387 *
1388 * Problem: the above approach makes it unwieldy to catch signals while
1389 * we are in read builtin, of while we read commands from stdin:
1390 * masked signals are not visible!
1391 *
1392 * New implementation
1393 * ==================
1394 * We record each signal we are interested in by installing signal handler
1395 * for them - a bit like emulating kernel pending signal mask in userspace.
1396 * We are interested in: signals which need to have special handling
1397 * as described above, and all signals which have traps set.
1398 * Signals are rocorded in pending_set.
1399 * After each pipe execution, we extract any pending signals
1400 * and act on them.
1401 *
1402 * unsigned special_sig_mask: a mask of shell-special signals.
1403 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1404 * char *traps[sig] if trap for sig is set (even if it's '').
1405 * sigset_t pending_set: set of sigs we received.
1406 *
1407 * "trap - SIGxxx":
1408 * if sig is in special_sig_mask, set handler back to:
1409 * record_pending_signo, or to IGN if it's a tty stop signal
1410 * if sig is in fatal_sig_mask, set handler back to sigexit.
1411 * else: set handler back to SIG_DFL
1412 * "trap 'cmd' SIGxxx":
1413 * set handler to record_pending_signo.
1414 * "trap '' SIGxxx":
1415 * set handler to SIG_IGN.
1416 * after [v]fork, if we plan to be a shell:
1417 * set signals with special interactive handling to SIG_DFL
1418 * (because child shell is not interactive),
1419 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1420 * after [v]fork, if we plan to exec:
1421 * POSIX says fork clears pending signal mask in child - no need to clear it.
1422 *
1423 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1424 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1425 *
1426 * Note (compat):
1427 * Standard says "When a subshell is entered, traps that are not being ignored
1428 * are set to the default actions". bash interprets it so that traps which
1429 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001430 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001431enum {
1432 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001433 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001434 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001435 | (1 << SIGHUP)
1436 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001437 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001438#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001439 | (1 << SIGTTIN)
1440 | (1 << SIGTTOU)
1441 | (1 << SIGTSTP)
1442#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001443 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001444};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001445
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001446static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001447{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001448 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001449#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001450 if (sig == SIGCHLD) {
1451 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001452//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001453 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001454#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001455}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001456
Denys Vlasenko0806e402011-05-12 23:06:20 +02001457static sighandler_t install_sighandler(int sig, sighandler_t handler)
1458{
1459 struct sigaction old_sa;
1460
1461 /* We could use signal() to install handlers... almost:
1462 * except that we need to mask ALL signals while handlers run.
1463 * I saw signal nesting in strace, race window isn't small.
1464 * SA_RESTART is also needed, but in Linux, signal()
1465 * sets SA_RESTART too.
1466 */
1467 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1468 /* sigfillset(&G.sa.sa_mask); - already done */
1469 /* G.sa.sa_flags = SA_RESTART; - already done */
1470 G.sa.sa_handler = handler;
1471 sigaction(sig, &G.sa, &old_sa);
1472 return old_sa.sa_handler;
1473}
1474
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001475#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001476
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001477/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001478# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001479/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001480# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001481
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001482/* Restores tty foreground process group, and exits.
1483 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001484 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001485 * or called directly with -EXITCODE.
1486 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001487static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001488static void sigexit(int sig)
1489{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001490 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001491 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001492 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1493 /* Disable all signals: job control, SIGPIPE, etc.
1494 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1495 */
1496 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001497 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001498 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001499
1500 /* Not a signal, just exit */
1501 if (sig <= 0)
1502 _exit(- sig);
1503
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001504 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001505}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001506#else
1507
Denys Vlasenko8391c482010-05-22 17:50:43 +02001508# define disable_restore_tty_pgrp_on_exit() ((void)0)
1509# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001510
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001511#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001512
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001513static sighandler_t pick_sighandler(unsigned sig)
1514{
1515 sighandler_t handler = SIG_DFL;
1516 if (sig < sizeof(unsigned)*8) {
1517 unsigned sigmask = (1 << sig);
1518
1519#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001520 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001521 if (G_fatal_sig_mask & sigmask)
1522 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001523 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001524#endif
1525 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001526 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001527 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001528 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001529 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001530 * in an endless loop when we try to do some
1531 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001532 */
1533 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1534 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001535 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001536 }
1537 return handler;
1538}
1539
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001540/* Restores tty foreground process group, and exits. */
1541static void hush_exit(int exitcode) NORETURN;
1542static void hush_exit(int exitcode)
1543{
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001544 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001545 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001546 char *argv[3];
1547 /* argv[0] is unused */
1548 argv[1] = G.traps[0];
1549 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001550 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001551 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001552 * "trap" will still show it, if executed
1553 * in the handler */
1554 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001555 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001556
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001557#if ENABLE_FEATURE_CLEAN_UP
1558 {
1559 struct variable *cur_var;
1560 if (G.cwd != bb_msg_unknown)
1561 free((char*)G.cwd);
1562 cur_var = G.top_var;
1563 while (cur_var) {
1564 struct variable *tmp = cur_var;
1565 if (!cur_var->max_len)
1566 free(cur_var->varstr);
1567 cur_var = cur_var->next;
1568 free(tmp);
1569 }
1570 }
1571#endif
1572
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001573#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001574 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001575 sigexit(- (exitcode & 0xff));
1576#else
1577 exit(exitcode);
1578#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001579}
1580
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001581
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001582//TODO: return a mask of ALL handled sigs?
1583static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001584{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001585 int last_sig = 0;
1586
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001587 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001588 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001589
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001590 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001591 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001592 sig = 0;
1593 do {
1594 sig++;
1595 if (sigismember(&G.pending_set, sig)) {
1596 sigdelset(&G.pending_set, sig);
1597 goto got_sig;
1598 }
1599 } while (sig < NSIG);
1600 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001601 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001602 if (G.traps && G.traps[sig]) {
1603 if (G.traps[sig][0]) {
1604 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001605 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001606 char *argv[3];
1607 /* argv[0] is unused */
1608 argv[1] = G.traps[sig];
1609 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001610 save_rcode = G.last_exitcode;
1611 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001612 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001613 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001614 } /* else: "" trap, ignoring signal */
1615 continue;
1616 }
1617 /* not a trap: special action */
1618 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001619 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001620 /* Builtin was ^C'ed, make it look prettier: */
1621 bb_putchar('\n');
1622 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001623 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001624 break;
1625#if ENABLE_HUSH_JOB
1626 case SIGHUP: {
1627 struct pipe *job;
1628 /* bash is observed to signal whole process groups,
1629 * not individual processes */
1630 for (job = G.job_list; job; job = job->next) {
1631 if (job->pgrp <= 0)
1632 continue;
1633 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1634 if (kill(- job->pgrp, SIGHUP) == 0)
1635 kill(- job->pgrp, SIGCONT);
1636 }
1637 sigexit(SIGHUP);
1638 }
1639#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001640#if ENABLE_HUSH_FAST
1641 case SIGCHLD:
1642 G.count_SIGCHLD++;
1643//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1644 /* Note:
1645 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1646 * This simplifies wait builtin a bit.
1647 */
1648 break;
1649#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001650 default: /* ignored: */
1651 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001652 /* Note:
1653 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1654 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001655 * in interactive shell, because TERM is ignored.
1656 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001657 break;
1658 }
1659 }
1660 return last_sig;
1661}
1662
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001663
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001664static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001665{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001666 if (force || G.cwd == NULL) {
1667 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1668 * we must not try to free(bb_msg_unknown) */
1669 if (G.cwd == bb_msg_unknown)
1670 G.cwd = NULL;
1671 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1672 if (!G.cwd)
1673 G.cwd = bb_msg_unknown;
1674 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001675 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001676}
1677
Denis Vlasenko83506862007-11-23 13:11:42 +00001678
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001679/*
1680 * Shell and environment variable support
1681 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001682static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001683{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001684 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001685 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001686
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001687 pp = &G.top_var;
1688 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001689 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001690 return pp;
1691 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001692 }
1693 return NULL;
1694}
1695
Denys Vlasenko03dad222010-01-12 23:29:57 +01001696static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001697{
Denys Vlasenko29082232010-07-16 13:52:32 +02001698 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001699 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001700
1701 if (G.expanded_assignments) {
1702 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001703 while (*cpp) {
1704 char *cp = *cpp;
1705 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1706 return cp + len + 1;
1707 cpp++;
1708 }
1709 }
1710
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001711 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001712 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001713 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001714
Denys Vlasenkodea47882009-10-09 15:40:49 +02001715 if (strcmp(name, "PPID") == 0)
1716 return utoa(G.root_ppid);
1717 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001718#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001719 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001720 return utoa(next_random(&G.random_gen));
1721#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001722 return NULL;
1723}
1724
1725/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001726 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001727 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001728 * 0: do not change export flag
1729 * (if creating new variable, flag will be 0)
1730 * 1: set export flag and putenv the variable
1731 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001732 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001733 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001734#if !BB_MMU && ENABLE_HUSH_LOCAL
1735/* all params are used */
1736#elif BB_MMU && ENABLE_HUSH_LOCAL
1737#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1738 set_local_var(str, flg_export, local_lvl)
1739#elif BB_MMU && !ENABLE_HUSH_LOCAL
1740#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001741 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001742#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1743#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1744 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001745#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001746static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001747{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001748 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001749 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001750 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001751 int name_len;
1752
Denis Vlasenko950bd722009-04-21 11:23:56 +00001753 eq_sign = strchr(str, '=');
1754 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001755 free(str);
1756 return -1;
1757 }
1758
Denis Vlasenko950bd722009-04-21 11:23:56 +00001759 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001760 var_pp = &G.top_var;
1761 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001762 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001763 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001764 continue;
1765 }
1766 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001767 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001768#if !BB_MMU
1769 if (!flg_read_only)
1770#endif
1771 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001772 free(str);
1773 return -1;
1774 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001775 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001776 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1777 *eq_sign = '\0';
1778 unsetenv(str);
1779 *eq_sign = '=';
1780 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001781#if ENABLE_HUSH_LOCAL
1782 if (cur->func_nest_level < local_lvl) {
1783 /* New variable is declared as local,
1784 * and existing one is global, or local
1785 * from enclosing function.
1786 * Remove and save old one: */
1787 *var_pp = cur->next;
1788 cur->next = *G.shadowed_vars_pp;
1789 *G.shadowed_vars_pp = cur;
1790 /* bash 3.2.33(1) and exported vars:
1791 * # export z=z
1792 * # f() { local z=a; env | grep ^z; }
1793 * # f
1794 * z=a
1795 * # env | grep ^z
1796 * z=z
1797 */
1798 if (cur->flg_export)
1799 flg_export = 1;
1800 break;
1801 }
1802#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001803 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001804 free_and_exp:
1805 free(str);
1806 goto exp;
1807 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001808 if (cur->max_len != 0) {
1809 if (cur->max_len >= strlen(str)) {
1810 /* This one is from startup env, reuse space */
1811 strcpy(cur->varstr, str);
1812 goto free_and_exp;
1813 }
1814 } else {
1815 /* max_len == 0 signifies "malloced" var, which we can
1816 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001817 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001818 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001819 cur->max_len = 0;
1820 goto set_str_and_exp;
1821 }
1822
Denys Vlasenko295fef82009-06-03 12:47:26 +02001823 /* Not found - create new variable struct */
1824 cur = xzalloc(sizeof(*cur));
1825#if ENABLE_HUSH_LOCAL
1826 cur->func_nest_level = local_lvl;
1827#endif
1828 cur->next = *var_pp;
1829 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001830
1831 set_str_and_exp:
1832 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001833#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001834 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001835#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001836 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001837 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001838 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001839 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1840 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001841 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001842 if (flg_export == -1) {
1843 cur->flg_export = 0;
1844 /* unsetenv was already done */
1845 } else {
1846 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1847 return putenv(cur->varstr);
1848 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001849 }
1850 return 0;
1851}
1852
Denys Vlasenko6db47842009-09-05 20:15:17 +02001853/* Used at startup and after each cd */
1854static void set_pwd_var(int exp)
1855{
1856 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1857 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1858}
1859
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001860static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001861{
1862 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001863 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001864
1865 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001866 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001867 var_pp = &G.top_var;
1868 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001869 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1870 if (cur->flg_read_only) {
1871 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001872 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001873 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001874 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001875 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1876 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001877 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1878 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001879 if (!cur->max_len)
1880 free(cur->varstr);
1881 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001882 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001883 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001884 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001885 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001886 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001887}
1888
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001889static int unset_local_var(const char *name)
1890{
1891 return unset_local_var_len(name, strlen(name));
1892}
1893
1894static void unset_vars(char **strings)
1895{
1896 char **v;
1897
1898 if (!strings)
1899 return;
1900 v = strings;
1901 while (*v) {
1902 const char *eq = strchrnul(*v, '=');
1903 unset_local_var_len(*v, (int)(eq - *v));
1904 v++;
1905 }
1906 free(strings);
1907}
1908
Denys Vlasenko03dad222010-01-12 23:29:57 +01001909static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001910{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001911 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001912 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001913}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001914
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001915
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001916/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001917 * Helpers for "var1=val1 var2=val2 cmd" feature
1918 */
1919static void add_vars(struct variable *var)
1920{
1921 struct variable *next;
1922
1923 while (var) {
1924 next = var->next;
1925 var->next = G.top_var;
1926 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001927 if (var->flg_export) {
1928 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001929 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001930 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001931 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001932 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001933 var = next;
1934 }
1935}
1936
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001937static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001938{
1939 char **s;
1940 struct variable *old = NULL;
1941
1942 if (!strings)
1943 return old;
1944 s = strings;
1945 while (*s) {
1946 struct variable *var_p;
1947 struct variable **var_pp;
1948 char *eq;
1949
1950 eq = strchr(*s, '=');
1951 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001952 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001953 if (var_pp) {
1954 /* Remove variable from global linked list */
1955 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001956 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001957 *var_pp = var_p->next;
1958 /* Add it to returned list */
1959 var_p->next = old;
1960 old = var_p;
1961 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001962 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001963 }
1964 s++;
1965 }
1966 return old;
1967}
1968
1969
1970/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001971 * in_str support
1972 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001973static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001974{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001975 int ch = *i->p;
1976 if (ch != '\0') {
1977 i->p++;
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001978 i->last_char = ch;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001979 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001980 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001981 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001982}
1983
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001984static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001985{
1986 return *i->p;
1987}
1988
1989#if ENABLE_HUSH_INTERACTIVE
1990
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001991static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001992{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001993 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001994 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001995 if (G.PS1 == NULL)
1996 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001997 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001998 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001999 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002000 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002001 if (G.PS2 == NULL)
2002 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002003}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002004
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002005static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002006{
2007 const char *prompt_str;
2008 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002009 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2010 /* Set up the prompt */
2011 if (promptmode == 0) { /* PS1 */
2012 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002013 /* bash uses $PWD value, even if it is set by user.
2014 * It uses current dir only if PWD is unset.
2015 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002016 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002017 prompt_str = G.PS1;
2018 } else
2019 prompt_str = G.PS2;
2020 } else
2021 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002022 debug_printf("result '%s'\n", prompt_str);
2023 return prompt_str;
2024}
2025
2026static void get_user_input(struct in_str *i)
2027{
2028 int r;
2029 const char *prompt_str;
2030
2031 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002032# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002033 /* Enable command line editing only while a command line
2034 * is actually being read */
2035 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01002036 /* Unicode support should be activated even if LANG is set
2037 * _during_ shell execution, not only if it was set when
2038 * shell was started. Therefore, re-check LANG every time:
2039 */
2040 reinit_unicode(get_local_var_value("LANG"));
2041
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002042 G.flag_SIGINT = 0;
2043 /* buglet: SIGINT will not make new prompt to appear _at once_,
2044 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002045 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002046 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002047 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002048 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002049 i->eof_flag = (r < 0);
2050 if (i->eof_flag) { /* EOF/error detected */
2051 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2052 G.user_input_buf[1] = '\0';
2053 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02002054# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002055 do {
2056 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002057 if (i->last_char == '\0' || i->last_char == '\n') {
2058 /* Why check_and_run_traps here? Try this interactively:
2059 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2060 * $ <[enter], repeatedly...>
2061 * Without check_and_run_traps, handler never runs.
2062 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002063 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002064 fputs(prompt_str, stdout);
2065 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002066 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002067 G.user_input_buf[0] = r = fgetc(i->file);
2068 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002069 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002070 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002071# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002072 i->p = G.user_input_buf;
2073}
2074
2075#endif /* INTERACTIVE */
2076
2077/* This is the magic location that prints prompts
2078 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002079static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002080{
2081 int ch;
2082
2083 /* If there is data waiting, eat it up */
2084 if (i->p && *i->p) {
2085#if ENABLE_HUSH_INTERACTIVE
2086 take_cached:
2087#endif
2088 ch = *i->p++;
2089 if (i->eof_flag && !*i->p)
2090 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002091 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002092 } else {
2093 /* need to double check i->file because we might be doing something
2094 * more complicated by now, like sourcing or substituting. */
2095#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002096 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002097 do {
2098 get_user_input(i);
2099 } while (!*i->p); /* need non-empty line */
2100 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002101 goto take_cached;
2102 }
2103#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00002104 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002105 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002106 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002107 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002108 return ch;
2109}
2110
Denis Vlasenko913a2012009-04-05 22:17:04 +00002111/* All callers guarantee this routine will never
2112 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002113 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002114static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002115{
2116 int ch;
2117 if (i->p && *i->p) {
2118 if (i->eof_flag && !i->p[1])
2119 return EOF;
2120 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002121 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002122 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002123 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002124 i->eof_flag = (ch == EOF);
2125 i->peek_buf[0] = ch;
2126 i->peek_buf[1] = '\0';
2127 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002128 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002129 return ch;
2130}
2131
2132static void setup_file_in_str(struct in_str *i, FILE *f)
2133{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002134 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002135 i->peek = file_peek;
2136 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002137 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002138 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002139 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002140}
2141
2142static void setup_string_in_str(struct in_str *i, const char *s)
2143{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002144 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002145 i->peek = static_peek;
2146 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002147 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002148 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002149 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002150}
2151
2152
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002153/*
2154 * o_string support
2155 */
2156#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002157
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002158static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002159{
2160 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002161 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002162 if (o->data)
2163 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002164}
2165
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002166static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002167{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002168 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002169 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002170}
2171
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002172static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2173{
2174 free(o->data);
2175}
2176
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002177static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002178{
2179 if (o->length + len > o->maxlen) {
2180 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2181 o->data = xrealloc(o->data, 1 + o->maxlen);
2182 }
2183}
2184
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002185static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002186{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002187 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2188 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002189 o->data[o->length] = ch;
2190 o->length++;
2191 o->data[o->length] = '\0';
2192}
2193
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002194static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002195{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002196 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002197 memcpy(&o->data[o->length], str, len);
2198 o->length += len;
2199 o->data[o->length] = '\0';
2200}
2201
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002202static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002203{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002204 o_addblock(o, str, strlen(str));
2205}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002206
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002207#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002208static void nommu_addchr(o_string *o, int ch)
2209{
2210 if (o)
2211 o_addchr(o, ch);
2212}
2213#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002214# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002215#endif
2216
2217static void o_addstr_with_NUL(o_string *o, const char *str)
2218{
2219 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002220}
2221
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002222/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002223 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002224 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2225 * Apparently, on unquoted $v bash still does globbing
2226 * ("v='*.txt'; echo $v" prints all .txt files),
2227 * but NOT brace expansion! Thus, there should be TWO independent
2228 * quoting mechanisms on $v expansion side: one protects
2229 * $v from brace expansion, and other additionally protects "$v" against globbing.
2230 * We have only second one.
2231 */
2232
Denys Vlasenko9e800222010-10-03 14:28:04 +02002233#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002234# define MAYBE_BRACES "{}"
2235#else
2236# define MAYBE_BRACES ""
2237#endif
2238
Eric Andersen25f27032001-04-26 23:22:31 +00002239/* My analysis of quoting semantics tells me that state information
2240 * is associated with a destination, not a source.
2241 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002242static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002243{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002244 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002245 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002246 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002247 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002248 o_grow_by(o, sz);
2249 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002250 o->data[o->length] = '\\';
2251 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002252 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002253 o->data[o->length] = ch;
2254 o->length++;
2255 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002256}
2257
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002258static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002259{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002260 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002261 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2262 && strchr("*?[\\" MAYBE_BRACES, ch)
2263 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002264 sz++;
2265 o->data[o->length] = '\\';
2266 o->length++;
2267 }
2268 o_grow_by(o, sz);
2269 o->data[o->length] = ch;
2270 o->length++;
2271 o->data[o->length] = '\0';
2272}
2273
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002274static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002275{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002276 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002277 char ch;
2278 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002279 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002280 if (ordinary_cnt > len) /* paranoia */
2281 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002282 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002283 if (ordinary_cnt == len)
2284 return;
2285 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002286 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002287
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002288 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002289 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002290 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002291 sz++;
2292 o->data[o->length] = '\\';
2293 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002294 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002295 o_grow_by(o, sz);
2296 o->data[o->length] = ch;
2297 o->length++;
2298 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002299 }
2300}
2301
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002302static void o_addQblock(o_string *o, const char *str, int len)
2303{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002304 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002305 o_addblock(o, str, len);
2306 return;
2307 }
2308 o_addqblock(o, str, len);
2309}
2310
Denys Vlasenko38292b62010-09-05 14:49:40 +02002311static void o_addQstr(o_string *o, const char *str)
2312{
2313 o_addQblock(o, str, strlen(str));
2314}
2315
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002316/* A special kind of o_string for $VAR and `cmd` expansion.
2317 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002318 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002319 * list[i] contains an INDEX (int!) into this string data.
2320 * It means that if list[] needs to grow, data needs to be moved higher up
2321 * but list[i]'s need not be modified.
2322 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002323 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002324 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2325 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002326#if DEBUG_EXPAND || DEBUG_GLOB
2327static void debug_print_list(const char *prefix, o_string *o, int n)
2328{
2329 char **list = (char**)o->data;
2330 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2331 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002332
2333 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002334 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002335 prefix, list, n, string_start, o->length, o->maxlen,
2336 !!(o->o_expflags & EXP_FLAG_GLOB),
2337 o->has_quoted_part,
2338 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002339 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002340 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002341 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2342 o->data + (int)(uintptr_t)list[i] + string_start,
2343 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002344 i++;
2345 }
2346 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002347 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002348 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002349 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002350 }
2351}
2352#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002353# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002354#endif
2355
2356/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2357 * in list[n] so that it points past last stored byte so far.
2358 * It returns n+1. */
2359static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002360{
2361 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002362 int string_start;
2363 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002364
2365 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002366 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2367 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002368 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002369 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002370 /* list[n] points to string_start, make space for 16 more pointers */
2371 o->maxlen += 0x10 * sizeof(list[0]);
2372 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002373 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002374 memmove(list + n + 0x10, list + n, string_len);
2375 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002376 } else {
2377 debug_printf_list("list[%d]=%d string_start=%d\n",
2378 n, string_len, string_start);
2379 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002380 } else {
2381 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002382 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2383 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002384 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2385 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002386 o->has_empty_slot = 0;
2387 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002388 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002389 return n + 1;
2390}
2391
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002392/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002393static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002394{
2395 char **list = (char**)o->data;
2396 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2397
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002398 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002399}
2400
Denys Vlasenko9e800222010-10-03 14:28:04 +02002401#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002402/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2403 * first, it processes even {a} (no commas), second,
2404 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002405 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002406 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002407
2408/* Helper */
2409static int glob_needed(const char *s)
2410{
2411 while (*s) {
2412 if (*s == '\\') {
2413 if (!s[1])
2414 return 0;
2415 s += 2;
2416 continue;
2417 }
2418 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2419 return 1;
2420 s++;
2421 }
2422 return 0;
2423}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002424/* Return pointer to next closing brace or to comma */
2425static const char *next_brace_sub(const char *cp)
2426{
2427 unsigned depth = 0;
2428 cp++;
2429 while (*cp != '\0') {
2430 if (*cp == '\\') {
2431 if (*++cp == '\0')
2432 break;
2433 cp++;
2434 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002435 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002436 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002437 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002438 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002439 depth++;
2440 }
2441
2442 return *cp != '\0' ? cp : NULL;
2443}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002444/* Recursive brace globber. Note: may garble pattern[]. */
2445static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002446{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002447 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002448 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002449 const char *next;
2450 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002451 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002452 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002453
2454 debug_printf_glob("glob_brace('%s')\n", pattern);
2455
2456 begin = pattern;
2457 while (1) {
2458 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002459 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002460 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002461 /* Find the first sub-pattern and at the same time
2462 * find the rest after the closing brace */
2463 next = next_brace_sub(begin);
2464 if (next == NULL) {
2465 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002466 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002467 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002468 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002469 /* "{abc}" with no commas - illegal
2470 * brace expr, disregard and skip it */
2471 begin = next + 1;
2472 continue;
2473 }
2474 break;
2475 }
2476 if (*begin == '\\' && begin[1] != '\0')
2477 begin++;
2478 begin++;
2479 }
2480 debug_printf_glob("begin:%s\n", begin);
2481 debug_printf_glob("next:%s\n", next);
2482
2483 /* Now find the end of the whole brace expression */
2484 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002485 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002486 rest = next_brace_sub(rest);
2487 if (rest == NULL) {
2488 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002489 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002490 }
2491 debug_printf_glob("rest:%s\n", rest);
2492 }
2493 rest_len = strlen(++rest) + 1;
2494
2495 /* We are sure the brace expression is well-formed */
2496
2497 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002498 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002499
2500 /* We have a brace expression. BEGIN points to the opening {,
2501 * NEXT points past the terminator of the first element, and REST
2502 * points past the final }. We will accumulate result names from
2503 * recursive runs for each brace alternative in the buffer using
2504 * GLOB_APPEND. */
2505
2506 p = begin + 1;
2507 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002508 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002509 memcpy(
2510 mempcpy(
2511 mempcpy(new_pattern_buf,
2512 /* We know the prefix for all sub-patterns */
2513 pattern, begin - pattern),
2514 p, next - p),
2515 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002516
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002517 /* Note: glob_brace() may garble new_pattern_buf[].
2518 * That's why we re-copy prefix every time (1st memcpy above).
2519 */
2520 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002521 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002522 /* We saw the last entry */
2523 break;
2524 }
2525 p = next + 1;
2526 next = next_brace_sub(next);
2527 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002528 free(new_pattern_buf);
2529 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002530
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002531 simple_glob:
2532 {
2533 int gr;
2534 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002535
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002536 memset(&globdata, 0, sizeof(globdata));
2537 gr = glob(pattern, 0, NULL, &globdata);
2538 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2539 if (gr != 0) {
2540 if (gr == GLOB_NOMATCH) {
2541 globfree(&globdata);
2542 /* NB: garbles parameter */
2543 unbackslash(pattern);
2544 o_addstr_with_NUL(o, pattern);
2545 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2546 return o_save_ptr_helper(o, n);
2547 }
2548 if (gr == GLOB_NOSPACE)
2549 bb_error_msg_and_die(bb_msg_memory_exhausted);
2550 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2551 * but we didn't specify it. Paranoia again. */
2552 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2553 }
2554 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2555 char **argv = globdata.gl_pathv;
2556 while (1) {
2557 o_addstr_with_NUL(o, *argv);
2558 n = o_save_ptr_helper(o, n);
2559 argv++;
2560 if (!*argv)
2561 break;
2562 }
2563 }
2564 globfree(&globdata);
2565 }
2566 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002567}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002568/* Performs globbing on last list[],
2569 * saving each result as a new list[].
2570 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002571static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002572{
2573 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002574
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002575 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002576 if (!o->data)
2577 return o_save_ptr_helper(o, n);
2578 pattern = o->data + o_get_last_ptr(o, n);
2579 debug_printf_glob("glob pattern '%s'\n", pattern);
2580 if (!glob_needed(pattern)) {
2581 /* unbackslash last string in o in place, fix length */
2582 o->length = unbackslash(pattern) - o->data;
2583 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2584 return o_save_ptr_helper(o, n);
2585 }
2586
2587 copy = xstrdup(pattern);
2588 /* "forget" pattern in o */
2589 o->length = pattern - o->data;
2590 n = glob_brace(copy, o, n);
2591 free(copy);
2592 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002593 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002594 return n;
2595}
2596
Denys Vlasenko238081f2010-10-03 14:26:26 +02002597#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002598
2599/* Helper */
2600static int glob_needed(const char *s)
2601{
2602 while (*s) {
2603 if (*s == '\\') {
2604 if (!s[1])
2605 return 0;
2606 s += 2;
2607 continue;
2608 }
2609 if (*s == '*' || *s == '[' || *s == '?')
2610 return 1;
2611 s++;
2612 }
2613 return 0;
2614}
2615/* Performs globbing on last list[],
2616 * saving each result as a new list[].
2617 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002618static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002619{
2620 glob_t globdata;
2621 int gr;
2622 char *pattern;
2623
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002624 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002625 if (!o->data)
2626 return o_save_ptr_helper(o, n);
2627 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002628 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002629 if (!glob_needed(pattern)) {
2630 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002631 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002632 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002633 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002634 return o_save_ptr_helper(o, n);
2635 }
2636
2637 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002638 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2639 * If we glob "*.\*" and don't find anything, we need
2640 * to fall back to using literal "*.*", but GLOB_NOCHECK
2641 * will return "*.\*"!
2642 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002643 gr = glob(pattern, 0, NULL, &globdata);
2644 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002645 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002646 if (gr == GLOB_NOMATCH) {
2647 globfree(&globdata);
2648 goto literal;
2649 }
2650 if (gr == GLOB_NOSPACE)
2651 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002652 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2653 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002654 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002655 }
2656 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2657 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002658 /* "forget" pattern in o */
2659 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002660 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002661 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002662 n = o_save_ptr_helper(o, n);
2663 argv++;
2664 if (!*argv)
2665 break;
2666 }
2667 }
2668 globfree(&globdata);
2669 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002670 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002671 return n;
2672}
2673
Denys Vlasenko238081f2010-10-03 14:26:26 +02002674#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002675
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002676/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002677 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002678static int o_save_ptr(o_string *o, int n)
2679{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002680 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002681 /* If o->has_empty_slot, list[n] was already globbed
2682 * (if it was requested back then when it was filled)
2683 * so don't do that again! */
2684 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002685 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002686 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002687 return o_save_ptr_helper(o, n);
2688}
2689
2690/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002691static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002692{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002693 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002694 int string_start;
2695
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002696 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2697 if (DEBUG_EXPAND)
2698 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002699 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002700 list = (char**)o->data;
2701 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2702 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002703 while (n) {
2704 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002705 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002706 }
2707 return list;
2708}
2709
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002710static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002711
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002712/* Returns pi->next - next pipe in the list */
2713static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002714{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002715 struct pipe *next;
2716 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002717
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002718 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002719 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002720 struct command *command;
2721 struct redir_struct *r, *rnext;
2722
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002723 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002724 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002725 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002726 if (DEBUG_CLEAN) {
2727 int a;
2728 char **p;
2729 for (a = 0, p = command->argv; *p; a++, p++) {
2730 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2731 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002732 }
2733 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002734 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002735 }
2736 /* not "else if": on syntax error, we may have both! */
2737 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002738 debug_printf_clean(" begin group (cmd_type:%d)\n",
2739 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002740 free_pipe_list(command->group);
2741 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002742 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002743 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002744 /* else is crucial here.
2745 * If group != NULL, child_func is meaningless */
2746#if ENABLE_HUSH_FUNCTIONS
2747 else if (command->child_func) {
2748 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2749 command->child_func->parent_cmd = NULL;
2750 }
2751#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002752#if !BB_MMU
2753 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002754 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002755#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002756 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002757 debug_printf_clean(" redirect %d%s",
2758 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002759 /* guard against the case >$FOO, where foo is unset or blank */
2760 if (r->rd_filename) {
2761 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2762 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002763 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002764 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002765 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002766 rnext = r->next;
2767 free(r);
2768 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002769 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002770 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002771 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002772 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002773#if ENABLE_HUSH_JOB
2774 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002775 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002776#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002777
2778 next = pi->next;
2779 free(pi);
2780 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002781}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002782
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002783static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002784{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002785 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002786#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002787 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002788#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002789 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002790 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002791 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002792}
2793
2794
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002795/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002796
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002797#ifndef debug_print_tree
2798static void debug_print_tree(struct pipe *pi, int lvl)
2799{
2800 static const char *const PIPE[] = {
2801 [PIPE_SEQ] = "SEQ",
2802 [PIPE_AND] = "AND",
2803 [PIPE_OR ] = "OR" ,
2804 [PIPE_BG ] = "BG" ,
2805 };
2806 static const char *RES[] = {
2807 [RES_NONE ] = "NONE" ,
2808# if ENABLE_HUSH_IF
2809 [RES_IF ] = "IF" ,
2810 [RES_THEN ] = "THEN" ,
2811 [RES_ELIF ] = "ELIF" ,
2812 [RES_ELSE ] = "ELSE" ,
2813 [RES_FI ] = "FI" ,
2814# endif
2815# if ENABLE_HUSH_LOOPS
2816 [RES_FOR ] = "FOR" ,
2817 [RES_WHILE] = "WHILE",
2818 [RES_UNTIL] = "UNTIL",
2819 [RES_DO ] = "DO" ,
2820 [RES_DONE ] = "DONE" ,
2821# endif
2822# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2823 [RES_IN ] = "IN" ,
2824# endif
2825# if ENABLE_HUSH_CASE
2826 [RES_CASE ] = "CASE" ,
2827 [RES_CASE_IN ] = "CASE_IN" ,
2828 [RES_MATCH] = "MATCH",
2829 [RES_CASE_BODY] = "CASE_BODY",
2830 [RES_ESAC ] = "ESAC" ,
2831# endif
2832 [RES_XXXX ] = "XXXX" ,
2833 [RES_SNTX ] = "SNTX" ,
2834 };
2835 static const char *const CMDTYPE[] = {
2836 "{}",
2837 "()",
2838 "[noglob]",
2839# if ENABLE_HUSH_FUNCTIONS
2840 "func()",
2841# endif
2842 };
2843
2844 int pin, prn;
2845
2846 pin = 0;
2847 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002848 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002849 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2850 prn = 0;
2851 while (prn < pi->num_cmds) {
2852 struct command *command = &pi->cmds[prn];
2853 char **argv = command->argv;
2854
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002855 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002856 lvl*2, "", prn,
2857 command->assignment_cnt);
2858 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002859 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002860 CMDTYPE[command->cmd_type],
2861 argv
2862# if !BB_MMU
2863 , " group_as_string:", command->group_as_string
2864# else
2865 , "", ""
2866# endif
2867 );
2868 debug_print_tree(command->group, lvl+1);
2869 prn++;
2870 continue;
2871 }
2872 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002873 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002874 argv++;
2875 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002876 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002877 prn++;
2878 }
2879 pi = pi->next;
2880 pin++;
2881 }
2882}
2883#endif /* debug_print_tree */
2884
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002885static struct pipe *new_pipe(void)
2886{
Eric Andersen25f27032001-04-26 23:22:31 +00002887 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002888 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002889 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002890 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002891 return pi;
2892}
2893
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002894/* Command (member of a pipe) is complete, or we start a new pipe
2895 * if ctx->command is NULL.
2896 * No errors possible here.
2897 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002898static int done_command(struct parse_context *ctx)
2899{
2900 /* The command is really already in the pipe structure, so
2901 * advance the pipe counter and make a new, null command. */
2902 struct pipe *pi = ctx->pipe;
2903 struct command *command = ctx->command;
2904
2905 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002906 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002907 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002908 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002909 }
2910 pi->num_cmds++;
2911 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002912 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002913 } else {
2914 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2915 }
2916
2917 /* Only real trickiness here is that the uncommitted
2918 * command structure is not counted in pi->num_cmds. */
2919 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002920 ctx->command = command = &pi->cmds[pi->num_cmds];
2921 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002922 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002923 return pi->num_cmds; /* used only for 0/nonzero check */
2924}
2925
2926static void done_pipe(struct parse_context *ctx, pipe_style type)
2927{
2928 int not_null;
2929
2930 debug_printf_parse("done_pipe entered, followup %d\n", type);
2931 /* Close previous command */
2932 not_null = done_command(ctx);
2933 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002934#if HAS_KEYWORDS
2935 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2936 ctx->ctx_inverted = 0;
2937 ctx->pipe->res_word = ctx->ctx_res_w;
2938#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002939
2940 /* Without this check, even just <enter> on command line generates
2941 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002942 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002943 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002944#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002945 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002946#endif
2947#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002948 || ctx->ctx_res_w == RES_DONE
2949 || ctx->ctx_res_w == RES_FOR
2950 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002951#endif
2952#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002953 || ctx->ctx_res_w == RES_ESAC
2954#endif
2955 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002956 struct pipe *new_p;
2957 debug_printf_parse("done_pipe: adding new pipe: "
2958 "not_null:%d ctx->ctx_res_w:%d\n",
2959 not_null, ctx->ctx_res_w);
2960 new_p = new_pipe();
2961 ctx->pipe->next = new_p;
2962 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002963 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002964 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002965 * This is used to control execution.
2966 * RES_FOR and RES_IN are NOT sticky (needed to support
2967 * cases where variable or value happens to match a keyword):
2968 */
2969#if ENABLE_HUSH_LOOPS
2970 if (ctx->ctx_res_w == RES_FOR
2971 || ctx->ctx_res_w == RES_IN)
2972 ctx->ctx_res_w = RES_NONE;
2973#endif
2974#if ENABLE_HUSH_CASE
2975 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002976 ctx->ctx_res_w = RES_CASE_BODY;
2977 if (ctx->ctx_res_w == RES_CASE)
2978 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002979#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002980 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002981 /* Create the memory for command, roughly:
2982 * ctx->pipe->cmds = new struct command;
2983 * ctx->command = &ctx->pipe->cmds[0];
2984 */
2985 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002986 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002987 }
2988 debug_printf_parse("done_pipe return\n");
2989}
2990
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002991static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002992{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002993 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002994 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002995 /* Create the memory for command, roughly:
2996 * ctx->pipe->cmds = new struct command;
2997 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002998 */
2999 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003000}
3001
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003002/* If a reserved word is found and processed, parse context is modified
3003 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003004 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003005#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003006struct reserved_combo {
3007 char literal[6];
3008 unsigned char res;
3009 unsigned char assignment_flag;
3010 int flag;
3011};
3012enum {
3013 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003014# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003015 FLAG_IF = (1 << RES_IF ),
3016 FLAG_THEN = (1 << RES_THEN ),
3017 FLAG_ELIF = (1 << RES_ELIF ),
3018 FLAG_ELSE = (1 << RES_ELSE ),
3019 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003020# endif
3021# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003022 FLAG_FOR = (1 << RES_FOR ),
3023 FLAG_WHILE = (1 << RES_WHILE),
3024 FLAG_UNTIL = (1 << RES_UNTIL),
3025 FLAG_DO = (1 << RES_DO ),
3026 FLAG_DONE = (1 << RES_DONE ),
3027 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003028# endif
3029# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003030 FLAG_MATCH = (1 << RES_MATCH),
3031 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003032# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003033 FLAG_START = (1 << RES_XXXX ),
3034};
3035
3036static const struct reserved_combo* match_reserved_word(o_string *word)
3037{
Eric Andersen25f27032001-04-26 23:22:31 +00003038 /* Mostly a list of accepted follow-up reserved words.
3039 * FLAG_END means we are done with the sequence, and are ready
3040 * to turn the compound list into a command.
3041 * FLAG_START means the word must start a new compound list.
3042 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003043 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003044# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003045 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3046 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3047 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3048 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3049 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3050 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003051# endif
3052# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003053 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3054 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3055 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3056 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3057 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3058 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003059# endif
3060# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003061 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3062 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003063# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003064 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003065 const struct reserved_combo *r;
3066
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003067 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003068 if (strcmp(word->data, r->literal) == 0)
3069 return r;
3070 }
3071 return NULL;
3072}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003073/* Return 0: not a keyword, 1: keyword
3074 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003075static int reserved_word(o_string *word, struct parse_context *ctx)
3076{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003077# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003078 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003079 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003080 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003081# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003082 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003083
Denys Vlasenko38292b62010-09-05 14:49:40 +02003084 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003085 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003086 r = match_reserved_word(word);
3087 if (!r)
3088 return 0;
3089
3090 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003091# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003092 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3093 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003094 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003095 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003096# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003097 if (r->flag == 0) { /* '!' */
3098 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003099 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003100 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003101 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003102 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003103 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003104 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003105 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003106 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003107
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003108 old = xmalloc(sizeof(*old));
3109 debug_printf_parse("push stack %p\n", old);
3110 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003111 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003112 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003113 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003114 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003115 ctx->ctx_res_w = RES_SNTX;
3116 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003117 } else {
3118 /* "{...} fi" is ok. "{...} if" is not
3119 * Example:
3120 * if { echo foo; } then { echo bar; } fi */
3121 if (ctx->command->group)
3122 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003123 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003124
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003125 ctx->ctx_res_w = r->res;
3126 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003127 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003128 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003129
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003130 if (ctx->old_flag & FLAG_END) {
3131 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003132
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003133 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003134 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003135 old = ctx->stack;
3136 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003137 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003138# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003139 o_addstr(&old->as_string, ctx->as_string.data);
3140 o_free_unsafe(&ctx->as_string);
3141 old->command->group_as_string = xstrdup(old->as_string.data);
3142 debug_printf_parse("pop, remembering as:'%s'\n",
3143 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003144# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003145 *ctx = *old; /* physical copy */
3146 free(old);
3147 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003148 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003149}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003150#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003151
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003152/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003153 * Normal return is 0. Syntax errors return 1.
3154 * Note: on return, word is reset, but not o_free'd!
3155 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003156static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003157{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003158 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003159
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003160 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003161 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003162 debug_printf_parse("done_word return 0: true null, ignored\n");
3163 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003164 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003165
Eric Andersen25f27032001-04-26 23:22:31 +00003166 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003167 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3168 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003169 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3170 * "2.7 Redirection
3171 * ...the word that follows the redirection operator
3172 * shall be subjected to tilde expansion, parameter expansion,
3173 * command substitution, arithmetic expansion, and quote
3174 * removal. Pathname expansion shall not be performed
3175 * on the word by a non-interactive shell; an interactive
3176 * shell may perform it, but shall do so only when
3177 * the expansion would result in one word."
3178 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003179 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003180 /* Cater for >\file case:
3181 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3182 * Same with heredocs:
3183 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3184 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003185 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3186 unbackslash(ctx->pending_redirect->rd_filename);
3187 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003188 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003189 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3190 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003191 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003192 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003193 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003194 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003195#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003196# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003197 if (ctx->ctx_dsemicolon
3198 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3199 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003200 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003201 /* ctx->ctx_res_w = RES_MATCH; */
3202 ctx->ctx_dsemicolon = 0;
3203 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003204# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003205 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003206# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003207 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3208 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003209# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003210# if ENABLE_HUSH_CASE
3211 && ctx->ctx_res_w != RES_CASE
3212# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003213 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003214 int reserved = reserved_word(word, ctx);
3215 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3216 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003217 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003218 debug_printf_parse("done_word return %d\n",
3219 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003220 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003221 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003222# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003223 if (strcmp(word->data, "[[") == 0) {
3224 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3225 }
3226 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003227# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003228 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003229#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003230 if (command->group) {
3231 /* "{ echo foo; } echo bar" - bad */
3232 syntax_error_at(word->data);
3233 debug_printf_parse("done_word return 1: syntax error, "
3234 "groups and arglists don't mix\n");
3235 return 1;
3236 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003237
3238 /* If this word wasn't an assignment, next ones definitely
3239 * can't be assignments. Even if they look like ones. */
3240 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3241 && word->o_assignment != WORD_IS_KEYWORD
3242 ) {
3243 word->o_assignment = NOT_ASSIGNMENT;
3244 } else {
3245 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3246 command->assignment_cnt++;
3247 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3248 }
3249 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3250 word->o_assignment = MAYBE_ASSIGNMENT;
3251 }
3252 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3253
Denys Vlasenko38292b62010-09-05 14:49:40 +02003254 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003255 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3256 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003257 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003258 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003259 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003260 char *p = word->data;
3261 while (p[0] == SPECIAL_VAR_SYMBOL
3262 && (p[1] & 0x7f) == '@'
3263 && p[2] == SPECIAL_VAR_SYMBOL
3264 ) {
3265 p += 3;
3266 }
3267 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003268 /* saw no "$@", or not only "$@" but some
3269 * real text is there too */
3270 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003271 * e.g. "", $empty"" etc to not disappear */
3272 o_addchr(word, SPECIAL_VAR_SYMBOL);
3273 o_addchr(word, SPECIAL_VAR_SYMBOL);
3274 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003275 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003276 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003277 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003278 }
Eric Andersen25f27032001-04-26 23:22:31 +00003279
Denis Vlasenko06810332007-05-21 23:30:54 +00003280#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003281 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003282 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003283 || !is_well_formed_var_name(command->argv[0], '\0')
3284 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003285 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003286 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003287 return 1;
3288 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003289 /* Force FOR to have just one word (variable name) */
3290 /* NB: basically, this makes hush see "for v in ..."
3291 * syntax as if it is "for v; in ...". FOR and IN become
3292 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003293 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003294 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003295#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003296#if ENABLE_HUSH_CASE
3297 /* Force CASE to have just one word */
3298 if (ctx->ctx_res_w == RES_CASE) {
3299 done_pipe(ctx, PIPE_SEQ);
3300 }
3301#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003302
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003303 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003304
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003305 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003306 return 0;
3307}
3308
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003309
3310/* Peek ahead in the input to find out if we have a "&n" construct,
3311 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003312 * Return:
3313 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3314 * REDIRFD_SYNTAX_ERR if syntax error,
3315 * REDIRFD_TO_FILE if no & was seen,
3316 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003317 */
3318#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003319#define parse_redir_right_fd(as_string, input) \
3320 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003321#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003322static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003323{
3324 int ch, d, ok;
3325
3326 ch = i_peek(input);
3327 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003328 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003329
3330 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003331 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003332 ch = i_peek(input);
3333 if (ch == '-') {
3334 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003335 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003336 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003337 }
3338 d = 0;
3339 ok = 0;
3340 while (ch != EOF && isdigit(ch)) {
3341 d = d*10 + (ch-'0');
3342 ok = 1;
3343 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003344 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003345 ch = i_peek(input);
3346 }
3347 if (ok) return d;
3348
3349//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3350
3351 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003352 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003353}
3354
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003355/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003356 */
3357static int parse_redirect(struct parse_context *ctx,
3358 int fd,
3359 redir_type style,
3360 struct in_str *input)
3361{
3362 struct command *command = ctx->command;
3363 struct redir_struct *redir;
3364 struct redir_struct **redirp;
3365 int dup_num;
3366
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003367 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003368 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003369 /* Check for a '>&1' type redirect */
3370 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3371 if (dup_num == REDIRFD_SYNTAX_ERR)
3372 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003373 } else {
3374 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003375 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003376 if (dup_num) { /* <<-... */
3377 ch = i_getch(input);
3378 nommu_addchr(&ctx->as_string, ch);
3379 ch = i_peek(input);
3380 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003381 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003382
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003383 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003384 int ch = i_peek(input);
3385 if (ch == '|') {
3386 /* >|FILE redirect ("clobbering" >).
3387 * Since we do not support "set -o noclobber" yet,
3388 * >| and > are the same for now. Just eat |.
3389 */
3390 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003391 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003392 }
3393 }
3394
3395 /* Create a new redir_struct and append it to the linked list */
3396 redirp = &command->redirects;
3397 while ((redir = *redirp) != NULL) {
3398 redirp = &(redir->next);
3399 }
3400 *redirp = redir = xzalloc(sizeof(*redir));
3401 /* redir->next = NULL; */
3402 /* redir->rd_filename = NULL; */
3403 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003404 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003405
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003406 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3407 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003408
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003409 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003410 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003411 /* Erik had a check here that the file descriptor in question
3412 * is legit; I postpone that to "run time"
3413 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003414 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3415 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003416 } else {
3417 /* Set ctx->pending_redirect, so we know what to do at the
3418 * end of the next parsed word. */
3419 ctx->pending_redirect = redir;
3420 }
3421 return 0;
3422}
3423
Eric Andersen25f27032001-04-26 23:22:31 +00003424/* If a redirect is immediately preceded by a number, that number is
3425 * supposed to tell which file descriptor to redirect. This routine
3426 * looks for such preceding numbers. In an ideal world this routine
3427 * needs to handle all the following classes of redirects...
3428 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3429 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3430 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3431 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003432 *
3433 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3434 * "2.7 Redirection
3435 * ... If n is quoted, the number shall not be recognized as part of
3436 * the redirection expression. For example:
3437 * echo \2>a
3438 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003439 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003440 *
3441 * A -1 return means no valid number was found,
3442 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003443 */
3444static int redirect_opt_num(o_string *o)
3445{
3446 int num;
3447
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003448 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003449 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003450 num = bb_strtou(o->data, NULL, 10);
3451 if (errno || num < 0)
3452 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003453 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003454 return num;
3455}
3456
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003457#if BB_MMU
3458#define fetch_till_str(as_string, input, word, skip_tabs) \
3459 fetch_till_str(input, word, skip_tabs)
3460#endif
3461static char *fetch_till_str(o_string *as_string,
3462 struct in_str *input,
3463 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003464 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003465{
3466 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003467 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003468 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003469 int ch;
3470
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003471 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003472
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003473 while (1) {
3474 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003475 if (ch != EOF)
3476 nommu_addchr(as_string, ch);
3477 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003478 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3479 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003480 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3481 heredoc.data[past_EOL] = '\0';
3482 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3483 return heredoc.data;
3484 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003485 while (ch == '\n') {
3486 o_addchr(&heredoc, ch);
3487 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003488 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003489 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003490 do {
3491 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003492 if (ch != EOF)
3493 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003494 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003495 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003496 }
3497 if (ch == EOF) {
3498 o_free_unsafe(&heredoc);
3499 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003500 }
3501 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003502 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003503 if (prev == '\\' && ch == '\\')
3504 /* Correctly handle foo\\<eol> (not a line cont.) */
3505 prev = 0; /* not \ */
3506 else
3507 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003508 }
3509}
3510
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003511/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3512 * and load them all. There should be exactly heredoc_cnt of them.
3513 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003514static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3515{
3516 struct pipe *pi = ctx->list_head;
3517
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003518 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003519 int i;
3520 struct command *cmd = pi->cmds;
3521
3522 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3523 pi->num_cmds,
3524 cmd->argv ? cmd->argv[0] : "NONE");
3525 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003526 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003527
3528 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3529 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003530 while (redir) {
3531 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003532 char *p;
3533
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003534 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003535 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003536 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003537 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003538 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003539 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003540 return 1;
3541 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003542 free(redir->rd_filename);
3543 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003544 heredoc_cnt--;
3545 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003546 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003547 }
3548 cmd++;
3549 }
3550 pi = pi->next;
3551 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003552#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003553 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003554 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003555 bb_error_msg_and_die("heredoc BUG 2");
3556#endif
3557 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003558}
3559
3560
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003561static int run_list(struct pipe *pi);
3562#if BB_MMU
3563#define parse_stream(pstring, input, end_trigger) \
3564 parse_stream(input, end_trigger)
3565#endif
3566static struct pipe *parse_stream(char **pstring,
3567 struct in_str *input,
3568 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003569
Eric Andersen25f27032001-04-26 23:22:31 +00003570
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003571#if !ENABLE_HUSH_FUNCTIONS
3572#define parse_group(dest, ctx, input, ch) \
3573 parse_group(ctx, input, ch)
3574#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003575static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003576 struct in_str *input, int ch)
3577{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003578 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003579 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003580 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003581 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003582 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003583 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003584
3585 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003586#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003587 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003588 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003589 if (done_word(dest, ctx))
3590 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003591 if (!command->argv)
3592 goto skip; /* (... */
3593 if (command->argv[1]) { /* word word ... (... */
3594 syntax_error_unexpected_ch('(');
3595 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003596 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003597 /* it is "word(..." or "word (..." */
3598 do
3599 ch = i_getch(input);
3600 while (ch == ' ' || ch == '\t');
3601 if (ch != ')') {
3602 syntax_error_unexpected_ch(ch);
3603 return 1;
3604 }
3605 nommu_addchr(&ctx->as_string, ch);
3606 do
3607 ch = i_getch(input);
3608 while (ch == ' ' || ch == '\t' || ch == '\n');
3609 if (ch != '{') {
3610 syntax_error_unexpected_ch(ch);
3611 return 1;
3612 }
3613 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003614 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003615 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003616 }
3617#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003618
3619#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003620 if (command->argv /* word [word]{... */
3621 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003622 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003623 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003624 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003625 debug_printf_parse("parse_group return 1: "
3626 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003627 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003628 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003629#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003630
3631#if ENABLE_HUSH_FUNCTIONS
3632 skip:
3633#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003634 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003635 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003636 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003637 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003638 } else {
3639 /* bash does not allow "{echo...", requires whitespace */
3640 ch = i_getch(input);
3641 if (ch != ' ' && ch != '\t' && ch != '\n') {
3642 syntax_error_unexpected_ch(ch);
3643 return 1;
3644 }
3645 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003646 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003647
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003648 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003649#if BB_MMU
3650# define as_string NULL
3651#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003652 char *as_string = NULL;
3653#endif
3654 pipe_list = parse_stream(&as_string, input, endch);
3655#if !BB_MMU
3656 if (as_string)
3657 o_addstr(&ctx->as_string, as_string);
3658#endif
3659 /* empty ()/{} or parse error? */
3660 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003661 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003662 if (!BB_MMU)
3663 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003664 debug_printf_parse("parse_group return 1: "
3665 "parse_stream returned %p\n", pipe_list);
3666 return 1;
3667 }
3668 command->group = pipe_list;
3669#if !BB_MMU
3670 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3671 command->group_as_string = as_string;
3672 debug_printf_parse("end of group, remembering as:'%s'\n",
3673 command->group_as_string);
3674#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003675#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003676 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003677 debug_printf_parse("parse_group return 0\n");
3678 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003679 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003680}
3681
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003682#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003683/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003684static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003685/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003686static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003687{
3688 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003689 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003690 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003691 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003692 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003693 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003694 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003695 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003696 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003697 }
3698}
3699/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003700static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003701{
3702 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003703 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003704 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003705 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003706 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003707 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003708 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003709 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003710 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003711 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003712 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003713 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003714 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003715 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003716 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3717 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003718 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003719 continue;
3720 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003721 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003722 }
3723}
3724/* Process `cmd` - copy contents until "`" is seen. Complicated by
3725 * \` quoting.
3726 * "Within the backquoted style of command substitution, backslash
3727 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3728 * The search for the matching backquote shall be satisfied by the first
3729 * backquote found without a preceding backslash; during this search,
3730 * if a non-escaped backquote is encountered within a shell comment,
3731 * a here-document, an embedded command substitution of the $(command)
3732 * form, or a quoted string, undefined results occur. A single-quoted
3733 * or double-quoted string that begins, but does not end, within the
3734 * "`...`" sequence produces undefined results."
3735 * Example Output
3736 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3737 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003738static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003739{
3740 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003741 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003742 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003743 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003744 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003745 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3746 ch = i_getch(input);
3747 if (ch != '`'
3748 && ch != '$'
3749 && ch != '\\'
3750 && (!in_dquote || ch != '"')
3751 ) {
3752 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003753 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003754 }
3755 if (ch == EOF) {
3756 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003757 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003758 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003759 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003760 }
3761}
3762/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3763 * quoting and nested ()s.
3764 * "With the $(command) style of command substitution, all characters
3765 * following the open parenthesis to the matching closing parenthesis
3766 * constitute the command. Any valid shell script can be used for command,
3767 * except a script consisting solely of redirections which produces
3768 * unspecified results."
3769 * Example Output
3770 * echo $(echo '(TEST)' BEST) (TEST) BEST
3771 * echo $(echo 'TEST)' BEST) TEST) BEST
3772 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003773 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003774 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003775 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003776 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3777 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003778 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003779#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003780static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003781{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003782 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003783 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003784# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003785 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003786# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003787 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3788
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003789 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003790 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003791 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003792 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003793 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003794 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003795 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003796 if (!dbl)
3797 break;
3798 /* we look for closing )) of $((EXPR)) */
3799 if (i_peek(input) == end_ch) {
3800 i_getch(input); /* eat second ')' */
3801 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003802 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003803 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003804 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003805 if (ch == '(' || ch == '{') {
3806 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003807 if (!add_till_closing_bracket(dest, input, ch))
3808 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003809 o_addchr(dest, ch);
3810 continue;
3811 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003812 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003813 if (!add_till_single_quote(dest, input))
3814 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003815 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003816 continue;
3817 }
3818 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003819 if (!add_till_double_quote(dest, input))
3820 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003821 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003822 continue;
3823 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003824 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003825 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3826 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003827 o_addchr(dest, ch);
3828 continue;
3829 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003830 if (ch == '\\') {
3831 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003832 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003833 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003834 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003835 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003836 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003837 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003838 continue;
3839 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003840 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003841 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003842}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003843#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003844
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003845/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003846#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003847#define parse_dollar(as_string, dest, input, quote_mask) \
3848 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003849#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003850#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003851static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003852 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003853 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003854{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003855 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003856
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003857 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003858 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003859 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003860 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003861 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003862 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003863 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003864 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003865 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003866 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003867 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003868 if (!isalnum(ch) && ch != '_')
3869 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003870 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003871 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003872 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003873 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003874 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003875 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003876 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003877 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003878 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003879 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003880 o_addchr(dest, ch | quote_mask);
3881 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003882 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003883 case '$': /* pid */
3884 case '!': /* last bg pid */
3885 case '?': /* last exit code */
3886 case '#': /* number of args */
3887 case '*': /* args */
3888 case '@': /* args */
3889 goto make_one_char_var;
3890 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003891 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3892
Denys Vlasenko74369502010-05-21 19:52:01 +02003893 ch = i_getch(input); /* eat '{' */
3894 nommu_addchr(as_string, ch);
3895
3896 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003897 /* It should be ${?}, or ${#var},
3898 * or even ${?+subst} - operator acting on a special variable,
3899 * or the beginning of variable name.
3900 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003901 if (ch == EOF
3902 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3903 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003904 bad_dollar_syntax:
3905 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003906 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3907 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02003908 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003909 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003910 ch |= quote_mask;
3911
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003912 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003913 * However, this regresses some of our testsuite cases
3914 * which check invalid constructs like ${%}.
3915 * Oh well... let's check that the var name part is fine... */
3916
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003917 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003918 unsigned pos;
3919
Denys Vlasenko74369502010-05-21 19:52:01 +02003920 o_addchr(dest, ch);
3921 debug_printf_parse(": '%c'\n", ch);
3922
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003923 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003924 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003925 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003926 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003927
Denys Vlasenko74369502010-05-21 19:52:01 +02003928 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003929 unsigned end_ch;
3930 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003931 /* handle parameter expansions
3932 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3933 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003934 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003935 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003936
3937 /* Eat everything until closing '}' (or ':') */
3938 end_ch = '}';
3939 if (ENABLE_HUSH_BASH_COMPAT
3940 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003941 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003942 ) {
3943 /* It's ${var:N[:M]} thing */
3944 end_ch = '}' * 0x100 + ':';
3945 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003946 if (ENABLE_HUSH_BASH_COMPAT
3947 && ch == '/'
3948 ) {
3949 /* It's ${var/[/]pattern[/repl]} thing */
3950 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3951 i_getch(input);
3952 nommu_addchr(as_string, '/');
3953 ch = '\\';
3954 }
3955 end_ch = '}' * 0x100 + '/';
3956 }
3957 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003958 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003959 if (!BB_MMU)
3960 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003961#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003962 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003963 if (last_ch == 0) /* error? */
3964 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003965#else
3966#error Simple code to only allow ${var} is not implemented
3967#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003968 if (as_string) {
3969 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003970 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003971 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003972
3973 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3974 /* close the first block: */
3975 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003976 /* while parsing N from ${var:N[:M]}
3977 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003978 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003979 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003980 end_ch = '}';
3981 goto again;
3982 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003983 /* got '}' */
3984 if (end_ch == '}' * 0x100 + ':') {
3985 /* it's ${var:N} - emulate :999999999 */
3986 o_addstr(dest, "999999999");
3987 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003988 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003989 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003990 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003991 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003992 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3993 break;
3994 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003995#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003996 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003997 unsigned pos;
3998
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003999 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004000 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004001# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004002 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004003 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004004 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004005 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4006 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004007 if (!BB_MMU)
4008 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004009 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4010 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004011 if (as_string) {
4012 o_addstr(as_string, dest->data + pos);
4013 o_addchr(as_string, ')');
4014 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004015 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004016 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004017 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004018 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004019# endif
4020# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004021 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4022 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004023 if (!BB_MMU)
4024 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004025 if (!add_till_closing_bracket(dest, input, ')'))
4026 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004027 if (as_string) {
4028 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004029 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004030 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004031 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004032# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004033 break;
4034 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004035#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004036 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004037 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004038 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004039 ch = i_peek(input);
4040 if (isalnum(ch)) { /* it's $_name or $_123 */
4041 ch = '_';
4042 goto make_var;
4043 }
4044 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004045 /* TODO: $_ and $-: */
4046 /* $_ Shell or shell script name; or last argument of last command
4047 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4048 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004049 /* $- Option flags set by set builtin or shell options (-i etc) */
4050 default:
4051 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004052 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004053 debug_printf_parse("parse_dollar return 1 (ok)\n");
4054 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004055#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004056}
4057
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004058#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004059# if ENABLE_HUSH_BASH_COMPAT
4060#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4061 encode_string(dest, input, dquote_end, process_bkslash)
4062# else
4063/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4064#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4065 encode_string(dest, input, dquote_end)
4066# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004067#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004068
4069#else /* !MMU */
4070
4071# if ENABLE_HUSH_BASH_COMPAT
4072/* all parameters are needed, no macro tricks */
4073# else
4074#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4075 encode_string(as_string, dest, input, dquote_end)
4076# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004077#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004078static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004079 o_string *dest,
4080 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004081 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004082 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004083{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004084#if !ENABLE_HUSH_BASH_COMPAT
4085 const int process_bkslash = 1;
4086#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004087 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004088 int next;
4089
4090 again:
4091 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004092 if (ch != EOF)
4093 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004094 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004095 debug_printf_parse("encode_string return 1 (ok)\n");
4096 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004097 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004098 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004099 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004100 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004101 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004102 }
4103 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004104 if (ch != '\n') {
4105 next = i_peek(input);
4106 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004107 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004108 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004109 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004110 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004111 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004112 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004113 }
4114 /* bash:
4115 * "The backslash retains its special meaning [in "..."]
4116 * only when followed by one of the following characters:
4117 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004118 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004119 * NB: in (unquoted) heredoc, above does not apply to ",
4120 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004121 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004122 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004123 ch = i_getch(input); /* eat next */
4124 if (ch == '\n')
4125 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004126 } /* else: ch remains == '\\', and we double it below: */
4127 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004128 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004129 goto again;
4130 }
4131 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004132 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4133 debug_printf_parse("encode_string return 0: "
4134 "parse_dollar returned 0 (error)\n");
4135 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004136 }
4137 goto again;
4138 }
4139#if ENABLE_HUSH_TICK
4140 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004141 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004142 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4143 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004144 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4145 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004146 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4147 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004148 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004149 }
4150#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004151 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004152 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004153#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004154}
4155
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004156/*
4157 * Scan input until EOF or end_trigger char.
4158 * Return a list of pipes to execute, or NULL on EOF
4159 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004160 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004161 * reset parsing machinery and start parsing anew,
4162 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004163 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004164static struct pipe *parse_stream(char **pstring,
4165 struct in_str *input,
4166 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004167{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004168 struct parse_context ctx;
4169 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004170 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004171
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004172 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004173 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004174 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004175 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004176 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004177 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004178
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004179 /* If very first arg is "" or '', dest.data may end up NULL.
4180 * Preventing this: */
4181 o_addchr(&dest, '\0');
4182 dest.length = 0;
4183
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004184 /* We used to separate words on $IFS here. This was wrong.
4185 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004186 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004187 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004188
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004189 if (MAYBE_ASSIGNMENT != 0)
4190 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004191 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004192 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004193 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004194 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004195 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004196 int ch;
4197 int next;
4198 int redir_fd;
4199 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004200
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004201 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004202 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004203 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004204 if (ch == EOF) {
4205 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004206
4207 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004208 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004209 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004210 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004211 /* end_trigger == '}' case errors out earlier,
4212 * checking only ')' */
4213 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004214 syntax_error_unterm_ch('(');
4215 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004216 }
4217
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004218 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004219 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004220 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004221 o_free(&dest);
4222 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004223 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004224 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004225 /* (this makes bare "&" cmd a no-op.
4226 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004227 if (pi->num_cmds == 0
4228 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4229 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004230 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004231 pi = NULL;
4232 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004233#if !BB_MMU
4234 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4235 if (pstring)
4236 *pstring = ctx.as_string.data;
4237 else
4238 o_free_unsafe(&ctx.as_string);
4239#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004240 debug_leave();
4241 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004242 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004243 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004244 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004245
4246 next = '\0';
4247 if (ch != '\n')
4248 next = i_peek(input);
4249
4250 is_special = "{}<>;&|()#'" /* special outside of "str" */
4251 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4252 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004253 if (ctx.command->argv /* word [word]{... - non-special */
4254 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004255 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004256 || (next != ';' /* }; - special */
4257 && next != ')' /* }) - special */
4258 && next != '&' /* }& and }&& ... - special */
4259 && next != '|' /* }|| ... - special */
4260 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004261 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004262 ) {
4263 /* They are not special, skip "{}" */
4264 is_special += 2;
4265 }
4266 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004267 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004268
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004269 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004270 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004271 o_addQchr(&dest, ch);
4272 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4273 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004274 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004275 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004276 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004277 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004278 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004279 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004280 continue;
4281 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004282
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004283 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004284 if (done_word(&dest, &ctx)) {
4285 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004286 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004287 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004288 /* Is this a case when newline is simply ignored?
4289 * Some examples:
4290 * "cmd | <newline> cmd ..."
4291 * "case ... in <newline> word) ..."
4292 */
4293 if (IS_NULL_CMD(ctx.command)
4294 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004295 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004296 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004297 * Without check #1, interactive shell
4298 * ignores even bare <newline>,
4299 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004300 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004301 * ps2> _ <=== wrong, should be ps1
4302 * Without check #2, "cmd & <newline>"
4303 * is similarly mistreated.
4304 * (BTW, this makes "cmd & cmd"
4305 * and "cmd && cmd" non-orthogonal.
4306 * Really, ask yourself, why
4307 * "cmd && <newline>" doesn't start
4308 * cmd but waits for more input?
4309 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004310 */
4311 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004312 if (pi->num_cmds != 0 /* check #1 */
4313 && pi->followup != PIPE_BG /* check #2 */
4314 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004315 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004316 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004317 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004318 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004319 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004320 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4321 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004322 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004323 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004324 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004325 heredoc_cnt = 0;
4326 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004327 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004328 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004329 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004330 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004331 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004332 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004333 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004334
4335 /* "cmd}" or "cmd }..." without semicolon or &:
4336 * } is an ordinary char in this case, even inside { cmd; }
4337 * Pathological example: { ""}; } should exec "}" cmd
4338 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004339 if (ch == '}') {
4340 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4341 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004342 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004343 ) {
4344 goto ordinary_char;
4345 }
4346 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4347 goto skip_end_trigger;
4348 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004349 }
4350
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004351 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004352 && (ch != ';' || heredoc_cnt == 0)
4353#if ENABLE_HUSH_CASE
4354 && (ch != ')'
4355 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004356 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004357 )
4358#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004359 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004360 if (heredoc_cnt) {
4361 /* This is technically valid:
4362 * { cat <<HERE; }; echo Ok
4363 * heredoc
4364 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004365 * HERE
4366 * but we don't support this.
4367 * We require heredoc to be in enclosing {}/(),
4368 * if any.
4369 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004370 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004371 goto parse_error;
4372 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004373 if (done_word(&dest, &ctx)) {
4374 goto parse_error;
4375 }
4376 done_pipe(&ctx, PIPE_SEQ);
4377 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004378 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004379 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004380 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004381 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004382 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004383 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004384#if !BB_MMU
4385 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4386 if (pstring)
4387 *pstring = ctx.as_string.data;
4388 else
4389 o_free_unsafe(&ctx.as_string);
4390#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004391 debug_leave();
4392 debug_printf_parse("parse_stream return %p: "
4393 "end_trigger char found\n",
4394 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004395 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004396 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004397 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004398 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004399 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004400 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004401
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004402 /* Catch <, > before deciding whether this word is
4403 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4404 switch (ch) {
4405 case '>':
4406 redir_fd = redirect_opt_num(&dest);
4407 if (done_word(&dest, &ctx)) {
4408 goto parse_error;
4409 }
4410 redir_style = REDIRECT_OVERWRITE;
4411 if (next == '>') {
4412 redir_style = REDIRECT_APPEND;
4413 ch = i_getch(input);
4414 nommu_addchr(&ctx.as_string, ch);
4415 }
4416#if 0
4417 else if (next == '(') {
4418 syntax_error(">(process) not supported");
4419 goto parse_error;
4420 }
4421#endif
4422 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4423 goto parse_error;
4424 continue; /* back to top of while (1) */
4425 case '<':
4426 redir_fd = redirect_opt_num(&dest);
4427 if (done_word(&dest, &ctx)) {
4428 goto parse_error;
4429 }
4430 redir_style = REDIRECT_INPUT;
4431 if (next == '<') {
4432 redir_style = REDIRECT_HEREDOC;
4433 heredoc_cnt++;
4434 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4435 ch = i_getch(input);
4436 nommu_addchr(&ctx.as_string, ch);
4437 } else if (next == '>') {
4438 redir_style = REDIRECT_IO;
4439 ch = i_getch(input);
4440 nommu_addchr(&ctx.as_string, ch);
4441 }
4442#if 0
4443 else if (next == '(') {
4444 syntax_error("<(process) not supported");
4445 goto parse_error;
4446 }
4447#endif
4448 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4449 goto parse_error;
4450 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004451 case '#':
4452 if (dest.length == 0 && !dest.has_quoted_part) {
4453 /* skip "#comment" */
4454 while (1) {
4455 ch = i_peek(input);
4456 if (ch == EOF || ch == '\n')
4457 break;
4458 i_getch(input);
4459 /* note: we do not add it to &ctx.as_string */
4460 }
4461 nommu_addchr(&ctx.as_string, '\n');
4462 continue; /* back to top of while (1) */
4463 }
4464 break;
4465 case '\\':
4466 if (next == '\n') {
4467 /* It's "\<newline>" */
4468#if !BB_MMU
4469 /* Remove trailing '\' from ctx.as_string */
4470 ctx.as_string.data[--ctx.as_string.length] = '\0';
4471#endif
4472 ch = i_getch(input); /* eat it */
4473 continue; /* back to top of while (1) */
4474 }
4475 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004476 }
4477
4478 if (dest.o_assignment == MAYBE_ASSIGNMENT
4479 /* check that we are not in word in "a=1 2>word b=1": */
4480 && !ctx.pending_redirect
4481 ) {
4482 /* ch is a special char and thus this word
4483 * cannot be an assignment */
4484 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004485 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004486 }
4487
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004488 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4489
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004490 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004491 case '#': /* non-comment #: "echo a#b" etc */
4492 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004493 break;
4494 case '\\':
4495 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004496 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004497 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004498 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004499 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004500 /* note: ch != '\n' (that case does not reach this place) */
4501 o_addchr(&dest, '\\');
4502 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4503 o_addchr(&dest, ch);
4504 nommu_addchr(&ctx.as_string, ch);
4505 /* Example: echo Hello \2>file
4506 * we need to know that word 2 is quoted */
4507 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004508 break;
4509 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004510 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004511 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004512 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004513 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004514 }
Eric Andersen25f27032001-04-26 23:22:31 +00004515 break;
4516 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004517 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004518 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004519 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004520 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004521 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004522 goto parse_error;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004523 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004524 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004525 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004526 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004527 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004528 }
Eric Andersen25f27032001-04-26 23:22:31 +00004529 break;
4530 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004531 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004532 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004533 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004534 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004535 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004536 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004537 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004538#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004539 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004540 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004541
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004542 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4543 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004544 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004545 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4546 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004547# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004548 o_addstr(&ctx.as_string, dest.data + pos);
4549 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004550# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004551 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4552 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004553 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004554 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004555#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004556 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004557#if ENABLE_HUSH_CASE
4558 case_semi:
4559#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004560 if (done_word(&dest, &ctx)) {
4561 goto parse_error;
4562 }
4563 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004564#if ENABLE_HUSH_CASE
4565 /* Eat multiple semicolons, detect
4566 * whether it means something special */
4567 while (1) {
4568 ch = i_peek(input);
4569 if (ch != ';')
4570 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004571 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004572 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004573 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004574 ctx.ctx_dsemicolon = 1;
4575 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004576 break;
4577 }
4578 }
4579#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004580 new_cmd:
4581 /* We just finished a cmd. New one may start
4582 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004583 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004584 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004585 break;
4586 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004587 if (done_word(&dest, &ctx)) {
4588 goto parse_error;
4589 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004590 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004591 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004592 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004593 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004594 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004595 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004596 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004597 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004598 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004599 if (done_word(&dest, &ctx)) {
4600 goto parse_error;
4601 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004602#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004603 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004604 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004605#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004606 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004607 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004608 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004609 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004610 } else {
4611 /* we could pick up a file descriptor choice here
4612 * with redirect_opt_num(), but bash doesn't do it.
4613 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004614 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004615#if !BB_MMU
4616 o_reset_to_empty_unquoted(&ctx.as_string);
4617#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004618 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004619 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004620 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004621#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004622 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004623 if (ctx.ctx_res_w == RES_MATCH
4624 && ctx.command->argv == NULL /* not (word|(... */
4625 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004626 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004627 ) {
4628 continue;
4629 }
4630#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004631 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004632 if (parse_group(&dest, &ctx, input, ch) != 0) {
4633 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004634 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004635 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004636 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004637#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004638 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004639 goto case_semi;
4640#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004641 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004642 /* proper use of this character is caught by end_trigger:
4643 * if we see {, we call parse_group(..., end_trigger='}')
4644 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004645 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004646 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004647 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004648 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004649 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004650 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004651 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004652
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004653 parse_error:
4654 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004655 struct parse_context *pctx;
4656 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004657
4658 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004659 * Sample for finding leaks on syntax error recovery path.
4660 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004661 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004662 * Samples to catch leaks at execution:
4663 * while if (true | {true;}); then echo ok; fi; do break; done
4664 * 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 +00004665 */
4666 pctx = &ctx;
4667 do {
4668 /* Update pipe/command counts,
4669 * otherwise freeing may miss some */
4670 done_pipe(pctx, PIPE_SEQ);
4671 debug_printf_clean("freeing list %p from ctx %p\n",
4672 pctx->list_head, pctx);
4673 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004674 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004675 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004676#if !BB_MMU
4677 o_free_unsafe(&pctx->as_string);
4678#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004679 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004680 if (pctx != &ctx) {
4681 free(pctx);
4682 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004683 IF_HAS_KEYWORDS(pctx = p2;)
4684 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004685
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004686 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004687 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004688#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004689 if (pstring)
4690 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004691#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004692 debug_leave();
4693 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004694 }
Eric Andersen25f27032001-04-26 23:22:31 +00004695}
4696
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004697
4698/*** Execution routines ***/
4699
4700/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004701#if !ENABLE_HUSH_BASH_COMPAT
4702/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4703#define expand_string_to_string(str, do_unbackslash) \
4704 expand_string_to_string(str)
4705#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004706static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004707#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004708static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004709#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004710
4711/* expand_strvec_to_strvec() takes a list of strings, expands
4712 * all variable references within and returns a pointer to
4713 * a list of expanded strings, possibly with larger number
4714 * of strings. (Think VAR="a b"; echo $VAR).
4715 * This new list is allocated as a single malloc block.
4716 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004717 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004718 * Caller can deallocate entire list by single free(list). */
4719
Denys Vlasenko238081f2010-10-03 14:26:26 +02004720/* A horde of its helpers come first: */
4721
4722static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4723{
4724 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004725 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004726
Denys Vlasenko9e800222010-10-03 14:28:04 +02004727#if ENABLE_HUSH_BRACE_EXPANSION
4728 if (c == '{' || c == '}') {
4729 /* { -> \{, } -> \} */
4730 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004731 /* And now we want to add { or } and continue:
4732 * o_addchr(o, c);
4733 * continue;
4734 * luckily, just falling throught achieves this.
4735 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004736 }
4737#endif
4738 o_addchr(o, c);
4739 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004740 /* \z -> \\\z; \<eol> -> \\<eol> */
4741 o_addchr(o, '\\');
4742 if (len) {
4743 len--;
4744 o_addchr(o, '\\');
4745 o_addchr(o, *str++);
4746 }
4747 }
4748 }
4749}
4750
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004751/* Store given string, finalizing the word and starting new one whenever
4752 * we encounter IFS char(s). This is used for expanding variable values.
4753 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4754static int expand_on_ifs(o_string *output, int n, const char *str)
4755{
4756 while (1) {
4757 int word_len = strcspn(str, G.ifs);
4758 if (word_len) {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004759 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004760 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004761 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004762 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004763 * Example: "v='\*'; echo b$v" prints "b\*"
4764 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004765 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004766 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004767 /*/ Why can't we do it easier? */
4768 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4769 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4770 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004771 str += word_len;
4772 }
4773 if (!*str) /* EOL - do not finalize word */
4774 break;
4775 o_addchr(output, '\0');
4776 debug_print_list("expand_on_ifs", output, n);
4777 n = o_save_ptr(output, n);
4778 str += strspn(str, G.ifs); /* skip ifs chars */
4779 }
4780 debug_print_list("expand_on_ifs[1]", output, n);
4781 return n;
4782}
4783
4784/* Helper to expand $((...)) and heredoc body. These act as if
4785 * they are in double quotes, with the exception that they are not :).
4786 * Just the rules are similar: "expand only $var and `cmd`"
4787 *
4788 * Returns malloced string.
4789 * As an optimization, we return NULL if expansion is not needed.
4790 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004791#if !ENABLE_HUSH_BASH_COMPAT
4792/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4793#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4794 encode_then_expand_string(str)
4795#endif
4796static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004797{
4798 char *exp_str;
4799 struct in_str input;
4800 o_string dest = NULL_O_STRING;
4801
4802 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004803 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004804#if ENABLE_HUSH_TICK
4805 && !strchr(str, '`')
4806#endif
4807 ) {
4808 return NULL;
4809 }
4810
4811 /* We need to expand. Example:
4812 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4813 */
4814 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004815 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004816//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004817 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004818 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004819 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4820 o_free_unsafe(&dest);
4821 return exp_str;
4822}
4823
4824#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004825static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004826{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004827 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004828 arith_t res;
4829 char *exp_str;
4830
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004831 math_state.lookupvar = get_local_var_value;
4832 math_state.setvar = set_local_var_from_halves;
4833 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004834 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004835 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004836 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004837 if (errmsg_p)
4838 *errmsg_p = math_state.errmsg;
4839 if (math_state.errmsg)
4840 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004841 return res;
4842}
4843#endif
4844
4845#if ENABLE_HUSH_BASH_COMPAT
4846/* ${var/[/]pattern[/repl]} helpers */
4847static char *strstr_pattern(char *val, const char *pattern, int *size)
4848{
4849 while (1) {
4850 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4851 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4852 if (end) {
4853 *size = end - val;
4854 return val;
4855 }
4856 if (*val == '\0')
4857 return NULL;
4858 /* Optimization: if "*pat" did not match the start of "string",
4859 * we know that "tring", "ring" etc will not match too:
4860 */
4861 if (pattern[0] == '*')
4862 return NULL;
4863 val++;
4864 }
4865}
4866static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4867{
4868 char *result = NULL;
4869 unsigned res_len = 0;
4870 unsigned repl_len = strlen(repl);
4871
4872 while (1) {
4873 int size;
4874 char *s = strstr_pattern(val, pattern, &size);
4875 if (!s)
4876 break;
4877
4878 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4879 memcpy(result + res_len, val, s - val);
4880 res_len += s - val;
4881 strcpy(result + res_len, repl);
4882 res_len += repl_len;
4883 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4884
4885 val = s + size;
4886 if (exp_op == '/')
4887 break;
4888 }
4889 if (val[0] && result) {
4890 result = xrealloc(result, res_len + strlen(val) + 1);
4891 strcpy(result + res_len, val);
4892 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4893 }
4894 debug_printf_varexp("result:'%s'\n", result);
4895 return result;
4896}
4897#endif
4898
4899/* Helper:
4900 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4901 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004902static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004903{
4904 const char *val = NULL;
4905 char *to_be_freed = NULL;
4906 char *p = *pp;
4907 char *var;
4908 char first_char;
4909 char exp_op;
4910 char exp_save = exp_save; /* for compiler */
4911 char *exp_saveptr; /* points to expansion operator */
4912 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004913 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004914
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004915 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004916 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004917 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004918 arg0 = arg[0];
4919 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004920 exp_op = 0;
4921
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004922 if (first_char == '#' /* ${#... */
4923 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4924 ) {
4925 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004926 var++;
4927 exp_op = 'L';
4928 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004929 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004930 if (exp_saveptr /* if 2nd char is one of expansion operators */
4931 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4932 ) {
4933 /* ${?:0}, ${#[:]%0} etc */
4934 exp_saveptr = var + 1;
4935 } else {
4936 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4937 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4938 }
4939 exp_op = exp_save = *exp_saveptr;
4940 if (exp_op) {
4941 exp_word = exp_saveptr + 1;
4942 if (exp_op == ':') {
4943 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004944//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004945 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004946 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004947 ) {
4948 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4949 exp_op = ':';
4950 exp_word--;
4951 }
4952 }
4953 *exp_saveptr = '\0';
4954 } /* else: it's not an expansion op, but bare ${var} */
4955 }
4956
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004957 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004958 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004959 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004960 int n = xatoi_positive(var);
4961 if (n < G.global_argc)
4962 val = G.global_argv[n];
4963 /* else val remains NULL: $N with too big N */
4964 } else {
4965 switch (var[0]) {
4966 case '$': /* pid */
4967 val = utoa(G.root_pid);
4968 break;
4969 case '!': /* bg pid */
4970 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4971 break;
4972 case '?': /* exitcode */
4973 val = utoa(G.last_exitcode);
4974 break;
4975 case '#': /* argc */
4976 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4977 break;
4978 default:
4979 val = get_local_var_value(var);
4980 }
4981 }
4982
4983 /* Handle any expansions */
4984 if (exp_op == 'L') {
4985 debug_printf_expand("expand: length(%s)=", val);
4986 val = utoa(val ? strlen(val) : 0);
4987 debug_printf_expand("%s\n", val);
4988 } else if (exp_op) {
4989 if (exp_op == '%' || exp_op == '#') {
4990 /* Standard-mandated substring removal ops:
4991 * ${parameter%word} - remove smallest suffix pattern
4992 * ${parameter%%word} - remove largest suffix pattern
4993 * ${parameter#word} - remove smallest prefix pattern
4994 * ${parameter##word} - remove largest prefix pattern
4995 *
4996 * Word is expanded to produce a glob pattern.
4997 * Then var's value is matched to it and matching part removed.
4998 */
4999 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005000 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005001 char *exp_exp_word;
5002 char *loc;
5003 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005004 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005005 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005006 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005007 if (exp_exp_word)
5008 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005009 /* HACK ALERT. We depend here on the fact that
5010 * G.global_argv and results of utoa and get_local_var_value
5011 * are actually in writable memory:
5012 * scan_and_match momentarily stores NULs there. */
5013 t = (char*)val;
5014 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005015 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005016 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005017 free(exp_exp_word);
5018 if (loc) { /* match was found */
5019 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005020 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005021 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005022 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005023 }
5024 }
5025 }
5026#if ENABLE_HUSH_BASH_COMPAT
5027 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005028 /* It's ${var/[/]pattern[/repl]} thing.
5029 * Note that in encoded form it has TWO parts:
5030 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005031 * and if // is used, it is encoded as \:
5032 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005033 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005034 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005035 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005036 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005037 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005038 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005039 * by the usual expansion rules:
5040 * >az; >bz;
5041 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5042 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5043 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5044 * v='a bz'; echo ${v/a*z/\z} prints "z"
5045 * (note that a*z _pattern_ is never globbed!)
5046 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005047 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005048 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005049 if (!pattern)
5050 pattern = xstrdup(exp_word);
5051 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5052 *p++ = SPECIAL_VAR_SYMBOL;
5053 exp_word = p;
5054 p = strchr(p, SPECIAL_VAR_SYMBOL);
5055 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005056 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005057 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5058 /* HACK ALERT. We depend here on the fact that
5059 * G.global_argv and results of utoa and get_local_var_value
5060 * are actually in writable memory:
5061 * replace_pattern momentarily stores NULs there. */
5062 t = (char*)val;
5063 to_be_freed = replace_pattern(t,
5064 pattern,
5065 (repl ? repl : exp_word),
5066 exp_op);
5067 if (to_be_freed) /* at least one replace happened */
5068 val = to_be_freed;
5069 free(pattern);
5070 free(repl);
5071 }
5072 }
5073#endif
5074 else if (exp_op == ':') {
5075#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5076 /* It's ${var:N[:M]} bashism.
5077 * Note that in encoded form it has TWO parts:
5078 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5079 */
5080 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005081 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005082
Denys Vlasenko063847d2010-09-15 13:33:02 +02005083 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5084 if (errmsg)
5085 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005086 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5087 *p++ = SPECIAL_VAR_SYMBOL;
5088 exp_word = p;
5089 p = strchr(p, SPECIAL_VAR_SYMBOL);
5090 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005091 len = expand_and_evaluate_arith(exp_word, &errmsg);
5092 if (errmsg)
5093 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005094 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005095 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005096 if (beg < 0) /* bash compat */
5097 beg = 0;
5098 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005099 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005100 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005101 val = NULL;
5102 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005103 /* Paranoia. What if user entered 9999999999999
5104 * which fits in arith_t but not int? */
5105 if (len >= INT_MAX)
5106 len = INT_MAX;
5107 val = to_be_freed = xstrndup(val + beg, len);
5108 }
5109 debug_printf_varexp("val:'%s'\n", val);
5110 } else
5111#endif
5112 {
5113 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005114 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005115 }
5116 } else { /* one of "-=+?" */
5117 /* Standard-mandated substitution ops:
5118 * ${var?word} - indicate error if unset
5119 * If var is unset, word (or a message indicating it is unset
5120 * if word is null) is written to standard error
5121 * and the shell exits with a non-zero exit status.
5122 * Otherwise, the value of var is substituted.
5123 * ${var-word} - use default value
5124 * If var is unset, word is substituted.
5125 * ${var=word} - assign and use default value
5126 * If var is unset, word is assigned to var.
5127 * In all cases, final value of var is substituted.
5128 * ${var+word} - use alternative value
5129 * If var is unset, null is substituted.
5130 * Otherwise, word is substituted.
5131 *
5132 * Word is subjected to tilde expansion, parameter expansion,
5133 * command substitution, and arithmetic expansion.
5134 * If word is not needed, it is not expanded.
5135 *
5136 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5137 * but also treat null var as if it is unset.
5138 */
5139 int use_word = (!val || ((exp_save == ':') && !val[0]));
5140 if (exp_op == '+')
5141 use_word = !use_word;
5142 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5143 (exp_save == ':') ? "true" : "false", use_word);
5144 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005145 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005146 if (to_be_freed)
5147 exp_word = to_be_freed;
5148 if (exp_op == '?') {
5149 /* mimic bash message */
5150 die_if_script("%s: %s",
5151 var,
5152 exp_word[0] ? exp_word : "parameter null or not set"
5153 );
5154//TODO: how interactive bash aborts expansion mid-command?
5155 } else {
5156 val = exp_word;
5157 }
5158
5159 if (exp_op == '=') {
5160 /* ${var=[word]} or ${var:=[word]} */
5161 if (isdigit(var[0]) || var[0] == '#') {
5162 /* mimic bash message */
5163 die_if_script("$%s: cannot assign in this way", var);
5164 val = NULL;
5165 } else {
5166 char *new_var = xasprintf("%s=%s", var, val);
5167 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5168 }
5169 }
5170 }
5171 } /* one of "-=+?" */
5172
5173 *exp_saveptr = exp_save;
5174 } /* if (exp_op) */
5175
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005176 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005177
5178 *pp = p;
5179 *to_be_freed_pp = to_be_freed;
5180 return val;
5181}
5182
5183/* Expand all variable references in given string, adding words to list[]
5184 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5185 * to be filled). This routine is extremely tricky: has to deal with
5186 * variables/parameters with whitespace, $* and $@, and constructs like
5187 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005188static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005189{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005190 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005191 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005192 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005193 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005194 char *p;
5195
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005196 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5197 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005198 debug_print_list("expand_vars_to_list", output, n);
5199 n = o_save_ptr(output, n);
5200 debug_print_list("expand_vars_to_list[0]", output, n);
5201
5202 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5203 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005204 char *to_be_freed = NULL;
5205 const char *val = NULL;
5206#if ENABLE_HUSH_TICK
5207 o_string subst_result = NULL_O_STRING;
5208#endif
5209#if ENABLE_SH_MATH_SUPPORT
5210 char arith_buf[sizeof(arith_t)*3 + 2];
5211#endif
5212 o_addblock(output, arg, p - arg);
5213 debug_print_list("expand_vars_to_list[1]", output, n);
5214 arg = ++p;
5215 p = strchr(p, SPECIAL_VAR_SYMBOL);
5216
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005217 /* Fetch special var name (if it is indeed one of them)
5218 * and quote bit, force the bit on if singleword expansion -
5219 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005220 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005221
5222 /* Is this variable quoted and thus expansion can't be null?
5223 * "$@" is special. Even if quoted, it can still
5224 * expand to nothing (not even an empty string),
5225 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005226 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005227 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005228
5229 switch (first_ch & 0x7f) {
5230 /* Highest bit in first_ch indicates that var is double-quoted */
5231 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005232 case '@': {
5233 int i;
5234 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005235 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005236 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005237 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005238 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005239 while (G.global_argv[i]) {
5240 n = expand_on_ifs(output, n, G.global_argv[i]);
5241 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5242 if (G.global_argv[i++][0] && G.global_argv[i]) {
5243 /* this argv[] is not empty and not last:
5244 * put terminating NUL, start new word */
5245 o_addchr(output, '\0');
5246 debug_print_list("expand_vars_to_list[2]", output, n);
5247 n = o_save_ptr(output, n);
5248 debug_print_list("expand_vars_to_list[3]", output, n);
5249 }
5250 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005251 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005252 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005253 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005254 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005255 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005256 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005257 while (1) {
5258 o_addQstr(output, G.global_argv[i]);
5259 if (++i >= G.global_argc)
5260 break;
5261 o_addchr(output, '\0');
5262 debug_print_list("expand_vars_to_list[4]", output, n);
5263 n = o_save_ptr(output, n);
5264 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005265 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005266 while (1) {
5267 o_addQstr(output, G.global_argv[i]);
5268 if (!G.global_argv[++i])
5269 break;
5270 if (G.ifs[0])
5271 o_addchr(output, G.ifs[0]);
5272 }
5273 }
5274 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005275 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005276 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5277 /* "Empty variable", used to make "" etc to not disappear */
5278 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005279 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005280 break;
5281#if ENABLE_HUSH_TICK
5282 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005283 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005284 arg++;
5285 /* Can't just stuff it into output o_string,
5286 * expanded result may need to be globbed
5287 * and $IFS-splitted */
5288 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5289 G.last_exitcode = process_command_subs(&subst_result, arg);
5290 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5291 val = subst_result.data;
5292 goto store_val;
5293#endif
5294#if ENABLE_SH_MATH_SUPPORT
5295 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5296 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005297
5298 arg++; /* skip '+' */
5299 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5300 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005301 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005302 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5303 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005304 val = arith_buf;
5305 break;
5306 }
5307#endif
5308 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005309 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005310 IF_HUSH_TICK(store_val:)
5311 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005312 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5313 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005314 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005315 n = expand_on_ifs(output, n, val);
5316 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005317 }
5318 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005319 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5320 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005321 }
5322 break;
5323
5324 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5325
5326 if (val && val[0]) {
5327 o_addQstr(output, val);
5328 }
5329 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005330
5331 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5332 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005333 if (*p != SPECIAL_VAR_SYMBOL)
5334 *p = SPECIAL_VAR_SYMBOL;
5335
5336#if ENABLE_HUSH_TICK
5337 o_free(&subst_result);
5338#endif
5339 arg = ++p;
5340 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5341
5342 if (arg[0]) {
5343 debug_print_list("expand_vars_to_list[a]", output, n);
5344 /* this part is literal, and it was already pre-quoted
5345 * if needed (much earlier), do not use o_addQstr here! */
5346 o_addstr_with_NUL(output, arg);
5347 debug_print_list("expand_vars_to_list[b]", output, n);
5348 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005349 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005350 ) {
5351 n--;
5352 /* allow to reuse list[n] later without re-growth */
5353 output->has_empty_slot = 1;
5354 } else {
5355 o_addchr(output, '\0');
5356 }
5357
5358 return n;
5359}
5360
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005361static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005362{
5363 int n;
5364 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005365 o_string output = NULL_O_STRING;
5366
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005367 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005368
5369 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005370 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005371 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005372 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005373 }
5374 debug_print_list("expand_variables", &output, n);
5375
5376 /* output.data (malloced in one block) gets returned in "list" */
5377 list = o_finalize_list(&output, n);
5378 debug_print_strings("expand_variables[1]", list);
5379 return list;
5380}
5381
5382static char **expand_strvec_to_strvec(char **argv)
5383{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005384 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005385}
5386
5387#if ENABLE_HUSH_BASH_COMPAT
5388static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5389{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005390 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005391}
5392#endif
5393
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005394/* Used for expansion of right hand of assignments,
5395 * $((...)), heredocs, variable espansion parts.
5396 *
5397 * NB: should NOT do globbing!
5398 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5399 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005400static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005401{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005402#if !ENABLE_HUSH_BASH_COMPAT
5403 const int do_unbackslash = 1;
5404#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005405 char *argv[2], **list;
5406
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005407 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005408 /* This is generally an optimization, but it also
5409 * handles "", which otherwise trips over !list[0] check below.
5410 * (is this ever happens that we actually get str="" here?)
5411 */
5412 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5413 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005414 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005415 return xstrdup(str);
5416 }
5417
5418 argv[0] = (char*)str;
5419 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005420 list = expand_variables(argv, do_unbackslash
5421 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5422 : EXP_FLAG_SINGLEWORD
5423 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005424 if (HUSH_DEBUG)
5425 if (!list[0] || list[1])
5426 bb_error_msg_and_die("BUG in varexp2");
5427 /* actually, just move string 2*sizeof(char*) bytes back */
5428 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005429 if (do_unbackslash)
5430 unbackslash((char*)list);
5431 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005432 return (char*)list;
5433}
5434
5435/* Used for "eval" builtin */
5436static char* expand_strvec_to_string(char **argv)
5437{
5438 char **list;
5439
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005440 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005441 /* Convert all NULs to spaces */
5442 if (list[0]) {
5443 int n = 1;
5444 while (list[n]) {
5445 if (HUSH_DEBUG)
5446 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5447 bb_error_msg_and_die("BUG in varexp3");
5448 /* bash uses ' ' regardless of $IFS contents */
5449 list[n][-1] = ' ';
5450 n++;
5451 }
5452 }
5453 overlapping_strcpy((char*)list, list[0]);
5454 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5455 return (char*)list;
5456}
5457
5458static char **expand_assignments(char **argv, int count)
5459{
5460 int i;
5461 char **p;
5462
5463 G.expanded_assignments = p = NULL;
5464 /* Expand assignments into one string each */
5465 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005466 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005467 }
5468 G.expanded_assignments = NULL;
5469 return p;
5470}
5471
5472
5473#if BB_MMU
5474/* never called */
5475void re_execute_shell(char ***to_free, const char *s,
5476 char *g_argv0, char **g_argv,
5477 char **builtin_argv) NORETURN;
5478
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005479static void switch_off_special_sigs(unsigned mask)
5480{
5481 unsigned sig = 0;
5482 while ((mask >>= 1) != 0) {
5483 sig++;
5484 if (!(mask & 1))
5485 continue;
5486 if (G.traps) {
5487 if (G.traps[sig] && !G.traps[sig][0])
5488 /* trap is '', has to remain SIG_IGN */
5489 continue;
5490 free(G.traps[sig]);
5491 G.traps[sig] = NULL;
5492 }
5493 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005494 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005495 }
5496}
5497
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005498static void reset_traps_to_defaults(void)
5499{
5500 /* This function is always called in a child shell
5501 * after fork (not vfork, NOMMU doesn't use this function).
5502 */
5503 unsigned sig;
5504 unsigned mask;
5505
5506 /* Child shells are not interactive.
5507 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5508 * Testcase: (while :; do :; done) + ^Z should background.
5509 * Same goes for SIGTERM, SIGHUP, SIGINT.
5510 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005511 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5512 if (!G.traps && !mask)
5513 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005514
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005515 /* Switch off special sigs */
5516 switch_off_special_sigs(mask);
5517#if ENABLE_HUSH_JOB
5518 G_fatal_sig_mask = 0;
5519#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005520 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005521 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5522 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005523
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005524 if (!G.traps)
5525 return;
5526
5527 /* Reset all sigs to default except ones with empty traps */
5528 for (sig = 0; sig < NSIG; sig++) {
5529 if (!G.traps[sig])
5530 continue; /* no trap: nothing to do */
5531 if (!G.traps[sig][0])
5532 continue; /* empty trap: has to remain SIG_IGN */
5533 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005534 free(G.traps[sig]);
5535 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005536 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005537 if (sig == 0)
5538 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005539 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005540 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005541}
5542
5543#else /* !BB_MMU */
5544
5545static void re_execute_shell(char ***to_free, const char *s,
5546 char *g_argv0, char **g_argv,
5547 char **builtin_argv) NORETURN;
5548static void re_execute_shell(char ***to_free, const char *s,
5549 char *g_argv0, char **g_argv,
5550 char **builtin_argv)
5551{
5552# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5553 /* delims + 2 * (number of bytes in printed hex numbers) */
5554 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5555 char *heredoc_argv[4];
5556 struct variable *cur;
5557# if ENABLE_HUSH_FUNCTIONS
5558 struct function *funcp;
5559# endif
5560 char **argv, **pp;
5561 unsigned cnt;
5562 unsigned long long empty_trap_mask;
5563
5564 if (!g_argv0) { /* heredoc */
5565 argv = heredoc_argv;
5566 argv[0] = (char *) G.argv0_for_re_execing;
5567 argv[1] = (char *) "-<";
5568 argv[2] = (char *) s;
5569 argv[3] = NULL;
5570 pp = &argv[3]; /* used as pointer to empty environment */
5571 goto do_exec;
5572 }
5573
5574 cnt = 0;
5575 pp = builtin_argv;
5576 if (pp) while (*pp++)
5577 cnt++;
5578
5579 empty_trap_mask = 0;
5580 if (G.traps) {
5581 int sig;
5582 for (sig = 1; sig < NSIG; sig++) {
5583 if (G.traps[sig] && !G.traps[sig][0])
5584 empty_trap_mask |= 1LL << sig;
5585 }
5586 }
5587
5588 sprintf(param_buf, NOMMU_HACK_FMT
5589 , (unsigned) G.root_pid
5590 , (unsigned) G.root_ppid
5591 , (unsigned) G.last_bg_pid
5592 , (unsigned) G.last_exitcode
5593 , cnt
5594 , empty_trap_mask
5595 IF_HUSH_LOOPS(, G.depth_of_loop)
5596 );
5597# undef NOMMU_HACK_FMT
5598 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5599 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5600 */
5601 cnt += 6;
5602 for (cur = G.top_var; cur; cur = cur->next) {
5603 if (!cur->flg_export || cur->flg_read_only)
5604 cnt += 2;
5605 }
5606# if ENABLE_HUSH_FUNCTIONS
5607 for (funcp = G.top_func; funcp; funcp = funcp->next)
5608 cnt += 3;
5609# endif
5610 pp = g_argv;
5611 while (*pp++)
5612 cnt++;
5613 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5614 *pp++ = (char *) G.argv0_for_re_execing;
5615 *pp++ = param_buf;
5616 for (cur = G.top_var; cur; cur = cur->next) {
5617 if (strcmp(cur->varstr, hush_version_str) == 0)
5618 continue;
5619 if (cur->flg_read_only) {
5620 *pp++ = (char *) "-R";
5621 *pp++ = cur->varstr;
5622 } else if (!cur->flg_export) {
5623 *pp++ = (char *) "-V";
5624 *pp++ = cur->varstr;
5625 }
5626 }
5627# if ENABLE_HUSH_FUNCTIONS
5628 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5629 *pp++ = (char *) "-F";
5630 *pp++ = funcp->name;
5631 *pp++ = funcp->body_as_string;
5632 }
5633# endif
5634 /* We can pass activated traps here. Say, -Tnn:trap_string
5635 *
5636 * However, POSIX says that subshells reset signals with traps
5637 * to SIG_DFL.
5638 * I tested bash-3.2 and it not only does that with true subshells
5639 * of the form ( list ), but with any forked children shells.
5640 * I set trap "echo W" WINCH; and then tried:
5641 *
5642 * { echo 1; sleep 20; echo 2; } &
5643 * while true; do echo 1; sleep 20; echo 2; break; done &
5644 * true | { echo 1; sleep 20; echo 2; } | cat
5645 *
5646 * In all these cases sending SIGWINCH to the child shell
5647 * did not run the trap. If I add trap "echo V" WINCH;
5648 * _inside_ group (just before echo 1), it works.
5649 *
5650 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005651 */
5652 *pp++ = (char *) "-c";
5653 *pp++ = (char *) s;
5654 if (builtin_argv) {
5655 while (*++builtin_argv)
5656 *pp++ = *builtin_argv;
5657 *pp++ = (char *) "";
5658 }
5659 *pp++ = g_argv0;
5660 while (*g_argv)
5661 *pp++ = *g_argv++;
5662 /* *pp = NULL; - is already there */
5663 pp = environ;
5664
5665 do_exec:
5666 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02005667 /* Don't propagate SIG_IGN to the child */
5668 if (SPECIAL_JOBSTOP_SIGS != 0)
5669 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005670 execve(bb_busybox_exec_path, argv, pp);
5671 /* Fallback. Useful for init=/bin/hush usage etc */
5672 if (argv[0][0] == '/')
5673 execve(argv[0], argv, pp);
5674 xfunc_error_retval = 127;
5675 bb_error_msg_and_die("can't re-execute the shell");
5676}
5677#endif /* !BB_MMU */
5678
5679
5680static int run_and_free_list(struct pipe *pi);
5681
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005682/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005683 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5684 * end_trigger controls how often we stop parsing
5685 * NUL: parse all, execute, return
5686 * ';': parse till ';' or newline, execute, repeat till EOF
5687 */
5688static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005689{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005690 /* Why we need empty flag?
5691 * An obscure corner case "false; ``; echo $?":
5692 * empty command in `` should still set $? to 0.
5693 * But we can't just set $? to 0 at the start,
5694 * this breaks "false; echo `echo $?`" case.
5695 */
5696 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005697 while (1) {
5698 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005699
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005700#if ENABLE_HUSH_INTERACTIVE
5701 if (end_trigger == ';')
5702 inp->promptmode = 0; /* PS1 */
5703#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005704 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005705 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5706 /* If we are in "big" script
5707 * (not in `cmd` or something similar)...
5708 */
5709 if (pipe_list == ERR_PTR && end_trigger == ';') {
5710 /* Discard cached input (rest of line) */
5711 int ch = inp->last_char;
5712 while (ch != EOF && ch != '\n') {
5713 //bb_error_msg("Discarded:'%c'", ch);
5714 ch = i_getch(inp);
5715 }
5716 /* Force prompt */
5717 inp->p = NULL;
5718 /* This stream isn't empty */
5719 empty = 0;
5720 continue;
5721 }
5722 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01005723 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005724 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005725 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005726 debug_print_tree(pipe_list, 0);
5727 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5728 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005729 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005730#if ENABLE_HUSH_FUNCTIONS
5731 if (G.flag_return_in_progress == 1)
5732 break;
5733#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005734 }
Eric Andersen25f27032001-04-26 23:22:31 +00005735}
5736
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005737static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005738{
5739 struct in_str input;
5740 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005741 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005742}
5743
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005744static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005745{
Eric Andersen25f27032001-04-26 23:22:31 +00005746 struct in_str input;
5747 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005748 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005749}
5750
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005751#if ENABLE_HUSH_TICK
5752static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5753{
5754 pid_t pid;
5755 int channel[2];
5756# if !BB_MMU
5757 char **to_free = NULL;
5758# endif
5759
5760 xpipe(channel);
5761 pid = BB_MMU ? xfork() : xvfork();
5762 if (pid == 0) { /* child */
5763 disable_restore_tty_pgrp_on_exit();
5764 /* Process substitution is not considered to be usual
5765 * 'command execution'.
5766 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5767 */
5768 bb_signals(0
5769 + (1 << SIGTSTP)
5770 + (1 << SIGTTIN)
5771 + (1 << SIGTTOU)
5772 , SIG_IGN);
5773 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5774 close(channel[0]); /* NB: close _first_, then move fd! */
5775 xmove_fd(channel[1], 1);
5776 /* Prevent it from trying to handle ctrl-z etc */
5777 IF_HUSH_JOB(G.run_list_level = 1;)
5778 /* Awful hack for `trap` or $(trap).
5779 *
5780 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5781 * contains an example where "trap" is executed in a subshell:
5782 *
5783 * save_traps=$(trap)
5784 * ...
5785 * eval "$save_traps"
5786 *
5787 * Standard does not say that "trap" in subshell shall print
5788 * parent shell's traps. It only says that its output
5789 * must have suitable form, but then, in the above example
5790 * (which is not supposed to be normative), it implies that.
5791 *
5792 * bash (and probably other shell) does implement it
5793 * (traps are reset to defaults, but "trap" still shows them),
5794 * but as a result, "trap" logic is hopelessly messed up:
5795 *
5796 * # trap
5797 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5798 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5799 * # true | trap <--- trap is in subshell - no output (ditto)
5800 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5801 * trap -- 'echo Ho' SIGWINCH
5802 * # echo `(trap)` <--- in subshell in subshell - output
5803 * trap -- 'echo Ho' SIGWINCH
5804 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5805 * trap -- 'echo Ho' SIGWINCH
5806 *
5807 * The rules when to forget and when to not forget traps
5808 * get really complex and nonsensical.
5809 *
5810 * Our solution: ONLY bare $(trap) or `trap` is special.
5811 */
5812 s = skip_whitespace(s);
5813 if (strncmp(s, "trap", 4) == 0
5814 && skip_whitespace(s + 4)[0] == '\0'
5815 ) {
5816 static const char *const argv[] = { NULL, NULL };
5817 builtin_trap((char**)argv);
5818 exit(0); /* not _exit() - we need to fflush */
5819 }
5820# if BB_MMU
5821 reset_traps_to_defaults();
5822 parse_and_run_string(s);
5823 _exit(G.last_exitcode);
5824# else
5825 /* We re-execute after vfork on NOMMU. This makes this script safe:
5826 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5827 * huge=`cat BIG` # was blocking here forever
5828 * echo OK
5829 */
5830 re_execute_shell(&to_free,
5831 s,
5832 G.global_argv[0],
5833 G.global_argv + 1,
5834 NULL);
5835# endif
5836 }
5837
5838 /* parent */
5839 *pid_p = pid;
5840# if ENABLE_HUSH_FAST
5841 G.count_SIGCHLD++;
5842//bb_error_msg("[%d] fork in generate_stream_from_string:"
5843// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5844// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5845# endif
5846 enable_restore_tty_pgrp_on_exit();
5847# if !BB_MMU
5848 free(to_free);
5849# endif
5850 close(channel[1]);
5851 close_on_exec_on(channel[0]);
5852 return xfdopen_for_read(channel[0]);
5853}
5854
5855/* Return code is exit status of the process that is run. */
5856static int process_command_subs(o_string *dest, const char *s)
5857{
5858 FILE *fp;
5859 struct in_str pipe_str;
5860 pid_t pid;
5861 int status, ch, eol_cnt;
5862
5863 fp = generate_stream_from_string(s, &pid);
5864
5865 /* Now send results of command back into original context */
5866 setup_file_in_str(&pipe_str, fp);
5867 eol_cnt = 0;
5868 while ((ch = i_getch(&pipe_str)) != EOF) {
5869 if (ch == '\n') {
5870 eol_cnt++;
5871 continue;
5872 }
5873 while (eol_cnt) {
5874 o_addchr(dest, '\n');
5875 eol_cnt--;
5876 }
5877 o_addQchr(dest, ch);
5878 }
5879
5880 debug_printf("done reading from `cmd` pipe, closing it\n");
5881 fclose(fp);
5882 /* We need to extract exitcode. Test case
5883 * "true; echo `sleep 1; false` $?"
5884 * should print 1 */
5885 safe_waitpid(pid, &status, 0);
5886 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5887 return WEXITSTATUS(status);
5888}
5889#endif /* ENABLE_HUSH_TICK */
5890
5891
5892static void setup_heredoc(struct redir_struct *redir)
5893{
5894 struct fd_pair pair;
5895 pid_t pid;
5896 int len, written;
5897 /* the _body_ of heredoc (misleading field name) */
5898 const char *heredoc = redir->rd_filename;
5899 char *expanded;
5900#if !BB_MMU
5901 char **to_free;
5902#endif
5903
5904 expanded = NULL;
5905 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005906 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005907 if (expanded)
5908 heredoc = expanded;
5909 }
5910 len = strlen(heredoc);
5911
5912 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5913 xpiped_pair(pair);
5914 xmove_fd(pair.rd, redir->rd_fd);
5915
5916 /* Try writing without forking. Newer kernels have
5917 * dynamically growing pipes. Must use non-blocking write! */
5918 ndelay_on(pair.wr);
5919 while (1) {
5920 written = write(pair.wr, heredoc, len);
5921 if (written <= 0)
5922 break;
5923 len -= written;
5924 if (len == 0) {
5925 close(pair.wr);
5926 free(expanded);
5927 return;
5928 }
5929 heredoc += written;
5930 }
5931 ndelay_off(pair.wr);
5932
5933 /* Okay, pipe buffer was not big enough */
5934 /* Note: we must not create a stray child (bastard? :)
5935 * for the unsuspecting parent process. Child creates a grandchild
5936 * and exits before parent execs the process which consumes heredoc
5937 * (that exec happens after we return from this function) */
5938#if !BB_MMU
5939 to_free = NULL;
5940#endif
5941 pid = xvfork();
5942 if (pid == 0) {
5943 /* child */
5944 disable_restore_tty_pgrp_on_exit();
5945 pid = BB_MMU ? xfork() : xvfork();
5946 if (pid != 0)
5947 _exit(0);
5948 /* grandchild */
5949 close(redir->rd_fd); /* read side of the pipe */
5950#if BB_MMU
5951 full_write(pair.wr, heredoc, len); /* may loop or block */
5952 _exit(0);
5953#else
5954 /* Delegate blocking writes to another process */
5955 xmove_fd(pair.wr, STDOUT_FILENO);
5956 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5957#endif
5958 }
5959 /* parent */
5960#if ENABLE_HUSH_FAST
5961 G.count_SIGCHLD++;
5962//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5963#endif
5964 enable_restore_tty_pgrp_on_exit();
5965#if !BB_MMU
5966 free(to_free);
5967#endif
5968 close(pair.wr);
5969 free(expanded);
5970 wait(NULL); /* wait till child has died */
5971}
5972
5973/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5974 * and stderr if they are redirected. */
5975static int setup_redirects(struct command *prog, int squirrel[])
5976{
5977 int openfd, mode;
5978 struct redir_struct *redir;
5979
5980 for (redir = prog->redirects; redir; redir = redir->next) {
5981 if (redir->rd_type == REDIRECT_HEREDOC2) {
5982 /* rd_fd<<HERE case */
5983 if (squirrel && redir->rd_fd < 3
5984 && squirrel[redir->rd_fd] < 0
5985 ) {
5986 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5987 }
5988 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5989 * of the heredoc */
5990 debug_printf_parse("set heredoc '%s'\n",
5991 redir->rd_filename);
5992 setup_heredoc(redir);
5993 continue;
5994 }
5995
5996 if (redir->rd_dup == REDIRFD_TO_FILE) {
5997 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5998 char *p;
5999 if (redir->rd_filename == NULL) {
6000 /* Something went wrong in the parse.
6001 * Pretend it didn't happen */
6002 bb_error_msg("bug in redirect parse");
6003 continue;
6004 }
6005 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006006 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006007 openfd = open_or_warn(p, mode);
6008 free(p);
6009 if (openfd < 0) {
6010 /* this could get lost if stderr has been redirected, but
6011 * bash and ash both lose it as well (though zsh doesn't!) */
6012//what the above comment tries to say?
6013 return 1;
6014 }
6015 } else {
6016 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6017 openfd = redir->rd_dup;
6018 }
6019
6020 if (openfd != redir->rd_fd) {
6021 if (squirrel && redir->rd_fd < 3
6022 && squirrel[redir->rd_fd] < 0
6023 ) {
6024 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6025 }
6026 if (openfd == REDIRFD_CLOSE) {
6027 /* "n>-" means "close me" */
6028 close(redir->rd_fd);
6029 } else {
6030 xdup2(openfd, redir->rd_fd);
6031 if (redir->rd_dup == REDIRFD_TO_FILE)
6032 close(openfd);
6033 }
6034 }
6035 }
6036 return 0;
6037}
6038
6039static void restore_redirects(int squirrel[])
6040{
6041 int i, fd;
6042 for (i = 0; i < 3; i++) {
6043 fd = squirrel[i];
6044 if (fd != -1) {
6045 /* We simply die on error */
6046 xmove_fd(fd, i);
6047 }
6048 }
6049}
6050
6051static char *find_in_path(const char *arg)
6052{
6053 char *ret = NULL;
6054 const char *PATH = get_local_var_value("PATH");
6055
6056 if (!PATH)
6057 return NULL;
6058
6059 while (1) {
6060 const char *end = strchrnul(PATH, ':');
6061 int sz = end - PATH; /* must be int! */
6062
6063 free(ret);
6064 if (sz != 0) {
6065 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6066 } else {
6067 /* We have xxx::yyyy in $PATH,
6068 * it means "use current dir" */
6069 ret = xstrdup(arg);
6070 }
6071 if (access(ret, F_OK) == 0)
6072 break;
6073
6074 if (*end == '\0') {
6075 free(ret);
6076 return NULL;
6077 }
6078 PATH = end + 1;
6079 }
6080
6081 return ret;
6082}
6083
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006084static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006085 const struct built_in_command *x,
6086 const struct built_in_command *end)
6087{
6088 while (x != end) {
6089 if (strcmp(name, x->b_cmd) != 0) {
6090 x++;
6091 continue;
6092 }
6093 debug_printf_exec("found builtin '%s'\n", name);
6094 return x;
6095 }
6096 return NULL;
6097}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006098static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006099{
6100 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6101}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006102static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006103{
6104 const struct built_in_command *x = find_builtin1(name);
6105 if (x)
6106 return x;
6107 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6108}
6109
6110#if ENABLE_HUSH_FUNCTIONS
6111static struct function **find_function_slot(const char *name)
6112{
6113 struct function **funcpp = &G.top_func;
6114 while (*funcpp) {
6115 if (strcmp(name, (*funcpp)->name) == 0) {
6116 break;
6117 }
6118 funcpp = &(*funcpp)->next;
6119 }
6120 return funcpp;
6121}
6122
6123static const struct function *find_function(const char *name)
6124{
6125 const struct function *funcp = *find_function_slot(name);
6126 if (funcp)
6127 debug_printf_exec("found function '%s'\n", name);
6128 return funcp;
6129}
6130
6131/* Note: takes ownership on name ptr */
6132static struct function *new_function(char *name)
6133{
6134 struct function **funcpp = find_function_slot(name);
6135 struct function *funcp = *funcpp;
6136
6137 if (funcp != NULL) {
6138 struct command *cmd = funcp->parent_cmd;
6139 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6140 if (!cmd) {
6141 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6142 free(funcp->name);
6143 /* Note: if !funcp->body, do not free body_as_string!
6144 * This is a special case of "-F name body" function:
6145 * body_as_string was not malloced! */
6146 if (funcp->body) {
6147 free_pipe_list(funcp->body);
6148# if !BB_MMU
6149 free(funcp->body_as_string);
6150# endif
6151 }
6152 } else {
6153 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6154 cmd->argv[0] = funcp->name;
6155 cmd->group = funcp->body;
6156# if !BB_MMU
6157 cmd->group_as_string = funcp->body_as_string;
6158# endif
6159 }
6160 } else {
6161 debug_printf_exec("remembering new function '%s'\n", name);
6162 funcp = *funcpp = xzalloc(sizeof(*funcp));
6163 /*funcp->next = NULL;*/
6164 }
6165
6166 funcp->name = name;
6167 return funcp;
6168}
6169
6170static void unset_func(const char *name)
6171{
6172 struct function **funcpp = find_function_slot(name);
6173 struct function *funcp = *funcpp;
6174
6175 if (funcp != NULL) {
6176 debug_printf_exec("freeing function '%s'\n", funcp->name);
6177 *funcpp = funcp->next;
6178 /* funcp is unlinked now, deleting it.
6179 * Note: if !funcp->body, the function was created by
6180 * "-F name body", do not free ->body_as_string
6181 * and ->name as they were not malloced. */
6182 if (funcp->body) {
6183 free_pipe_list(funcp->body);
6184 free(funcp->name);
6185# if !BB_MMU
6186 free(funcp->body_as_string);
6187# endif
6188 }
6189 free(funcp);
6190 }
6191}
6192
6193# if BB_MMU
6194#define exec_function(to_free, funcp, argv) \
6195 exec_function(funcp, argv)
6196# endif
6197static void exec_function(char ***to_free,
6198 const struct function *funcp,
6199 char **argv) NORETURN;
6200static void exec_function(char ***to_free,
6201 const struct function *funcp,
6202 char **argv)
6203{
6204# if BB_MMU
6205 int n = 1;
6206
6207 argv[0] = G.global_argv[0];
6208 G.global_argv = argv;
6209 while (*++argv)
6210 n++;
6211 G.global_argc = n;
6212 /* On MMU, funcp->body is always non-NULL */
6213 n = run_list(funcp->body);
6214 fflush_all();
6215 _exit(n);
6216# else
6217 re_execute_shell(to_free,
6218 funcp->body_as_string,
6219 G.global_argv[0],
6220 argv + 1,
6221 NULL);
6222# endif
6223}
6224
6225static int run_function(const struct function *funcp, char **argv)
6226{
6227 int rc;
6228 save_arg_t sv;
6229 smallint sv_flg;
6230
6231 save_and_replace_G_args(&sv, argv);
6232
6233 /* "we are in function, ok to use return" */
6234 sv_flg = G.flag_return_in_progress;
6235 G.flag_return_in_progress = -1;
6236# if ENABLE_HUSH_LOCAL
6237 G.func_nest_level++;
6238# endif
6239
6240 /* On MMU, funcp->body is always non-NULL */
6241# if !BB_MMU
6242 if (!funcp->body) {
6243 /* Function defined by -F */
6244 parse_and_run_string(funcp->body_as_string);
6245 rc = G.last_exitcode;
6246 } else
6247# endif
6248 {
6249 rc = run_list(funcp->body);
6250 }
6251
6252# if ENABLE_HUSH_LOCAL
6253 {
6254 struct variable *var;
6255 struct variable **var_pp;
6256
6257 var_pp = &G.top_var;
6258 while ((var = *var_pp) != NULL) {
6259 if (var->func_nest_level < G.func_nest_level) {
6260 var_pp = &var->next;
6261 continue;
6262 }
6263 /* Unexport */
6264 if (var->flg_export)
6265 bb_unsetenv(var->varstr);
6266 /* Remove from global list */
6267 *var_pp = var->next;
6268 /* Free */
6269 if (!var->max_len)
6270 free(var->varstr);
6271 free(var);
6272 }
6273 G.func_nest_level--;
6274 }
6275# endif
6276 G.flag_return_in_progress = sv_flg;
6277
6278 restore_G_args(&sv, argv);
6279
6280 return rc;
6281}
6282#endif /* ENABLE_HUSH_FUNCTIONS */
6283
6284
6285#if BB_MMU
6286#define exec_builtin(to_free, x, argv) \
6287 exec_builtin(x, argv)
6288#else
6289#define exec_builtin(to_free, x, argv) \
6290 exec_builtin(to_free, argv)
6291#endif
6292static void exec_builtin(char ***to_free,
6293 const struct built_in_command *x,
6294 char **argv) NORETURN;
6295static void exec_builtin(char ***to_free,
6296 const struct built_in_command *x,
6297 char **argv)
6298{
6299#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006300 int rcode;
6301 fflush_all();
6302 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006303 fflush_all();
6304 _exit(rcode);
6305#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006306 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006307 /* On NOMMU, we must never block!
6308 * Example: { sleep 99 | read line; } & echo Ok
6309 */
6310 re_execute_shell(to_free,
6311 argv[0],
6312 G.global_argv[0],
6313 G.global_argv + 1,
6314 argv);
6315#endif
6316}
6317
6318
6319static void execvp_or_die(char **argv) NORETURN;
6320static void execvp_or_die(char **argv)
6321{
6322 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006323 /* Don't propagate SIG_IGN to the child */
6324 if (SPECIAL_JOBSTOP_SIGS != 0)
6325 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006326 execvp(argv[0], argv);
6327 bb_perror_msg("can't execute '%s'", argv[0]);
6328 _exit(127); /* bash compat */
6329}
6330
6331#if ENABLE_HUSH_MODE_X
6332static void dump_cmd_in_x_mode(char **argv)
6333{
6334 if (G_x_mode && argv) {
6335 /* We want to output the line in one write op */
6336 char *buf, *p;
6337 int len;
6338 int n;
6339
6340 len = 3;
6341 n = 0;
6342 while (argv[n])
6343 len += strlen(argv[n++]) + 1;
6344 buf = xmalloc(len);
6345 buf[0] = '+';
6346 p = buf + 1;
6347 n = 0;
6348 while (argv[n])
6349 p += sprintf(p, " %s", argv[n++]);
6350 *p++ = '\n';
6351 *p = '\0';
6352 fputs(buf, stderr);
6353 free(buf);
6354 }
6355}
6356#else
6357# define dump_cmd_in_x_mode(argv) ((void)0)
6358#endif
6359
6360#if BB_MMU
6361#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6362 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6363#define pseudo_exec(nommu_save, command, argv_expanded) \
6364 pseudo_exec(command, argv_expanded)
6365#endif
6366
6367/* Called after [v]fork() in run_pipe, or from builtin_exec.
6368 * Never returns.
6369 * Don't exit() here. If you don't exec, use _exit instead.
6370 * The at_exit handlers apparently confuse the calling process,
6371 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6372static void pseudo_exec_argv(nommu_save_t *nommu_save,
6373 char **argv, int assignment_cnt,
6374 char **argv_expanded) NORETURN;
6375static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6376 char **argv, int assignment_cnt,
6377 char **argv_expanded)
6378{
6379 char **new_env;
6380
6381 new_env = expand_assignments(argv, assignment_cnt);
6382 dump_cmd_in_x_mode(new_env);
6383
6384 if (!argv[assignment_cnt]) {
6385 /* Case when we are here: ... | var=val | ...
6386 * (note that we do not exit early, i.e., do not optimize out
6387 * expand_assignments(): think about ... | var=`sleep 1` | ...
6388 */
6389 free_strings(new_env);
6390 _exit(EXIT_SUCCESS);
6391 }
6392
6393#if BB_MMU
6394 set_vars_and_save_old(new_env);
6395 free(new_env); /* optional */
6396 /* we can also destroy set_vars_and_save_old's return value,
6397 * to save memory */
6398#else
6399 nommu_save->new_env = new_env;
6400 nommu_save->old_vars = set_vars_and_save_old(new_env);
6401#endif
6402
6403 if (argv_expanded) {
6404 argv = argv_expanded;
6405 } else {
6406 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6407#if !BB_MMU
6408 nommu_save->argv = argv;
6409#endif
6410 }
6411 dump_cmd_in_x_mode(argv);
6412
6413#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6414 if (strchr(argv[0], '/') != NULL)
6415 goto skip;
6416#endif
6417
6418 /* Check if the command matches any of the builtins.
6419 * Depending on context, this might be redundant. But it's
6420 * easier to waste a few CPU cycles than it is to figure out
6421 * if this is one of those cases.
6422 */
6423 {
6424 /* On NOMMU, it is more expensive to re-execute shell
6425 * just in order to run echo or test builtin.
6426 * It's better to skip it here and run corresponding
6427 * non-builtin later. */
6428 const struct built_in_command *x;
6429 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6430 if (x) {
6431 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6432 }
6433 }
6434#if ENABLE_HUSH_FUNCTIONS
6435 /* Check if the command matches any functions */
6436 {
6437 const struct function *funcp = find_function(argv[0]);
6438 if (funcp) {
6439 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6440 }
6441 }
6442#endif
6443
6444#if ENABLE_FEATURE_SH_STANDALONE
6445 /* Check if the command matches any busybox applets */
6446 {
6447 int a = find_applet_by_name(argv[0]);
6448 if (a >= 0) {
6449# if BB_MMU /* see above why on NOMMU it is not allowed */
6450 if (APPLET_IS_NOEXEC(a)) {
6451 debug_printf_exec("running applet '%s'\n", argv[0]);
6452 run_applet_no_and_exit(a, argv);
6453 }
6454# endif
6455 /* Re-exec ourselves */
6456 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006457 /* Don't propagate SIG_IGN to the child */
6458 if (SPECIAL_JOBSTOP_SIGS != 0)
6459 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006460 execv(bb_busybox_exec_path, argv);
6461 /* If they called chroot or otherwise made the binary no longer
6462 * executable, fall through */
6463 }
6464 }
6465#endif
6466
6467#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6468 skip:
6469#endif
6470 execvp_or_die(argv);
6471}
6472
6473/* Called after [v]fork() in run_pipe
6474 */
6475static void pseudo_exec(nommu_save_t *nommu_save,
6476 struct command *command,
6477 char **argv_expanded) NORETURN;
6478static void pseudo_exec(nommu_save_t *nommu_save,
6479 struct command *command,
6480 char **argv_expanded)
6481{
6482 if (command->argv) {
6483 pseudo_exec_argv(nommu_save, command->argv,
6484 command->assignment_cnt, argv_expanded);
6485 }
6486
6487 if (command->group) {
6488 /* Cases when we are here:
6489 * ( list )
6490 * { list } &
6491 * ... | ( list ) | ...
6492 * ... | { list } | ...
6493 */
6494#if BB_MMU
6495 int rcode;
6496 debug_printf_exec("pseudo_exec: run_list\n");
6497 reset_traps_to_defaults();
6498 rcode = run_list(command->group);
6499 /* OK to leak memory by not calling free_pipe_list,
6500 * since this process is about to exit */
6501 _exit(rcode);
6502#else
6503 re_execute_shell(&nommu_save->argv_from_re_execing,
6504 command->group_as_string,
6505 G.global_argv[0],
6506 G.global_argv + 1,
6507 NULL);
6508#endif
6509 }
6510
6511 /* Case when we are here: ... | >file */
6512 debug_printf_exec("pseudo_exec'ed null command\n");
6513 _exit(EXIT_SUCCESS);
6514}
6515
6516#if ENABLE_HUSH_JOB
6517static const char *get_cmdtext(struct pipe *pi)
6518{
6519 char **argv;
6520 char *p;
6521 int len;
6522
6523 /* This is subtle. ->cmdtext is created only on first backgrounding.
6524 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6525 * On subsequent bg argv is trashed, but we won't use it */
6526 if (pi->cmdtext)
6527 return pi->cmdtext;
6528 argv = pi->cmds[0].argv;
6529 if (!argv || !argv[0]) {
6530 pi->cmdtext = xzalloc(1);
6531 return pi->cmdtext;
6532 }
6533
6534 len = 0;
6535 do {
6536 len += strlen(*argv) + 1;
6537 } while (*++argv);
6538 p = xmalloc(len);
6539 pi->cmdtext = p;
6540 argv = pi->cmds[0].argv;
6541 do {
6542 len = strlen(*argv);
6543 memcpy(p, *argv, len);
6544 p += len;
6545 *p++ = ' ';
6546 } while (*++argv);
6547 p[-1] = '\0';
6548 return pi->cmdtext;
6549}
6550
6551static void insert_bg_job(struct pipe *pi)
6552{
6553 struct pipe *job, **jobp;
6554 int i;
6555
6556 /* Linear search for the ID of the job to use */
6557 pi->jobid = 1;
6558 for (job = G.job_list; job; job = job->next)
6559 if (job->jobid >= pi->jobid)
6560 pi->jobid = job->jobid + 1;
6561
6562 /* Add job to the list of running jobs */
6563 jobp = &G.job_list;
6564 while ((job = *jobp) != NULL)
6565 jobp = &job->next;
6566 job = *jobp = xmalloc(sizeof(*job));
6567
6568 *job = *pi; /* physical copy */
6569 job->next = NULL;
6570 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6571 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6572 for (i = 0; i < pi->num_cmds; i++) {
6573 job->cmds[i].pid = pi->cmds[i].pid;
6574 /* all other fields are not used and stay zero */
6575 }
6576 job->cmdtext = xstrdup(get_cmdtext(pi));
6577
6578 if (G_interactive_fd)
6579 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6580 G.last_jobid = job->jobid;
6581}
6582
6583static void remove_bg_job(struct pipe *pi)
6584{
6585 struct pipe *prev_pipe;
6586
6587 if (pi == G.job_list) {
6588 G.job_list = pi->next;
6589 } else {
6590 prev_pipe = G.job_list;
6591 while (prev_pipe->next != pi)
6592 prev_pipe = prev_pipe->next;
6593 prev_pipe->next = pi->next;
6594 }
6595 if (G.job_list)
6596 G.last_jobid = G.job_list->jobid;
6597 else
6598 G.last_jobid = 0;
6599}
6600
6601/* Remove a backgrounded job */
6602static void delete_finished_bg_job(struct pipe *pi)
6603{
6604 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006605 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006606}
6607#endif /* JOB */
6608
6609/* Check to see if any processes have exited -- if they
6610 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006611static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006612{
6613 int attributes;
6614 int status;
6615#if ENABLE_HUSH_JOB
6616 struct pipe *pi;
6617#endif
6618 pid_t childpid;
6619 int rcode = 0;
6620
6621 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6622
6623 attributes = WUNTRACED;
6624 if (fg_pipe == NULL)
6625 attributes |= WNOHANG;
6626
6627 errno = 0;
6628#if ENABLE_HUSH_FAST
6629 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6630//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6631//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6632 /* There was neither fork nor SIGCHLD since last waitpid */
6633 /* Avoid doing waitpid syscall if possible */
6634 if (!G.we_have_children) {
6635 errno = ECHILD;
6636 return -1;
6637 }
6638 if (fg_pipe == NULL) { /* is WNOHANG set? */
6639 /* We have children, but they did not exit
6640 * or stop yet (we saw no SIGCHLD) */
6641 return 0;
6642 }
6643 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6644 }
6645#endif
6646
6647/* Do we do this right?
6648 * bash-3.00# sleep 20 | false
6649 * <ctrl-Z pressed>
6650 * [3]+ Stopped sleep 20 | false
6651 * bash-3.00# echo $?
6652 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6653 * [hush 1.14.0: yes we do it right]
6654 */
6655 wait_more:
6656 while (1) {
6657 int i;
6658 int dead;
6659
6660#if ENABLE_HUSH_FAST
6661 i = G.count_SIGCHLD;
6662#endif
6663 childpid = waitpid(-1, &status, attributes);
6664 if (childpid <= 0) {
6665 if (childpid && errno != ECHILD)
6666 bb_perror_msg("waitpid");
6667#if ENABLE_HUSH_FAST
6668 else { /* Until next SIGCHLD, waitpid's are useless */
6669 G.we_have_children = (childpid == 0);
6670 G.handled_SIGCHLD = i;
6671//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6672 }
6673#endif
6674 break;
6675 }
6676 dead = WIFEXITED(status) || WIFSIGNALED(status);
6677
6678#if DEBUG_JOBS
6679 if (WIFSTOPPED(status))
6680 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6681 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6682 if (WIFSIGNALED(status))
6683 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6684 childpid, WTERMSIG(status), WEXITSTATUS(status));
6685 if (WIFEXITED(status))
6686 debug_printf_jobs("pid %d exited, exitcode %d\n",
6687 childpid, WEXITSTATUS(status));
6688#endif
6689 /* Were we asked to wait for fg pipe? */
6690 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006691 i = fg_pipe->num_cmds;
6692 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006693 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6694 if (fg_pipe->cmds[i].pid != childpid)
6695 continue;
6696 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006697 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006698 fg_pipe->cmds[i].pid = 0;
6699 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006700 ex = WEXITSTATUS(status);
6701 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006702 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006703 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6704 */
6705 if (WIFSIGNALED(status)) {
6706 int sig = WTERMSIG(status);
6707 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006708 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6709 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6710 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006711 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6712 * Maybe we need to use sig | 128? */
6713 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006714 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006715 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006716 } else {
6717 fg_pipe->cmds[i].is_stopped = 1;
6718 fg_pipe->stopped_cmds++;
6719 }
6720 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6721 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006722 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006723 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006724 i = fg_pipe->num_cmds;
6725 while (--i >= 0) {
6726 rcode = fg_pipe->cmds[i].cmd_exitcode;
6727 /* usually last process gives overall exitstatus,
6728 * but with "set -o pipefail", last *failed* process does */
6729 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6730 break;
6731 }
6732 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006733/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6734 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6735 * and "killall -STOP cat" */
6736 if (G_interactive_fd) {
6737#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006738 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006739 insert_bg_job(fg_pipe);
6740#endif
6741 return rcode;
6742 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006743 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006744 return rcode;
6745 }
6746 /* There are still running processes in the fg pipe */
6747 goto wait_more; /* do waitpid again */
6748 }
6749 /* it wasnt fg_pipe, look for process in bg pipes */
6750 }
6751
6752#if ENABLE_HUSH_JOB
6753 /* We asked to wait for bg or orphaned children */
6754 /* No need to remember exitcode in this case */
6755 for (pi = G.job_list; pi; pi = pi->next) {
6756 for (i = 0; i < pi->num_cmds; i++) {
6757 if (pi->cmds[i].pid == childpid)
6758 goto found_pi_and_prognum;
6759 }
6760 }
6761 /* Happens when shell is used as init process (init=/bin/sh) */
6762 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6763 continue; /* do waitpid again */
6764
6765 found_pi_and_prognum:
6766 if (dead) {
6767 /* child exited */
6768 pi->cmds[i].pid = 0;
6769 pi->alive_cmds--;
6770 if (!pi->alive_cmds) {
6771 if (G_interactive_fd)
6772 printf(JOB_STATUS_FORMAT, pi->jobid,
6773 "Done", pi->cmdtext);
6774 delete_finished_bg_job(pi);
6775 }
6776 } else {
6777 /* child stopped */
6778 pi->cmds[i].is_stopped = 1;
6779 pi->stopped_cmds++;
6780 }
6781#endif
6782 } /* while (waitpid succeeds)... */
6783
6784 return rcode;
6785}
6786
6787#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006788static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006789{
6790 pid_t p;
6791 int rcode = checkjobs(fg_pipe);
6792 if (G_saved_tty_pgrp) {
6793 /* Job finished, move the shell to the foreground */
6794 p = getpgrp(); /* our process group id */
6795 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6796 tcsetpgrp(G_interactive_fd, p);
6797 }
6798 return rcode;
6799}
6800#endif
6801
6802/* Start all the jobs, but don't wait for anything to finish.
6803 * See checkjobs().
6804 *
6805 * Return code is normally -1, when the caller has to wait for children
6806 * to finish to determine the exit status of the pipe. If the pipe
6807 * is a simple builtin command, however, the action is done by the
6808 * time run_pipe returns, and the exit code is provided as the
6809 * return value.
6810 *
6811 * Returns -1 only if started some children. IOW: we have to
6812 * mask out retvals of builtins etc with 0xff!
6813 *
6814 * The only case when we do not need to [v]fork is when the pipe
6815 * is single, non-backgrounded, non-subshell command. Examples:
6816 * cmd ; ... { list } ; ...
6817 * cmd && ... { list } && ...
6818 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006819 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006820 * or (if SH_STANDALONE) an applet, and we can run the { list }
6821 * with run_list. If it isn't one of these, we fork and exec cmd.
6822 *
6823 * Cases when we must fork:
6824 * non-single: cmd | cmd
6825 * backgrounded: cmd & { list } &
6826 * subshell: ( list ) [&]
6827 */
6828#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006829#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006830 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6831#endif
6832static int redirect_and_varexp_helper(char ***new_env_p,
6833 struct variable **old_vars_p,
6834 struct command *command,
6835 int squirrel[3],
6836 char **argv_expanded)
6837{
6838 /* setup_redirects acts on file descriptors, not FILEs.
6839 * This is perfect for work that comes after exec().
6840 * Is it really safe for inline use? Experimentally,
6841 * things seem to work. */
6842 int rcode = setup_redirects(command, squirrel);
6843 if (rcode == 0) {
6844 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6845 *new_env_p = new_env;
6846 dump_cmd_in_x_mode(new_env);
6847 dump_cmd_in_x_mode(argv_expanded);
6848 if (old_vars_p)
6849 *old_vars_p = set_vars_and_save_old(new_env);
6850 }
6851 return rcode;
6852}
6853static NOINLINE int run_pipe(struct pipe *pi)
6854{
6855 static const char *const null_ptr = NULL;
6856
6857 int cmd_no;
6858 int next_infd;
6859 struct command *command;
6860 char **argv_expanded;
6861 char **argv;
6862 /* it is not always needed, but we aim to smaller code */
6863 int squirrel[] = { -1, -1, -1 };
6864 int rcode;
6865
6866 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6867 debug_enter();
6868
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006869 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6870 * Result should be 3 lines: q w e, qwe, q w e
6871 */
6872 G.ifs = get_local_var_value("IFS");
6873 if (!G.ifs)
6874 G.ifs = defifs;
6875
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006876 IF_HUSH_JOB(pi->pgrp = -1;)
6877 pi->stopped_cmds = 0;
6878 command = &pi->cmds[0];
6879 argv_expanded = NULL;
6880
6881 if (pi->num_cmds != 1
6882 || pi->followup == PIPE_BG
6883 || command->cmd_type == CMD_SUBSHELL
6884 ) {
6885 goto must_fork;
6886 }
6887
6888 pi->alive_cmds = 1;
6889
6890 debug_printf_exec(": group:%p argv:'%s'\n",
6891 command->group, command->argv ? command->argv[0] : "NONE");
6892
6893 if (command->group) {
6894#if ENABLE_HUSH_FUNCTIONS
6895 if (command->cmd_type == CMD_FUNCDEF) {
6896 /* "executing" func () { list } */
6897 struct function *funcp;
6898
6899 funcp = new_function(command->argv[0]);
6900 /* funcp->name is already set to argv[0] */
6901 funcp->body = command->group;
6902# if !BB_MMU
6903 funcp->body_as_string = command->group_as_string;
6904 command->group_as_string = NULL;
6905# endif
6906 command->group = NULL;
6907 command->argv[0] = NULL;
6908 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6909 funcp->parent_cmd = command;
6910 command->child_func = funcp;
6911
6912 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6913 debug_leave();
6914 return EXIT_SUCCESS;
6915 }
6916#endif
6917 /* { list } */
6918 debug_printf("non-subshell group\n");
6919 rcode = 1; /* exitcode if redir failed */
6920 if (setup_redirects(command, squirrel) == 0) {
6921 debug_printf_exec(": run_list\n");
6922 rcode = run_list(command->group) & 0xff;
6923 }
6924 restore_redirects(squirrel);
6925 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6926 debug_leave();
6927 debug_printf_exec("run_pipe: return %d\n", rcode);
6928 return rcode;
6929 }
6930
6931 argv = command->argv ? command->argv : (char **) &null_ptr;
6932 {
6933 const struct built_in_command *x;
6934#if ENABLE_HUSH_FUNCTIONS
6935 const struct function *funcp;
6936#else
6937 enum { funcp = 0 };
6938#endif
6939 char **new_env = NULL;
6940 struct variable *old_vars = NULL;
6941
6942 if (argv[command->assignment_cnt] == NULL) {
6943 /* Assignments, but no command */
6944 /* Ensure redirects take effect (that is, create files).
6945 * Try "a=t >file" */
6946#if 0 /* A few cases in testsuite fail with this code. FIXME */
6947 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6948 /* Set shell variables */
6949 if (new_env) {
6950 argv = new_env;
6951 while (*argv) {
6952 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6953 /* Do we need to flag set_local_var() errors?
6954 * "assignment to readonly var" and "putenv error"
6955 */
6956 argv++;
6957 }
6958 }
6959 /* Redirect error sets $? to 1. Otherwise,
6960 * if evaluating assignment value set $?, retain it.
6961 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6962 if (rcode == 0)
6963 rcode = G.last_exitcode;
6964 /* Exit, _skipping_ variable restoring code: */
6965 goto clean_up_and_ret0;
6966
6967#else /* Older, bigger, but more correct code */
6968
6969 rcode = setup_redirects(command, squirrel);
6970 restore_redirects(squirrel);
6971 /* Set shell variables */
6972 if (G_x_mode)
6973 bb_putchar_stderr('+');
6974 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006975 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006976 if (G_x_mode)
6977 fprintf(stderr, " %s", p);
6978 debug_printf_exec("set shell var:'%s'->'%s'\n",
6979 *argv, p);
6980 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6981 /* Do we need to flag set_local_var() errors?
6982 * "assignment to readonly var" and "putenv error"
6983 */
6984 argv++;
6985 }
6986 if (G_x_mode)
6987 bb_putchar_stderr('\n');
6988 /* Redirect error sets $? to 1. Otherwise,
6989 * if evaluating assignment value set $?, retain it.
6990 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6991 if (rcode == 0)
6992 rcode = G.last_exitcode;
6993 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6994 debug_leave();
6995 debug_printf_exec("run_pipe: return %d\n", rcode);
6996 return rcode;
6997#endif
6998 }
6999
7000 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007001#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007002 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007003 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007004 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007005#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007006 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007007 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7008 }
7009
7010 /* if someone gives us an empty string: `cmd with empty output` */
7011 if (!argv_expanded[0]) {
7012 free(argv_expanded);
7013 debug_leave();
7014 return G.last_exitcode;
7015 }
7016
7017 x = find_builtin(argv_expanded[0]);
7018#if ENABLE_HUSH_FUNCTIONS
7019 funcp = NULL;
7020 if (!x)
7021 funcp = find_function(argv_expanded[0]);
7022#endif
7023 if (x || funcp) {
7024 if (!funcp) {
7025 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7026 debug_printf("exec with redirects only\n");
7027 rcode = setup_redirects(command, NULL);
7028 goto clean_up_and_ret1;
7029 }
7030 }
7031 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7032 if (rcode == 0) {
7033 if (!funcp) {
7034 debug_printf_exec(": builtin '%s' '%s'...\n",
7035 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007036 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007037 rcode = x->b_function(argv_expanded) & 0xff;
7038 fflush_all();
7039 }
7040#if ENABLE_HUSH_FUNCTIONS
7041 else {
7042# if ENABLE_HUSH_LOCAL
7043 struct variable **sv;
7044 sv = G.shadowed_vars_pp;
7045 G.shadowed_vars_pp = &old_vars;
7046# endif
7047 debug_printf_exec(": function '%s' '%s'...\n",
7048 funcp->name, argv_expanded[1]);
7049 rcode = run_function(funcp, argv_expanded) & 0xff;
7050# if ENABLE_HUSH_LOCAL
7051 G.shadowed_vars_pp = sv;
7052# endif
7053 }
7054#endif
7055 }
7056 clean_up_and_ret:
7057 unset_vars(new_env);
7058 add_vars(old_vars);
7059/* clean_up_and_ret0: */
7060 restore_redirects(squirrel);
7061 clean_up_and_ret1:
7062 free(argv_expanded);
7063 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7064 debug_leave();
7065 debug_printf_exec("run_pipe return %d\n", rcode);
7066 return rcode;
7067 }
7068
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007069 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007070 int n = find_applet_by_name(argv_expanded[0]);
7071 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7072 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7073 if (rcode == 0) {
7074 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7075 argv_expanded[0], argv_expanded[1]);
7076 rcode = run_nofork_applet(n, argv_expanded);
7077 }
7078 goto clean_up_and_ret;
7079 }
7080 }
7081 /* It is neither builtin nor applet. We must fork. */
7082 }
7083
7084 must_fork:
7085 /* NB: argv_expanded may already be created, and that
7086 * might include `cmd` runs! Do not rerun it! We *must*
7087 * use argv_expanded if it's non-NULL */
7088
7089 /* Going to fork a child per each pipe member */
7090 pi->alive_cmds = 0;
7091 next_infd = 0;
7092
7093 cmd_no = 0;
7094 while (cmd_no < pi->num_cmds) {
7095 struct fd_pair pipefds;
7096#if !BB_MMU
7097 volatile nommu_save_t nommu_save;
7098 nommu_save.new_env = NULL;
7099 nommu_save.old_vars = NULL;
7100 nommu_save.argv = NULL;
7101 nommu_save.argv_from_re_execing = NULL;
7102#endif
7103 command = &pi->cmds[cmd_no];
7104 cmd_no++;
7105 if (command->argv) {
7106 debug_printf_exec(": pipe member '%s' '%s'...\n",
7107 command->argv[0], command->argv[1]);
7108 } else {
7109 debug_printf_exec(": pipe member with no argv\n");
7110 }
7111
7112 /* pipes are inserted between pairs of commands */
7113 pipefds.rd = 0;
7114 pipefds.wr = 1;
7115 if (cmd_no < pi->num_cmds)
7116 xpiped_pair(pipefds);
7117
7118 command->pid = BB_MMU ? fork() : vfork();
7119 if (!command->pid) { /* child */
7120#if ENABLE_HUSH_JOB
7121 disable_restore_tty_pgrp_on_exit();
7122 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7123
7124 /* Every child adds itself to new process group
7125 * with pgid == pid_of_first_child_in_pipe */
7126 if (G.run_list_level == 1 && G_interactive_fd) {
7127 pid_t pgrp;
7128 pgrp = pi->pgrp;
7129 if (pgrp < 0) /* true for 1st process only */
7130 pgrp = getpid();
7131 if (setpgid(0, pgrp) == 0
7132 && pi->followup != PIPE_BG
7133 && G_saved_tty_pgrp /* we have ctty */
7134 ) {
7135 /* We do it in *every* child, not just first,
7136 * to avoid races */
7137 tcsetpgrp(G_interactive_fd, pgrp);
7138 }
7139 }
7140#endif
7141 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7142 /* 1st cmd in backgrounded pipe
7143 * should have its stdin /dev/null'ed */
7144 close(0);
7145 if (open(bb_dev_null, O_RDONLY))
7146 xopen("/", O_RDONLY);
7147 } else {
7148 xmove_fd(next_infd, 0);
7149 }
7150 xmove_fd(pipefds.wr, 1);
7151 if (pipefds.rd > 1)
7152 close(pipefds.rd);
7153 /* Like bash, explicit redirects override pipes,
7154 * and the pipe fd is available for dup'ing. */
7155 if (setup_redirects(command, NULL))
7156 _exit(1);
7157
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007158 /* Stores to nommu_save list of env vars putenv'ed
7159 * (NOMMU, on MMU we don't need that) */
7160 /* cast away volatility... */
7161 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7162 /* pseudo_exec() does not return */
7163 }
7164
7165 /* parent or error */
7166#if ENABLE_HUSH_FAST
7167 G.count_SIGCHLD++;
7168//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7169#endif
7170 enable_restore_tty_pgrp_on_exit();
7171#if !BB_MMU
7172 /* Clean up after vforked child */
7173 free(nommu_save.argv);
7174 free(nommu_save.argv_from_re_execing);
7175 unset_vars(nommu_save.new_env);
7176 add_vars(nommu_save.old_vars);
7177#endif
7178 free(argv_expanded);
7179 argv_expanded = NULL;
7180 if (command->pid < 0) { /* [v]fork failed */
7181 /* Clearly indicate, was it fork or vfork */
7182 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7183 } else {
7184 pi->alive_cmds++;
7185#if ENABLE_HUSH_JOB
7186 /* Second and next children need to know pid of first one */
7187 if (pi->pgrp < 0)
7188 pi->pgrp = command->pid;
7189#endif
7190 }
7191
7192 if (cmd_no > 1)
7193 close(next_infd);
7194 if (cmd_no < pi->num_cmds)
7195 close(pipefds.wr);
7196 /* Pass read (output) pipe end to next iteration */
7197 next_infd = pipefds.rd;
7198 }
7199
7200 if (!pi->alive_cmds) {
7201 debug_leave();
7202 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7203 return 1;
7204 }
7205
7206 debug_leave();
7207 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7208 return -1;
7209}
7210
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007211/* NB: called by pseudo_exec, and therefore must not modify any
7212 * global data until exec/_exit (we can be a child after vfork!) */
7213static int run_list(struct pipe *pi)
7214{
7215#if ENABLE_HUSH_CASE
7216 char *case_word = NULL;
7217#endif
7218#if ENABLE_HUSH_LOOPS
7219 struct pipe *loop_top = NULL;
7220 char **for_lcur = NULL;
7221 char **for_list = NULL;
7222#endif
7223 smallint last_followup;
7224 smalluint rcode;
7225#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7226 smalluint cond_code = 0;
7227#else
7228 enum { cond_code = 0 };
7229#endif
7230#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007231 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007232 smallint last_rword; /* ditto */
7233#endif
7234
7235 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7236 debug_enter();
7237
7238#if ENABLE_HUSH_LOOPS
7239 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007240 {
7241 struct pipe *cpipe;
7242 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7243 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7244 continue;
7245 /* current word is FOR or IN (BOLD in comments below) */
7246 if (cpipe->next == NULL) {
7247 syntax_error("malformed for");
7248 debug_leave();
7249 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7250 return 1;
7251 }
7252 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7253 if (cpipe->next->res_word == RES_DO)
7254 continue;
7255 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7256 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7257 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7258 ) {
7259 syntax_error("malformed for");
7260 debug_leave();
7261 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7262 return 1;
7263 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007264 }
7265 }
7266#endif
7267
7268 /* Past this point, all code paths should jump to ret: label
7269 * in order to return, no direct "return" statements please.
7270 * This helps to ensure that no memory is leaked. */
7271
7272#if ENABLE_HUSH_JOB
7273 G.run_list_level++;
7274#endif
7275
7276#if HAS_KEYWORDS
7277 rword = RES_NONE;
7278 last_rword = RES_XXXX;
7279#endif
7280 last_followup = PIPE_SEQ;
7281 rcode = G.last_exitcode;
7282
7283 /* Go through list of pipes, (maybe) executing them. */
7284 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7285 if (G.flag_SIGINT)
7286 break;
7287
7288 IF_HAS_KEYWORDS(rword = pi->res_word;)
7289 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7290 rword, cond_code, last_rword);
7291#if ENABLE_HUSH_LOOPS
7292 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7293 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7294 ) {
7295 /* start of a loop: remember where loop starts */
7296 loop_top = pi;
7297 G.depth_of_loop++;
7298 }
7299#endif
7300 /* Still in the same "if...", "then..." or "do..." branch? */
7301 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7302 if ((rcode == 0 && last_followup == PIPE_OR)
7303 || (rcode != 0 && last_followup == PIPE_AND)
7304 ) {
7305 /* It is "<true> || CMD" or "<false> && CMD"
7306 * and we should not execute CMD */
7307 debug_printf_exec("skipped cmd because of || or &&\n");
7308 last_followup = pi->followup;
7309 continue;
7310 }
7311 }
7312 last_followup = pi->followup;
7313 IF_HAS_KEYWORDS(last_rword = rword;)
7314#if ENABLE_HUSH_IF
7315 if (cond_code) {
7316 if (rword == RES_THEN) {
7317 /* if false; then ... fi has exitcode 0! */
7318 G.last_exitcode = rcode = EXIT_SUCCESS;
7319 /* "if <false> THEN cmd": skip cmd */
7320 continue;
7321 }
7322 } else {
7323 if (rword == RES_ELSE || rword == RES_ELIF) {
7324 /* "if <true> then ... ELSE/ELIF cmd":
7325 * skip cmd and all following ones */
7326 break;
7327 }
7328 }
7329#endif
7330#if ENABLE_HUSH_LOOPS
7331 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7332 if (!for_lcur) {
7333 /* first loop through for */
7334
7335 static const char encoded_dollar_at[] ALIGN1 = {
7336 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7337 }; /* encoded representation of "$@" */
7338 static const char *const encoded_dollar_at_argv[] = {
7339 encoded_dollar_at, NULL
7340 }; /* argv list with one element: "$@" */
7341 char **vals;
7342
7343 vals = (char**)encoded_dollar_at_argv;
7344 if (pi->next->res_word == RES_IN) {
7345 /* if no variable values after "in" we skip "for" */
7346 if (!pi->next->cmds[0].argv) {
7347 G.last_exitcode = rcode = EXIT_SUCCESS;
7348 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7349 break;
7350 }
7351 vals = pi->next->cmds[0].argv;
7352 } /* else: "for var; do..." -> assume "$@" list */
7353 /* create list of variable values */
7354 debug_print_strings("for_list made from", vals);
7355 for_list = expand_strvec_to_strvec(vals);
7356 for_lcur = for_list;
7357 debug_print_strings("for_list", for_list);
7358 }
7359 if (!*for_lcur) {
7360 /* "for" loop is over, clean up */
7361 free(for_list);
7362 for_list = NULL;
7363 for_lcur = NULL;
7364 break;
7365 }
7366 /* Insert next value from for_lcur */
7367 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7368 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7369 continue;
7370 }
7371 if (rword == RES_IN) {
7372 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7373 }
7374 if (rword == RES_DONE) {
7375 continue; /* "done" has no cmds too */
7376 }
7377#endif
7378#if ENABLE_HUSH_CASE
7379 if (rword == RES_CASE) {
7380 case_word = expand_strvec_to_string(pi->cmds->argv);
7381 continue;
7382 }
7383 if (rword == RES_MATCH) {
7384 char **argv;
7385
7386 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7387 break;
7388 /* all prev words didn't match, does this one match? */
7389 argv = pi->cmds->argv;
7390 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007391 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007392 /* TODO: which FNM_xxx flags to use? */
7393 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7394 free(pattern);
7395 if (cond_code == 0) { /* match! we will execute this branch */
7396 free(case_word); /* make future "word)" stop */
7397 case_word = NULL;
7398 break;
7399 }
7400 argv++;
7401 }
7402 continue;
7403 }
7404 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7405 if (cond_code != 0)
7406 continue; /* not matched yet, skip this pipe */
7407 }
7408#endif
7409 /* Just pressing <enter> in shell should check for jobs.
7410 * OTOH, in non-interactive shell this is useless
7411 * and only leads to extra job checks */
7412 if (pi->num_cmds == 0) {
7413 if (G_interactive_fd)
7414 goto check_jobs_and_continue;
7415 continue;
7416 }
7417
7418 /* After analyzing all keywords and conditions, we decided
7419 * to execute this pipe. NB: have to do checkjobs(NULL)
7420 * after run_pipe to collect any background children,
7421 * even if list execution is to be stopped. */
7422 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7423 {
7424 int r;
7425#if ENABLE_HUSH_LOOPS
7426 G.flag_break_continue = 0;
7427#endif
7428 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7429 if (r != -1) {
7430 /* We ran a builtin, function, or group.
7431 * rcode is already known
7432 * and we don't need to wait for anything. */
7433 G.last_exitcode = rcode;
7434 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007435 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007436#if ENABLE_HUSH_LOOPS
7437 /* Was it "break" or "continue"? */
7438 if (G.flag_break_continue) {
7439 smallint fbc = G.flag_break_continue;
7440 /* We might fall into outer *loop*,
7441 * don't want to break it too */
7442 if (loop_top) {
7443 G.depth_break_continue--;
7444 if (G.depth_break_continue == 0)
7445 G.flag_break_continue = 0;
7446 /* else: e.g. "continue 2" should *break* once, *then* continue */
7447 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7448 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7449 goto check_jobs_and_break;
7450 /* "continue": simulate end of loop */
7451 rword = RES_DONE;
7452 continue;
7453 }
7454#endif
7455#if ENABLE_HUSH_FUNCTIONS
7456 if (G.flag_return_in_progress == 1) {
7457 /* same as "goto check_jobs_and_break" */
7458 checkjobs(NULL);
7459 break;
7460 }
7461#endif
7462 } else if (pi->followup == PIPE_BG) {
7463 /* What does bash do with attempts to background builtins? */
7464 /* even bash 3.2 doesn't do that well with nested bg:
7465 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7466 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007467 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007468#if ENABLE_HUSH_JOB
7469 if (G.run_list_level == 1)
7470 insert_bg_job(pi);
7471#endif
7472 /* Last command's pid goes to $! */
7473 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7474 G.last_exitcode = rcode = EXIT_SUCCESS;
7475 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7476 } else {
7477#if ENABLE_HUSH_JOB
7478 if (G.run_list_level == 1 && G_interactive_fd) {
7479 /* Waits for completion, then fg's main shell */
7480 rcode = checkjobs_and_fg_shell(pi);
7481 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007482 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007483 } else
7484#endif
7485 { /* This one just waits for completion */
7486 rcode = checkjobs(pi);
7487 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007488 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007489 }
7490 G.last_exitcode = rcode;
7491 }
7492 }
7493
7494 /* Analyze how result affects subsequent commands */
7495#if ENABLE_HUSH_IF
7496 if (rword == RES_IF || rword == RES_ELIF)
7497 cond_code = rcode;
7498#endif
7499#if ENABLE_HUSH_LOOPS
7500 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007501 if (pi->next
7502 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02007503 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007504 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007505 if (rword == RES_WHILE) {
7506 if (rcode) {
7507 /* "while false; do...done" - exitcode 0 */
7508 G.last_exitcode = rcode = EXIT_SUCCESS;
7509 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7510 goto check_jobs_and_break;
7511 }
7512 }
7513 if (rword == RES_UNTIL) {
7514 if (!rcode) {
7515 debug_printf_exec(": until expr is true: breaking\n");
7516 check_jobs_and_break:
7517 checkjobs(NULL);
7518 break;
7519 }
7520 }
7521 }
7522#endif
7523
7524 check_jobs_and_continue:
7525 checkjobs(NULL);
7526 } /* for (pi) */
7527
7528#if ENABLE_HUSH_JOB
7529 G.run_list_level--;
7530#endif
7531#if ENABLE_HUSH_LOOPS
7532 if (loop_top)
7533 G.depth_of_loop--;
7534 free(for_list);
7535#endif
7536#if ENABLE_HUSH_CASE
7537 free(case_word);
7538#endif
7539 debug_leave();
7540 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7541 return rcode;
7542}
7543
7544/* Select which version we will use */
7545static int run_and_free_list(struct pipe *pi)
7546{
7547 int rcode = 0;
7548 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007549 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007550 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7551 rcode = run_list(pi);
7552 }
7553 /* free_pipe_list has the side effect of clearing memory.
7554 * In the long run that function can be merged with run_list,
7555 * but doing that now would hobble the debugging effort. */
7556 free_pipe_list(pi);
7557 debug_printf_exec("run_and_free_list return %d\n", rcode);
7558 return rcode;
7559}
7560
7561
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007562static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007563{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007564 sighandler_t old_handler;
7565 unsigned sig = 0;
7566 while ((mask >>= 1) != 0) {
7567 sig++;
7568 if (!(mask & 1))
7569 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007570 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007571 /* POSIX allows shell to re-enable SIGCHLD
7572 * even if it was SIG_IGN on entry.
7573 * Therefore we skip IGN check for it:
7574 */
7575 if (sig == SIGCHLD)
7576 continue;
7577 if (old_handler == SIG_IGN) {
7578 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007579 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007580 if (!G.traps)
7581 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7582 free(G.traps[sig]);
7583 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7584 }
7585 }
7586}
7587
7588/* Called a few times only (or even once if "sh -c") */
7589static void install_special_sighandlers(void)
7590{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007591 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007592
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007593 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007594 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007595 if (G_interactive_fd) {
7596 mask |= SPECIAL_INTERACTIVE_SIGS;
7597 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007598 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007599 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007600 /* Careful, do not re-install handlers we already installed */
7601 if (G.special_sig_mask != mask) {
7602 unsigned diff = mask & ~G.special_sig_mask;
7603 G.special_sig_mask = mask;
7604 install_sighandlers(diff);
7605 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007606}
7607
7608#if ENABLE_HUSH_JOB
7609/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007610/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007611static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007612{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007613 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007614
7615 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007616 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007617 + (1 << SIGILL ) * HUSH_DEBUG
7618 + (1 << SIGFPE ) * HUSH_DEBUG
7619 + (1 << SIGBUS ) * HUSH_DEBUG
7620 + (1 << SIGSEGV) * HUSH_DEBUG
7621 + (1 << SIGTRAP) * HUSH_DEBUG
7622 + (1 << SIGABRT)
7623 /* bash 3.2 seems to handle these just like 'fatal' ones */
7624 + (1 << SIGPIPE)
7625 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007626 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007627 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007628 * we never want to restore pgrp on exit, and this fn is not called
7629 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007630 /*+ (1 << SIGHUP )*/
7631 /*+ (1 << SIGTERM)*/
7632 /*+ (1 << SIGINT )*/
7633 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007634 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007635
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007636 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007637}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007638#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007639
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007640static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007641{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007642 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007643 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007644 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007645 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007646 break;
7647 case 'x':
7648 IF_HUSH_MODE_X(G_x_mode = state;)
7649 break;
7650 case 'o':
7651 if (!o_opt) {
7652 /* "set -+o" without parameter.
7653 * in bash, set -o produces this output:
7654 * pipefail off
7655 * and set +o:
7656 * set +o pipefail
7657 * We always use the second form.
7658 */
7659 const char *p = o_opt_strings;
7660 idx = 0;
7661 while (*p) {
7662 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7663 idx++;
7664 p += strlen(p) + 1;
7665 }
7666 break;
7667 }
7668 idx = index_in_strings(o_opt_strings, o_opt);
7669 if (idx >= 0) {
7670 G.o_opt[idx] = state;
7671 break;
7672 }
7673 default:
7674 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007675 }
7676 return EXIT_SUCCESS;
7677}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007678
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007679int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007680int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007681{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007682 enum {
7683 OPT_login = (1 << 0),
7684 };
7685 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00007686 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007687 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007688 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007689 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007690 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007691
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007692 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02007693 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007694 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenko10c01312011-05-11 11:49:21 +02007695#if ENABLE_HUSH_FAST
7696 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7697#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007698#if !BB_MMU
7699 G.argv0_for_re_execing = argv[0];
7700#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007701 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007702 shell_ver = xzalloc(sizeof(*shell_ver));
7703 shell_ver->flg_export = 1;
7704 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007705 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007706 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007707 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007708 /* Create shell local variables from the values
7709 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007710 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007711 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007712 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007713 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007714 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007715 if (e) while (*e) {
7716 char *value = strchr(*e, '=');
7717 if (value) { /* paranoia */
7718 cur_var->next = xzalloc(sizeof(*cur_var));
7719 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007720 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007721 cur_var->max_len = strlen(*e);
7722 cur_var->flg_export = 1;
7723 }
7724 e++;
7725 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007726 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007727 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7728 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007729
7730 /* Export PWD */
7731 set_pwd_var(/*exp:*/ 1);
7732 /* bash also exports SHLVL and _,
7733 * and sets (but doesn't export) the following variables:
7734 * BASH=/bin/bash
7735 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7736 * BASH_VERSION='3.2.0(1)-release'
7737 * HOSTTYPE=i386
7738 * MACHTYPE=i386-pc-linux-gnu
7739 * OSTYPE=linux-gnu
7740 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007741 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007742 * EUID=<NNNNN>
7743 * UID=<NNNNN>
7744 * GROUPS=()
7745 * LINES=<NNN>
7746 * COLUMNS=<NNN>
7747 * BASH_ARGC=()
7748 * BASH_ARGV=()
7749 * BASH_LINENO=()
7750 * BASH_SOURCE=()
7751 * DIRSTACK=()
7752 * PIPESTATUS=([0]="0")
7753 * HISTFILE=/<xxx>/.bash_history
7754 * HISTFILESIZE=500
7755 * HISTSIZE=500
7756 * MAILCHECK=60
7757 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7758 * SHELL=/bin/bash
7759 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7760 * TERM=dumb
7761 * OPTERR=1
7762 * OPTIND=1
7763 * IFS=$' \t\n'
7764 * PS1='\s-\v\$ '
7765 * PS2='> '
7766 * PS4='+ '
7767 */
7768
Denis Vlasenko38f63192007-01-22 09:03:07 +00007769#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007770 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007771# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7772 {
7773 const char *hp = get_local_var_value("HISTFILE");
7774 if (!hp) {
7775 hp = get_local_var_value("HOME");
7776 if (hp) {
7777 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7778 //set_local_var(xasprintf("HISTFILE=%s", ...));
7779 }
7780 }
Denys Vlasenko2c4de5b2011-03-31 13:16:52 +02007781# if ENABLE_FEATURE_SH_HISTFILESIZE
7782 hp = get_local_var_value("HISTFILESIZE");
7783 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
7784# endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007785 }
7786# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007787#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007788
Eric Andersen94ac2442001-05-22 19:05:18 +00007789 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007790 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007791
Denis Vlasenkoed782372009-04-10 00:45:02 +00007792 if (setjmp(die_jmp)) {
7793 /* xfunc has failed! die die die */
7794 /* no EXIT traps, this is an escape hatch! */
7795 G.exiting = 1;
7796 hush_exit(xfunc_error_retval);
7797 }
7798
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007799 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007800 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007801 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007802 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007803 * in order to intercept (more) signals.
7804 */
7805
7806 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007807 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007808 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007809 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007810 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007811 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007812#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007813 "<:$:R:V:"
7814# if ENABLE_HUSH_FUNCTIONS
7815 "F:"
7816# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007817#endif
7818 );
7819 if (opt <= 0)
7820 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007821 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007822 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007823 /* Possibilities:
7824 * sh ... -c 'script'
7825 * sh ... -c 'script' ARG0 [ARG1...]
7826 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007827 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007828 * "" needs to be replaced with NULL
7829 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007830 * Note: the form without ARG0 never happens:
7831 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007832 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007833 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007834 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007835 G.root_ppid = getppid();
7836 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007837 G.global_argv = argv + optind;
7838 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007839 if (builtin_argc) {
7840 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7841 const struct built_in_command *x;
7842
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007843 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007844 x = find_builtin(optarg);
7845 if (x) { /* paranoia */
7846 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7847 G.global_argv += builtin_argc;
7848 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007849 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007850 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007851 }
7852 goto final_return;
7853 }
7854 if (!G.global_argv[0]) {
7855 /* -c 'script' (no params): prevent empty $0 */
7856 G.global_argv--; /* points to argv[i] of 'script' */
7857 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007858 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007859 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007860 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007861 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007862 goto final_return;
7863 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007864 /* Well, we cannot just declare interactiveness,
7865 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007866 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007867 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007868 case 's':
7869 /* "-s" means "read from stdin", but this is how we always
7870 * operate, so simply do nothing here. */
7871 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007872 case 'l':
7873 flags |= OPT_login;
7874 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007875#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007876 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007877 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007878 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007879 case '$': {
7880 unsigned long long empty_trap_mask;
7881
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007882 G.root_pid = bb_strtou(optarg, &optarg, 16);
7883 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007884 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7885 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007886 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7887 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007888 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007889 optarg++;
7890 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007891 optarg++;
7892 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7893 if (empty_trap_mask != 0) {
7894 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007895 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007896 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7897 for (sig = 1; sig < NSIG; sig++) {
7898 if (empty_trap_mask & (1LL << sig)) {
7899 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007900 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007901 }
7902 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007903 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007904# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007905 optarg++;
7906 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007907# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007908 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007909 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007910 case 'R':
7911 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007912 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007913 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007914# if ENABLE_HUSH_FUNCTIONS
7915 case 'F': {
7916 struct function *funcp = new_function(optarg);
7917 /* funcp->name is already set to optarg */
7918 /* funcp->body is set to NULL. It's a special case. */
7919 funcp->body_as_string = argv[optind];
7920 optind++;
7921 break;
7922 }
7923# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007924#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007925 case 'n':
7926 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007927 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007928 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007929 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007930#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007931 fprintf(stderr, "Usage: sh [FILE]...\n"
7932 " or: sh -c command [args]...\n\n");
7933 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007934#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007935 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007936#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007937 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007938 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007939
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007940 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7941 G.global_argc = argc - (optind - 1);
7942 G.global_argv = argv + (optind - 1);
7943 G.global_argv[0] = argv[0];
7944
Denys Vlasenkodea47882009-10-09 15:40:49 +02007945 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007946 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007947 G.root_ppid = getppid();
7948 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007949
7950 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007951 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007952 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007953 debug_printf("sourcing /etc/profile\n");
7954 input = fopen_for_read("/etc/profile");
7955 if (input != NULL) {
7956 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007957 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007958 parse_and_run_file(input);
7959 fclose(input);
7960 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007961 /* bash: after sourcing /etc/profile,
7962 * tries to source (in the given order):
7963 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007964 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007965 * bash also sources ~/.bash_logout on exit.
7966 * If called as sh, skips .bash_XXX files.
7967 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007968 }
7969
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007970 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007971 FILE *input;
7972 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007973 * "bash <script>" (which is never interactive (unless -i?))
7974 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007975 * If called as sh, does the same but with $ENV.
7976 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007977 G.global_argc--;
7978 G.global_argv++;
7979 debug_printf("running script '%s'\n", G.global_argv[0]);
7980 input = xfopen_for_read(G.global_argv[0]);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007981 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007982 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007983 parse_and_run_file(input);
7984#if ENABLE_FEATURE_CLEAN_UP
7985 fclose(input);
7986#endif
7987 goto final_return;
7988 }
7989
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007990 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007991 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007992 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007993
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007994 /* A shell is interactive if the '-i' flag was given,
7995 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007996 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007997 * no arguments remaining or the -s flag given
7998 * standard input is a terminal
7999 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008000 * Refer to Posix.2, the description of the 'sh' utility.
8001 */
8002#if ENABLE_HUSH_JOB
8003 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008004 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8005 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8006 if (G_saved_tty_pgrp < 0)
8007 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008008
8009 /* try to dup stdin to high fd#, >= 255 */
8010 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8011 if (G_interactive_fd < 0) {
8012 /* try to dup to any fd */
8013 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008014 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008015 /* give up */
8016 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008017 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008018 }
8019 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008020// TODO: track & disallow any attempts of user
8021// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008022 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008023 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008024 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008025 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008026
Mike Frysinger38478a62009-05-20 04:48:06 -04008027 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008028 /* If we were run as 'hush &', sleep until we are
8029 * in the foreground (tty pgrp == our pgrp).
8030 * If we get started under a job aware app (like bash),
8031 * make sure we are now in charge so we don't fight over
8032 * who gets the foreground */
8033 while (1) {
8034 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008035 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8036 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008037 break;
8038 /* send TTIN to ourself (should stop us) */
8039 kill(- shell_pgrp, SIGTTIN);
8040 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008041 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008042
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008043 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008044 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008045
Mike Frysinger38478a62009-05-20 04:48:06 -04008046 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008047 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008048 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008049 /* Put ourselves in our own process group
8050 * (bash, too, does this only if ctty is available) */
8051 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8052 /* Grab control of the terminal */
8053 tcsetpgrp(G_interactive_fd, getpid());
8054 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00008055 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00008056 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00008057 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008058 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008059 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008060 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008061#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008062 /* No job control compiled in, only prompt/line editing */
8063 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008064 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8065 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008066 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008067 G_interactive_fd = dup(STDIN_FILENO);
8068 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008069 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008070 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008071 }
8072 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008073 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008074 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008075 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008076 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008077#else
8078 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008079 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008080#endif
8081 /* bash:
8082 * if interactive but not a login shell, sources ~/.bashrc
8083 * (--norc turns this off, --rcfile <file> overrides)
8084 */
8085
8086 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008087 /* note: ash and hush share this string */
8088 printf("\n\n%s %s\n"
8089 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8090 "\n",
8091 bb_banner,
8092 "hush - the humble shell"
8093 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008094 }
8095
Denis Vlasenkof9375282009-04-05 19:13:39 +00008096 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008097
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008098 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008099 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008100}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008101
8102
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008103#if ENABLE_MSH
8104int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8105int msh_main(int argc, char **argv)
8106{
8107 //bb_error_msg("msh is deprecated, please use hush instead");
8108 return hush_main(argc, argv);
8109}
8110#endif
8111
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008112
8113/*
8114 * Built-ins
8115 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008116static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008117{
8118 return 0;
8119}
8120
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008121static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008122{
8123 int argc = 0;
8124 while (*argv) {
8125 argc++;
8126 argv++;
8127 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008128 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008129}
8130
8131static int FAST_FUNC builtin_test(char **argv)
8132{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008133 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008134}
8135
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008136static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008137{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008138 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008139}
8140
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008141#if ENABLE_PRINTF
8142static int FAST_FUNC builtin_printf(char **argv)
8143{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008144 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008145}
8146#endif
8147
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008148static char **skip_dash_dash(char **argv)
8149{
8150 argv++;
8151 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8152 argv++;
8153 return argv;
8154}
8155
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008156static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008157{
8158 int rcode = EXIT_SUCCESS;
8159
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008160 argv = skip_dash_dash(argv);
8161 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008162 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008163 /* bash:
8164 * eval "echo Hi; done" ("done" is syntax error):
8165 * "echo Hi" will not execute too.
8166 */
8167 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008168 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008169 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008170 }
8171 return rcode;
8172}
8173
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008174static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008175{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008176 const char *newdir;
8177
8178 argv = skip_dash_dash(argv);
8179 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008180 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008181 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008182 * bash says "bash: cd: HOME not set" and does nothing
8183 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008184 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008185 const char *home = get_local_var_value("HOME");
8186 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008187 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008188 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008189 /* Mimic bash message exactly */
8190 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008191 return EXIT_FAILURE;
8192 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008193 /* Read current dir (get_cwd(1) is inside) and set PWD.
8194 * Note: do not enforce exporting. If PWD was unset or unexported,
8195 * set it again, but do not export. bash does the same.
8196 */
8197 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008198 return EXIT_SUCCESS;
8199}
8200
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008201static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008202{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008203 argv = skip_dash_dash(argv);
8204 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008205 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008206
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008207 /* Careful: we can end up here after [v]fork. Do not restore
8208 * tty pgrp then, only top-level shell process does that */
8209 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8210 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8211
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008212 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008213 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008214 * and tcsetpgrp, and this is inherently racy.
8215 */
8216 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008217}
8218
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008219static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008220{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008221 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008222
8223 /* interactive bash:
8224 * # trap "echo EEE" EXIT
8225 * # exit
8226 * exit
8227 * There are stopped jobs.
8228 * (if there are _stopped_ jobs, running ones don't count)
8229 * # exit
8230 * exit
8231 # EEE (then bash exits)
8232 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008233 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008234 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008235
8236 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008237 argv = skip_dash_dash(argv);
8238 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008239 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008240 /* mimic bash: exit 123abc == exit 255 + error msg */
8241 xfunc_error_retval = 255;
8242 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008243 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008244}
8245
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008246static void print_escaped(const char *s)
8247{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008248 if (*s == '\'')
8249 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008250 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008251 const char *p = strchrnul(s, '\'');
8252 /* print 'xxxx', possibly just '' */
8253 printf("'%.*s'", (int)(p - s), s);
8254 if (*p == '\0')
8255 break;
8256 s = p;
8257 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008258 /* s points to '; print "'''...'''" */
8259 putchar('"');
8260 do putchar('\''); while (*++s == '\'');
8261 putchar('"');
8262 } while (*s);
8263}
8264
Denys Vlasenko295fef82009-06-03 12:47:26 +02008265#if !ENABLE_HUSH_LOCAL
8266#define helper_export_local(argv, exp, lvl) \
8267 helper_export_local(argv, exp)
8268#endif
8269static void helper_export_local(char **argv, int exp, int lvl)
8270{
8271 do {
8272 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008273 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008274
8275 /* So far we do not check that name is valid (TODO?) */
8276
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008277 if (*name_end == '\0') {
8278 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008279
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008280 vpp = get_ptr_to_local_var(name, name_end - name);
8281 var = vpp ? *vpp : NULL;
8282
Denys Vlasenko295fef82009-06-03 12:47:26 +02008283 if (exp == -1) { /* unexporting? */
8284 /* export -n NAME (without =VALUE) */
8285 if (var) {
8286 var->flg_export = 0;
8287 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8288 unsetenv(name);
8289 } /* else: export -n NOT_EXISTING_VAR: no-op */
8290 continue;
8291 }
8292 if (exp == 1) { /* exporting? */
8293 /* export NAME (without =VALUE) */
8294 if (var) {
8295 var->flg_export = 1;
8296 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8297 putenv(var->varstr);
8298 continue;
8299 }
8300 }
8301 /* Exporting non-existing variable.
8302 * bash does not put it in environment,
8303 * but remembers that it is exported,
8304 * and does put it in env when it is set later.
8305 * We just set it to "" and export. */
8306 /* Or, it's "local NAME" (without =VALUE).
8307 * bash sets the value to "". */
8308 name = xasprintf("%s=", name);
8309 } else {
8310 /* (Un)exporting/making local NAME=VALUE */
8311 name = xstrdup(name);
8312 }
8313 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8314 } while (*++argv);
8315}
8316
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008317static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008318{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008319 unsigned opt_unexport;
8320
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008321#if ENABLE_HUSH_EXPORT_N
8322 /* "!": do not abort on errors */
8323 opt_unexport = getopt32(argv, "!n");
8324 if (opt_unexport == (uint32_t)-1)
8325 return EXIT_FAILURE;
8326 argv += optind;
8327#else
8328 opt_unexport = 0;
8329 argv++;
8330#endif
8331
8332 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008333 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008334 if (e) {
8335 while (*e) {
8336#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008337 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008338#else
8339 /* ash emits: export VAR='VAL'
8340 * bash: declare -x VAR="VAL"
8341 * we follow ash example */
8342 const char *s = *e++;
8343 const char *p = strchr(s, '=');
8344
8345 if (!p) /* wtf? take next variable */
8346 continue;
8347 /* export var= */
8348 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008349 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008350 putchar('\n');
8351#endif
8352 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008353 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008354 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008355 return EXIT_SUCCESS;
8356 }
8357
Denys Vlasenko295fef82009-06-03 12:47:26 +02008358 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008359
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008360 return EXIT_SUCCESS;
8361}
8362
Denys Vlasenko295fef82009-06-03 12:47:26 +02008363#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008364static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008365{
8366 if (G.func_nest_level == 0) {
8367 bb_error_msg("%s: not in a function", argv[0]);
8368 return EXIT_FAILURE; /* bash compat */
8369 }
8370 helper_export_local(argv, 0, G.func_nest_level);
8371 return EXIT_SUCCESS;
8372}
8373#endif
8374
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008375static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008376{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008377 int sig;
8378 char *new_cmd;
8379
8380 if (!G.traps)
8381 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8382
8383 argv++;
8384 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008385 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008386 /* No args: print all trapped */
8387 for (i = 0; i < NSIG; ++i) {
8388 if (G.traps[i]) {
8389 printf("trap -- ");
8390 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008391 /* note: bash adds "SIG", but only if invoked
8392 * as "bash". If called as "sh", or if set -o posix,
8393 * then it prints short signal names.
8394 * We are printing short names: */
8395 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008396 }
8397 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008398 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008399 return EXIT_SUCCESS;
8400 }
8401
8402 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008403 /* If first arg is a number: reset all specified signals */
8404 sig = bb_strtou(*argv, NULL, 10);
8405 if (errno == 0) {
8406 int ret;
8407 process_sig_list:
8408 ret = EXIT_SUCCESS;
8409 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008410 sighandler_t handler;
8411
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008412 sig = get_signum(*argv++);
8413 if (sig < 0 || sig >= NSIG) {
8414 ret = EXIT_FAILURE;
8415 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008416 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008417 continue;
8418 }
8419
8420 free(G.traps[sig]);
8421 G.traps[sig] = xstrdup(new_cmd);
8422
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008423 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008424 get_signame(sig), sig, G.traps[sig]);
8425
8426 /* There is no signal for 0 (EXIT) */
8427 if (sig == 0)
8428 continue;
8429
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008430 if (new_cmd)
8431 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8432 else
8433 /* We are removing trap handler */
8434 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02008435 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008436 }
8437 return ret;
8438 }
8439
8440 if (!argv[1]) { /* no second arg */
8441 bb_error_msg("trap: invalid arguments");
8442 return EXIT_FAILURE;
8443 }
8444
8445 /* First arg is "-": reset all specified to default */
8446 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8447 /* Everything else: set arg as signal handler
8448 * (includes "" case, which ignores signal) */
8449 if (argv[0][0] == '-') {
8450 if (argv[0][1] == '\0') { /* "-" */
8451 /* new_cmd remains NULL: "reset these sigs" */
8452 goto reset_traps;
8453 }
8454 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8455 argv++;
8456 }
8457 /* else: "-something", no special meaning */
8458 }
8459 new_cmd = *argv;
8460 reset_traps:
8461 argv++;
8462 goto process_sig_list;
8463}
8464
Mike Frysinger93cadc22009-05-27 17:06:25 -04008465/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008466static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008467{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008468 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008469
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008470 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008471 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008472 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008473
8474 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008475 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008476 type = "an alias";*/
8477#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008478 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008479 type = "a function";
8480#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008481 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008482 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008483 else if ((path = find_in_path(*argv)) != NULL)
8484 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008485 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008486 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008487 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008488 continue;
8489 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008490
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008491 printf("%s is %s\n", *argv, type);
8492 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008493 }
8494
8495 return ret;
8496}
8497
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008498#if ENABLE_HUSH_JOB
8499/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008500static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008501{
8502 int i, jobnum;
8503 struct pipe *pi;
8504
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008505 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008506 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008507
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008508 /* If they gave us no args, assume they want the last backgrounded task */
8509 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008510 for (pi = G.job_list; pi; pi = pi->next) {
8511 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008512 goto found;
8513 }
8514 }
8515 bb_error_msg("%s: no current job", argv[0]);
8516 return EXIT_FAILURE;
8517 }
8518 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8519 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8520 return EXIT_FAILURE;
8521 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008522 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008523 if (pi->jobid == jobnum) {
8524 goto found;
8525 }
8526 }
8527 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8528 return EXIT_FAILURE;
8529 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008530 /* TODO: bash prints a string representation
8531 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008532 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008533 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008534 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008535 }
8536
8537 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008538 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8539 for (i = 0; i < pi->num_cmds; i++) {
8540 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8541 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008542 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008543 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008544
8545 i = kill(- pi->pgrp, SIGCONT);
8546 if (i < 0) {
8547 if (errno == ESRCH) {
8548 delete_finished_bg_job(pi);
8549 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008550 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008551 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008552 }
8553
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008554 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008555 remove_bg_job(pi);
8556 return checkjobs_and_fg_shell(pi);
8557 }
8558 return EXIT_SUCCESS;
8559}
8560#endif
8561
8562#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008563static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008564{
8565 const struct built_in_command *x;
8566
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008567 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008568 "Built-in commands:\n"
8569 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008570 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008571 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008572 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008573 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008574 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008575 return EXIT_SUCCESS;
8576}
8577#endif
8578
8579#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008580static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008581{
8582 struct pipe *job;
8583 const char *status_string;
8584
Denis Vlasenko87a86552008-07-29 19:43:10 +00008585 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008586 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008587 status_string = "Stopped";
8588 else
8589 status_string = "Running";
8590
8591 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8592 }
8593 return EXIT_SUCCESS;
8594}
8595#endif
8596
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008597#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008598static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008599{
8600 void *p;
8601 unsigned long l;
8602
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008603# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008604 /* Optional. Reduces probability of false positives */
8605 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008606# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008607 /* Crude attempt to find where "free memory" starts,
8608 * sans fragmentation. */
8609 p = malloc(240);
8610 l = (unsigned long)p;
8611 free(p);
8612 p = malloc(3400);
8613 if (l < (unsigned long)p) l = (unsigned long)p;
8614 free(p);
8615
8616 if (!G.memleak_value)
8617 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008618
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008619 l -= G.memleak_value;
8620 if ((long)l < 0)
8621 l = 0;
8622 l /= 1024;
8623 if (l > 127)
8624 l = 127;
8625
8626 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8627 return l;
8628}
8629#endif
8630
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008631static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008632{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008633 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008634 return EXIT_SUCCESS;
8635}
8636
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008637/* Interruptibility of read builtin in bash
8638 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8639 *
8640 * Empty trap makes read ignore corresponding signal, for any signal.
8641 *
8642 * SIGINT:
8643 * - terminates non-interactive shell;
8644 * - interrupts read in interactive shell;
8645 * if it has non-empty trap:
8646 * - executes trap and returns to command prompt in interactive shell;
8647 * - executes trap and returns to read in non-interactive shell;
8648 * SIGTERM:
8649 * - is ignored (does not interrupt) read in interactive shell;
8650 * - terminates non-interactive shell;
8651 * if it has non-empty trap:
8652 * - executes trap and returns to read;
8653 * SIGHUP:
8654 * - terminates shell (regardless of interactivity);
8655 * if it has non-empty trap:
8656 * - executes trap and returns to read;
8657 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008658static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008659{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008660 const char *r;
8661 char *opt_n = NULL;
8662 char *opt_p = NULL;
8663 char *opt_t = NULL;
8664 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008665 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01008666 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008667
Denys Vlasenko03dad222010-01-12 23:29:57 +01008668 /* "!": do not abort on errors.
8669 * Option string must start with "sr" to match BUILTIN_READ_xxx
8670 */
8671 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8672 if (read_flags == (uint32_t)-1)
8673 return EXIT_FAILURE;
8674 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008675 ifs = get_local_var_value("IFS"); /* can be NULL */
8676
8677 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01008678 r = shell_builtin_read(set_local_var_from_halves,
8679 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008680 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01008681 read_flags,
8682 opt_n,
8683 opt_p,
8684 opt_t,
8685 opt_u
8686 );
8687
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008688 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008689 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008690 if (sig && sig != SIGINT)
8691 goto again;
8692 }
8693
Denys Vlasenko03dad222010-01-12 23:29:57 +01008694 if ((uintptr_t)r > 1) {
8695 bb_error_msg("%s", r);
8696 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008697 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008698
Denys Vlasenko03dad222010-01-12 23:29:57 +01008699 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008700}
8701
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008702/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8703 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008704 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008705 * set [-abCefhmnuvx] [-o option] [argument...]
8706 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008707 * set -- [argument...]
8708 * set -o
8709 * set +o
8710 * Implementations shall support the options in both their hyphen and
8711 * plus-sign forms. These options can also be specified as options to sh.
8712 * Examples:
8713 * Write out all variables and their values: set
8714 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8715 * Turn on the -x and -v options: set -xv
8716 * Unset all positional parameters: set --
8717 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8718 * Set the positional parameters to the expansion of x, even if x expands
8719 * with a leading '-' or '+': set -- $x
8720 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008721 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008722 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008723static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008724{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008725 int n;
8726 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008727 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008728
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008729 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008730 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008731 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008732 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008733 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008734 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008735
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008736 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008737 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008738 ++argv;
8739 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008740 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008741 if (arg[0] != '+' && arg[0] != '-')
8742 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008743 for (n = 1; arg[n]; ++n) {
8744 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008745 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008746 if (arg[n] == 'o' && argv[1])
8747 argv++;
8748 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008749 } while ((arg = *++argv) != NULL);
8750 /* Now argv[0] is 1st argument */
8751
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008752 if (arg == NULL)
8753 return EXIT_SUCCESS;
8754 set_argv:
8755
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008756 /* NB: G.global_argv[0] ($0) is never freed/changed */
8757 g_argv = G.global_argv;
8758 if (G.global_args_malloced) {
8759 pp = g_argv;
8760 while (*++pp)
8761 free(*pp);
8762 g_argv[1] = NULL;
8763 } else {
8764 G.global_args_malloced = 1;
8765 pp = xzalloc(sizeof(pp[0]) * 2);
8766 pp[0] = g_argv[0]; /* retain $0 */
8767 g_argv = pp;
8768 }
8769 /* This realloc's G.global_argv */
8770 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8771
8772 n = 1;
8773 while (*++pp)
8774 n++;
8775 G.global_argc = n;
8776
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008777 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008778
8779 /* Nothing known, so abort */
8780 error:
8781 bb_error_msg("set: %s: invalid option", arg);
8782 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008783}
8784
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008785static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008786{
8787 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008788 argv = skip_dash_dash(argv);
8789 if (argv[0]) {
8790 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008791 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008792 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008793 if (G.global_args_malloced) {
8794 int m = 1;
8795 while (m <= n)
8796 free(G.global_argv[m++]);
8797 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008798 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008799 memmove(&G.global_argv[1], &G.global_argv[n+1],
8800 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008801 return EXIT_SUCCESS;
8802 }
8803 return EXIT_FAILURE;
8804}
8805
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008806static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008807{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008808 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008809 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008810 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008811#if ENABLE_HUSH_FUNCTIONS
8812 smallint sv_flg;
8813#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008814
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008815 argv = skip_dash_dash(argv);
8816 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008817 if (!filename) {
8818 /* bash says: "bash: .: filename argument required" */
8819 return 2; /* bash compat */
8820 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008821 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008822 if (!strchr(filename, '/')) {
8823 arg_path = find_in_path(filename);
8824 if (arg_path)
8825 filename = arg_path;
8826 }
8827 input = fopen_or_warn(filename, "r");
8828 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008829 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008830 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008831 return EXIT_FAILURE;
8832 }
8833 close_on_exec_on(fileno(input));
8834
Mike Frysinger885b6f22009-04-18 21:04:25 +00008835#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008836 sv_flg = G.flag_return_in_progress;
8837 /* "we are inside sourced file, ok to use return" */
8838 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008839#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008840 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008841
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008842 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008843 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008844
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008845 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008846#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008847 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008848#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008849
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008850 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008851}
8852
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008853static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008854{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008855 int rc;
8856 mode_t mask;
8857
8858 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008859 argv = skip_dash_dash(argv);
8860 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008861 mode_t old_mask = mask;
8862
8863 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008864 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008865 mask ^= 0777;
8866 if (rc == 0) {
8867 mask = old_mask;
8868 /* bash messages:
8869 * bash: umask: 'q': invalid symbolic mode operator
8870 * bash: umask: 999: octal number out of range
8871 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008872 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008873 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008874 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008875 rc = 1;
8876 /* Mimic bash */
8877 printf("%04o\n", (unsigned) mask);
8878 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008879 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008880 umask(mask);
8881
8882 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008883}
8884
Mike Frysingerd690f682009-03-30 06:50:54 +00008885/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008886static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008887{
Mike Frysingerd690f682009-03-30 06:50:54 +00008888 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008889 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008890
Denis Vlasenko28e67962009-04-26 23:22:40 +00008891 /* "!": do not abort on errors */
8892 /* "+": stop at 1st non-option */
8893 opts = getopt32(argv, "!+vf");
8894 if (opts == (unsigned)-1)
8895 return EXIT_FAILURE;
8896 if (opts == 3) {
8897 bb_error_msg("unset: -v and -f are exclusive");
8898 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008899 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008900 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008901
8902 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008903 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008904 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008905 if (unset_local_var(*argv)) {
8906 /* unset <nonexistent_var> doesn't fail.
8907 * Error is when one tries to unset RO var.
8908 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008909 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008910 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008911 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008912#if ENABLE_HUSH_FUNCTIONS
8913 else {
8914 unset_func(*argv);
8915 }
8916#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008917 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008918 }
8919 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008920}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008921
Mike Frysinger56bdea12009-03-28 20:01:58 +00008922/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008923static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008924{
8925 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008926 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008927
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008928 argv = skip_dash_dash(argv);
8929 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008930 /* Don't care about wait results */
8931 /* Note 1: must wait until there are no more children */
8932 /* Note 2: must be interruptible */
8933 /* Examples:
8934 * $ sleep 3 & sleep 6 & wait
8935 * [1] 30934 sleep 3
8936 * [2] 30935 sleep 6
8937 * [1] Done sleep 3
8938 * [2] Done sleep 6
8939 * $ sleep 3 & sleep 6 & wait
8940 * [1] 30936 sleep 3
8941 * [2] 30937 sleep 6
8942 * [1] Done sleep 3
8943 * ^C <-- after ~4 sec from keyboard
8944 * $
8945 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008946 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008947 int sig;
8948 sigset_t oldset, allsigs;
8949
8950 /* waitpid is not interruptible by SA_RESTARTed
8951 * signals which we use. Thus, this ugly dance:
8952 */
8953
8954 /* Make sure possible SIGCHLD is stored in kernel's
8955 * pending signal mask before we call waitpid.
8956 * Or else we may race with SIGCHLD, lose it,
8957 * and get stuck in sigwaitinfo...
8958 */
8959 sigfillset(&allsigs);
8960 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
8961
8962 if (!sigisemptyset(&G.pending_set)) {
8963 /* Crap! we raced with some signal! */
8964 // sig = 0;
8965 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008966 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008967
8968 checkjobs(NULL); /* waitpid(WNOHANG) inside */
8969 if (errno == ECHILD) {
8970 sigprocmask(SIG_SETMASK, &oldset, NULL);
8971 break;
8972 }
8973
8974 /* Wait for SIGCHLD or any other signal */
8975 //sig = sigwaitinfo(&allsigs, NULL);
8976 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
8977 /* Note: sigsuspend invokes signal handler */
8978 sigsuspend(&oldset);
8979 restore:
8980 sigprocmask(SIG_SETMASK, &oldset, NULL);
8981
8982 /* So, did we get a signal? */
8983 //if (sig > 0)
8984 // raise(sig); /* run handler */
8985 sig = check_and_run_traps();
8986 if (sig /*&& sig != SIGCHLD - always true */) {
8987 /* see note 2 */
8988 ret = 128 + sig;
8989 break;
8990 }
8991 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008992 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008993 return ret;
8994 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008995
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008996 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008997 while (*argv) {
8998 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008999 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009000 /* mimic bash message */
9001 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009002 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009003 }
9004 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00009005 if (WIFSIGNALED(status))
9006 ret = 128 + WTERMSIG(status);
9007 else if (WIFEXITED(status))
9008 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00009009 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00009010 ret = EXIT_FAILURE;
9011 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009012 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009013 ret = 127;
9014 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00009015 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009016 }
9017
9018 return ret;
9019}
9020
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009021#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9022static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9023{
9024 if (argv[1]) {
9025 def = bb_strtou(argv[1], NULL, 10);
9026 if (errno || def < def_min || argv[2]) {
9027 bb_error_msg("%s: bad arguments", argv[0]);
9028 def = UINT_MAX;
9029 }
9030 }
9031 return def;
9032}
9033#endif
9034
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009035#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009036static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009037{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009038 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009039 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009040 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009041 return EXIT_SUCCESS; /* bash compat */
9042 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009043 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009044
9045 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9046 if (depth == UINT_MAX)
9047 G.flag_break_continue = BC_BREAK;
9048 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009049 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009050
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009051 return EXIT_SUCCESS;
9052}
9053
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009054static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009055{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009056 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9057 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009058}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009059#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009060
9061#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009062static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009063{
9064 int rc;
9065
9066 if (G.flag_return_in_progress != -1) {
9067 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9068 return EXIT_FAILURE; /* bash compat */
9069 }
9070
9071 G.flag_return_in_progress = 1;
9072
9073 /* bash:
9074 * out of range: wraps around at 256, does not error out
9075 * non-numeric param:
9076 * f() { false; return qwe; }; f; echo $?
9077 * bash: return: qwe: numeric argument required <== we do this
9078 * 255 <== we also do this
9079 */
9080 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9081 return rc;
9082}
9083#endif