blob: 7cebe1784922d418e46924549fb1e95f9944b472 [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 Vlasenko202a2d12010-07-16 12:36:14 +0200109//config:config HUSH
110//config: bool "hush"
111//config: default y
112//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200113//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200114//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
115//config: case/esac. Redirections, here documents, $((arithmetic))
116//config: and functions are supported.
117//config:
118//config: It will compile and work on no-mmu systems.
119//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +0200120//config: It does not handle select, aliases, tilde expansion,
121//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200122//config:
123//config:config HUSH_BASH_COMPAT
124//config: bool "bash-compatible extensions"
125//config: default y
126//config: depends on HUSH
127//config: help
128//config: Enable bash-compatible extensions.
129//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200130//config:config HUSH_BRACE_EXPANSION
131//config: bool "Brace expansion"
132//config: default y
133//config: depends on HUSH_BASH_COMPAT
134//config: help
135//config: Enable {abc,def} extension.
136//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config:config HUSH_HELP
138//config: bool "help builtin"
139//config: default y
140//config: depends on HUSH
141//config: help
142//config: Enable help builtin in hush. Code size + ~1 kbyte.
143//config:
144//config:config HUSH_INTERACTIVE
145//config: bool "Interactive mode"
146//config: default y
147//config: depends on HUSH
148//config: help
149//config: Enable interactive mode (prompt and command editing).
150//config: Without this, hush simply reads and executes commands
151//config: from stdin just like a shell script from a file.
152//config: No prompt, no PS1/PS2 magic shell variables.
153//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200154//config:config HUSH_SAVEHISTORY
155//config: bool "Save command history to .hush_history"
156//config: default y
157//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
158//config: help
159//config: Enable history saving in hush.
160//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200161//config:config HUSH_JOB
162//config: bool "Job control"
163//config: default y
164//config: depends on HUSH_INTERACTIVE
165//config: help
166//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
167//config: command (not entire shell), fg/bg builtins work. Without this option,
168//config: "cmd &" still works by simply spawning a process and immediately
169//config: prompting for next command (or executing next command in a script),
170//config: but no separate process group is formed.
171//config:
172//config:config HUSH_TICK
173//config: bool "Process substitution"
174//config: default y
175//config: depends on HUSH
176//config: help
177//config: Enable process substitution `command` and $(command) in hush.
178//config:
179//config:config HUSH_IF
180//config: bool "Support if/then/elif/else/fi"
181//config: default y
182//config: depends on HUSH
183//config: help
184//config: Enable if/then/elif/else/fi in hush.
185//config:
186//config:config HUSH_LOOPS
187//config: bool "Support for, while and until loops"
188//config: default y
189//config: depends on HUSH
190//config: help
191//config: Enable for, while and until loops in hush.
192//config:
193//config:config HUSH_CASE
194//config: bool "Support case ... esac statement"
195//config: default y
196//config: depends on HUSH
197//config: help
198//config: Enable case ... esac statement in hush. +400 bytes.
199//config:
200//config:config HUSH_FUNCTIONS
201//config: bool "Support funcname() { commands; } syntax"
202//config: default y
203//config: depends on HUSH
204//config: help
205//config: Enable support for shell functions in hush. +800 bytes.
206//config:
207//config:config HUSH_LOCAL
208//config: bool "Support local builtin"
209//config: default y
210//config: depends on HUSH_FUNCTIONS
211//config: help
212//config: Enable support for local variables in functions.
213//config:
214//config:config HUSH_RANDOM_SUPPORT
215//config: bool "Pseudorandom generator and $RANDOM variable"
216//config: default y
217//config: depends on HUSH
218//config: help
219//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
220//config: Each read of "$RANDOM" will generate a new pseudorandom value.
221//config:
222//config:config HUSH_EXPORT_N
223//config: bool "Support 'export -n' option"
224//config: default y
225//config: depends on HUSH
226//config: help
227//config: export -n unexports variables. It is a bash extension.
228//config:
229//config:config HUSH_MODE_X
230//config: bool "Support 'hush -x' option and 'set -x' command"
231//config: default y
232//config: depends on HUSH
233//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200234//config: This instructs hush to print commands before execution.
235//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200236//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200237//config:config MSH
238//config: bool "msh (deprecated: aliased to hush)"
239//config: default n
240//config: select HUSH
241//config: help
242//config: msh is deprecated and will be removed, please migrate to hush.
243//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200244
Denys Vlasenko20704f02011-03-23 17:59:27 +0100245//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
246//applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
247//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
248//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
249
250//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
251//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
252
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100253/* -i (interactive) and -s (read stdin) are also accepted,
254 * but currently do nothing, therefore aren't shown in help.
255 * NOMMU-specific options are not meant to be used by users,
256 * therefore we don't show them either.
257 */
258//usage:#define hush_trivial_usage
Denys Vlasenkof58f7052011-05-12 02:10:33 +0200259//usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100260//usage:#define hush_full_usage "\n\n"
261//usage: "Unix shell interpreter"
262
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100263//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100264//usage:#define msh_full_usage hush_full_usage
265
266//usage:#if ENABLE_FEATURE_SH_IS_HUSH
267//usage:# define sh_trivial_usage hush_trivial_usage
268//usage:# define sh_full_usage hush_full_usage
269//usage:#endif
270//usage:#if ENABLE_FEATURE_BASH_IS_HUSH
271//usage:# define bash_trivial_usage hush_trivial_usage
272//usage:# define bash_full_usage hush_full_usage
273//usage:#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200274
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000275
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200276/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000277#define LEAK_HUNTING 0
278#define BUILD_AS_NOMMU 0
279/* Enable/disable sanity checks. Ok to enable in production,
280 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
281 * Keeping 1 for now even in released versions.
282 */
283#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200284/* Slightly bigger (+200 bytes), but faster hush.
285 * So far it only enables a trick with counting SIGCHLDs and forks,
286 * which allows us to do fewer waitpid's.
287 * (we can detect a case where neither forks were done nor SIGCHLDs happened
288 * and therefore waitpid will return the same result as last time)
289 */
290#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200291/* TODO: implement simplified code for users which do not need ${var%...} ops
292 * So far ${var%...} ops are always enabled:
293 */
294#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000295
296
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000297#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000298# undef BB_MMU
299# undef USE_FOR_NOMMU
300# undef USE_FOR_MMU
301# define BB_MMU 0
302# define USE_FOR_NOMMU(...) __VA_ARGS__
303# define USE_FOR_MMU(...)
304#endif
305
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200306#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100307#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000308/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000309# undef CONFIG_FEATURE_SH_STANDALONE
310# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000311# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100312# undef IF_NOT_FEATURE_SH_STANDALONE
313# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000314# define IF_FEATURE_SH_STANDALONE(...)
315# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000316#endif
317
Denis Vlasenko05743d72008-02-10 12:10:08 +0000318#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000319# undef ENABLE_FEATURE_EDITING
320# define ENABLE_FEATURE_EDITING 0
321# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
322# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200323# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
324# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000325#endif
326
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000327/* Do we support ANY keywords? */
328#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000329# define HAS_KEYWORDS 1
330# define IF_HAS_KEYWORDS(...) __VA_ARGS__
331# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000332#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000333# define HAS_KEYWORDS 0
334# define IF_HAS_KEYWORDS(...)
335# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000336#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000337
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000338/* If you comment out one of these below, it will be #defined later
339 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000340#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000341/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000342#define debug_printf_parse(...) do {} while (0)
343#define debug_print_tree(a, b) do {} while (0)
344#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000345#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000346#define debug_printf_jobs(...) do {} while (0)
347#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200348#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000349#define debug_printf_glob(...) do {} while (0)
350#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000351#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000352#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000353
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000354#define ERR_PTR ((void*)(long)1)
355
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200356#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000357
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200358#define _SPECIAL_VARS_STR "_*@$!?#"
359#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
360#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200361#if ENABLE_HUSH_BASH_COMPAT
362/* Support / and // replace ops */
363/* Note that // is stored as \ in "encoded" string representation */
364# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
365# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
366# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
367#else
368# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
369# define VAR_SUBST_OPS "%#:-=+?"
370# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
371#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200372
373#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000374
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200375struct variable;
376
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000377static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
378
379/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000380 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000381 */
382#if !BB_MMU
383typedef struct nommu_save_t {
384 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200385 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000386 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000387 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000388} nommu_save_t;
389#endif
390
Denys Vlasenko9b782552010-09-08 13:33:26 +0200391enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000392 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000393#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000394 RES_IF ,
395 RES_THEN ,
396 RES_ELIF ,
397 RES_ELSE ,
398 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000399#endif
400#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000401 RES_FOR ,
402 RES_WHILE ,
403 RES_UNTIL ,
404 RES_DO ,
405 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000406#endif
407#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000408 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000409#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000410#if ENABLE_HUSH_CASE
411 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200412 /* three pseudo-keywords support contrived "case" syntax: */
413 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
414 RES_MATCH , /* "word)" */
415 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000416 RES_ESAC ,
417#endif
418 RES_XXXX ,
419 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200420};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000421
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000422typedef struct o_string {
423 char *data;
424 int length; /* position where data is appended */
425 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200426 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000427 /* At least some part of the string was inside '' or "",
428 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200429 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000430 smallint has_empty_slot;
431 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
432} o_string;
433enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200434 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
435 EXP_FLAG_GLOB = 0x2,
436 /* Protect newly added chars against globbing
437 * by prepending \ to *, ?, [, \ */
438 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
439};
440enum {
441 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000442 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200443 NOT_ASSIGNMENT = 2,
444 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
445 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000446};
447/* Used for initialization: o_string foo = NULL_O_STRING; */
448#define NULL_O_STRING { NULL }
449
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200450#ifndef debug_printf_parse
451static const char *const assignment_flag[] = {
452 "MAYBE_ASSIGNMENT",
453 "DEFINITELY_ASSIGNMENT",
454 "NOT_ASSIGNMENT",
455 "WORD_IS_KEYWORD",
456};
457#endif
458
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000459typedef struct in_str {
460 const char *p;
461 /* eof_flag=1: last char in ->p is really an EOF */
462 char eof_flag; /* meaningless if ->p == NULL */
463 char peek_buf[2];
464#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000465 smallint promptmode; /* 0: PS1, 1: PS2 */
466#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200467 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000468 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200469 int (*get) (struct in_str *) FAST_FUNC;
470 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000471} in_str;
472#define i_getch(input) ((input)->get(input))
473#define i_peek(input) ((input)->peek(input))
474
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200475/* The descrip member of this structure is only used to make
476 * debugging output pretty */
477static const struct {
478 int mode;
479 signed char default_fd;
480 char descrip[3];
481} redir_table[] = {
482 { O_RDONLY, 0, "<" },
483 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
484 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
485 { O_CREAT|O_RDWR, 1, "<>" },
486 { O_RDONLY, 0, "<<" },
487/* Should not be needed. Bogus default_fd helps in debugging */
488/* { O_RDONLY, 77, "<<" }, */
489};
490
Eric Andersen25f27032001-04-26 23:22:31 +0000491struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000492 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000493 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000494 int rd_fd; /* fd to redirect */
495 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
496 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000497 smallint rd_type; /* (enum redir_type) */
498 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000499 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200500 * bit 0: do we need to trim leading tabs?
501 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000502 */
Eric Andersen25f27032001-04-26 23:22:31 +0000503};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000504typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200505 REDIRECT_INPUT = 0,
506 REDIRECT_OVERWRITE = 1,
507 REDIRECT_APPEND = 2,
508 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000509 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200510 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000511
512 REDIRFD_CLOSE = -3,
513 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000514 REDIRFD_TO_FILE = -1,
515 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000516
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000517 HEREDOC_SKIPTABS = 1,
518 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000519} redir_type;
520
Eric Andersen25f27032001-04-26 23:22:31 +0000521
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000522struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000523 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000524 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200525 smallint cmd_type; /* CMD_xxx */
526#define CMD_NORMAL 0
527#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200528#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200529/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200530# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000531#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200532#if ENABLE_HUSH_FUNCTIONS
533# define CMD_FUNCDEF 3
534#endif
535
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100536 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200537 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
538 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000539#if !BB_MMU
540 char *group_as_string;
541#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000542#if ENABLE_HUSH_FUNCTIONS
543 struct function *child_func;
544/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200545 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000546 * When we execute "f1() {a;}" cmd, we create new function and clear
547 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200548 * When we execute "f1() {b;}", we notice that f1 exists,
549 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000550 * we put those fields back into cmd->xxx
551 * (struct function has ->parent_cmd ptr to facilitate that).
552 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
553 * Without this trick, loop would execute a;b;b;b;...
554 * instead of correct sequence a;b;a;b;...
555 * When command is freed, it severs the link
556 * (sets ->child_func->parent_cmd to NULL).
557 */
558#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000559 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000560/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
561 * and on execution these are substituted with their values.
562 * Substitution can make _several_ words out of one argv[n]!
563 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000564 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000565 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000566 struct redir_struct *redirects; /* I/O redirections */
567};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000568/* Is there anything in this command at all? */
569#define IS_NULL_CMD(cmd) \
570 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
571
Eric Andersen25f27032001-04-26 23:22:31 +0000572struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000573 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000574 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000575 int alive_cmds; /* number of commands running (not exited) */
576 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000577#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000578 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000579 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000580 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000581#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000582 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000583 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000584 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
585 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000586};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000587typedef enum pipe_style {
588 PIPE_SEQ = 1,
589 PIPE_AND = 2,
590 PIPE_OR = 3,
591 PIPE_BG = 4,
592} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000593/* Is there anything in this pipe at all? */
594#define IS_NULL_PIPE(pi) \
595 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000596
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000597/* This holds pointers to the various results of parsing */
598struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000599 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000600 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000601 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000602 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000603 /* last command in pipe (being constructed right now) */
604 struct command *command;
605 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000606 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000607#if !BB_MMU
608 o_string as_string;
609#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000610#if HAS_KEYWORDS
611 smallint ctx_res_w;
612 smallint ctx_inverted; /* "! cmd | cmd" */
613#if ENABLE_HUSH_CASE
614 smallint ctx_dsemicolon; /* ";;" seen */
615#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000616 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
617 int old_flag;
618 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000619 * example: "if pipe1; pipe2; then pipe3; fi"
620 * when we see "if" or "then", we malloc and copy current context,
621 * and make ->stack point to it. then we parse pipeN.
622 * when closing "then" / fi" / whatever is found,
623 * we move list_head into ->stack->command->group,
624 * copy ->stack into current context, and delete ->stack.
625 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000626 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000627 struct parse_context *stack;
628#endif
629};
630
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000631/* On program start, environ points to initial environment.
632 * putenv adds new pointers into it, unsetenv removes them.
633 * Neither of these (de)allocates the strings.
634 * setenv allocates new strings in malloc space and does putenv,
635 * and thus setenv is unusable (leaky) for shell's purposes */
636#define setenv(...) setenv_is_leaky_dont_use()
637struct variable {
638 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000639 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200640#if ENABLE_HUSH_LOCAL
641 unsigned func_nest_level;
642#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000643 int max_len; /* if > 0, name is part of initial env; else name is malloced */
644 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000645 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000646};
647
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000648enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000649 BC_BREAK = 1,
650 BC_CONTINUE = 2,
651};
652
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000653#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000654struct function {
655 struct function *next;
656 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000657 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000658 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200659# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000660 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200661# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000662};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000663#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000664
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000665
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100666/* set -/+o OPT support. (TODO: make it optional)
667 * bash supports the following opts:
668 * allexport off
669 * braceexpand on
670 * emacs on
671 * errexit off
672 * errtrace off
673 * functrace off
674 * hashall on
675 * histexpand off
676 * history on
677 * ignoreeof off
678 * interactive-comments on
679 * keyword off
680 * monitor on
681 * noclobber off
682 * noexec off
683 * noglob off
684 * nolog off
685 * notify off
686 * nounset off
687 * onecmd off
688 * physical off
689 * pipefail off
690 * posix off
691 * privileged off
692 * verbose off
693 * vi off
694 * xtrace off
695 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800696static const char o_opt_strings[] ALIGN1 =
697 "pipefail\0"
698 "noexec\0"
699#if ENABLE_HUSH_MODE_X
700 "xtrace\0"
701#endif
702 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100703enum {
704 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800705 OPT_O_NOEXEC,
706#if ENABLE_HUSH_MODE_X
707 OPT_O_XTRACE,
708#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100709 NUM_OPT_O
710};
711
712
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000713/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000714/* Sorted roughly by size (smaller offsets == smaller code) */
715struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000716 /* interactive_fd != 0 means we are an interactive shell.
717 * If we are, then saved_tty_pgrp can also be != 0, meaning
718 * that controlling tty is available. With saved_tty_pgrp == 0,
719 * job control still works, but terminal signals
720 * (^C, ^Z, ^Y, ^\) won't work at all, and background
721 * process groups can only be created with "cmd &".
722 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
723 * to give tty to the foreground process group,
724 * and will take it back when the group is stopped (^Z)
725 * or killed (^C).
726 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000727#if ENABLE_HUSH_INTERACTIVE
728 /* 'interactive_fd' is a fd# open to ctty, if we have one
729 * _AND_ if we decided to act interactively */
730 int interactive_fd;
731 const char *PS1;
732 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000733# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000734#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000735# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000736#endif
737#if ENABLE_FEATURE_EDITING
738 line_input_t *line_input_state;
739#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000740 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200741 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000742 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200743#if ENABLE_HUSH_RANDOM_SUPPORT
744 random_t random_gen;
745#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000746#if ENABLE_HUSH_JOB
747 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000748 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000749 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000750 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400751# define G_saved_tty_pgrp (G.saved_tty_pgrp)
752#else
753# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000754#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100755 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100756#if ENABLE_HUSH_MODE_X
757# define G_x_mode (G.o_opt[OPT_O_XTRACE])
758#else
759# define G_x_mode 0
760#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000761 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000762#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000763 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000764#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000765#if ENABLE_HUSH_FUNCTIONS
766 /* 0: outside of a function (or sourced file)
767 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000768 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000769 */
770 smallint flag_return_in_progress;
771#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000772 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000773 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000774 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000775 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000776 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000777 /* how many non-NULL argv's we have. NB: $# + 1 */
778 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000779 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000780#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000781 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000782#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000783#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000784 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000785 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000786#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000787 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000788 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200789 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200790 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000791#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000792 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200793# if ENABLE_HUSH_LOCAL
794 struct variable **shadowed_vars_pp;
795 unsigned func_nest_level;
796# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000797#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000798 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200799#if ENABLE_HUSH_FAST
800 unsigned count_SIGCHLD;
801 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200802 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200803#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +0200804 /* Which signals have non-DFL handler (even with no traps set)?
805 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200806 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200807 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200808 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200809 * Other than these two times, never modified.
810 */
811 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200812#if ENABLE_HUSH_JOB
813 unsigned fatal_sig_mask;
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200814# define G_fatal_sig_mask G.fatal_sig_mask
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200815#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200816# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200817#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000818 char **traps; /* char *traps[NSIG] */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200819 sigset_t pending_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000820#if HUSH_DEBUG
821 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000822 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000823#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200824 struct sigaction sa;
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200825 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000826};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000827#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000828/* Not #defining name to G.name - this quickly gets unwieldy
829 * (too many defines). Also, I actually prefer to see when a variable
830 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000831#define INIT_G() do { \
832 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200833 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
834 sigfillset(&G.sa.sa_mask); \
835 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000836} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000837
838
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000839/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200840static int builtin_cd(char **argv) FAST_FUNC;
841static int builtin_echo(char **argv) FAST_FUNC;
842static int builtin_eval(char **argv) FAST_FUNC;
843static int builtin_exec(char **argv) FAST_FUNC;
844static int builtin_exit(char **argv) FAST_FUNC;
845static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000846#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200847static int builtin_fg_bg(char **argv) FAST_FUNC;
848static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000849#endif
850#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200851static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000852#endif
Flemming Madsend96ffda2013-04-07 18:47:24 +0200853#if MAX_HISTORY
854static int builtin_history(char **argv) FAST_FUNC;
855#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
Flemming Madsend96ffda2013-04-07 18:47:24 +0200925#if MAX_HISTORY
926 BLTIN("history" , builtin_history , "Show command history"),
927#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000928#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200929 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000930#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200931#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200932 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200933#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000934#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200935 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000936#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200937 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000938#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200939 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000940#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200941 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
942 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200943#if ENABLE_HUSH_BASH_COMPAT
944 BLTIN("source" , builtin_source , "Run commands in a file"),
945#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200946 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100947 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100948 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200949 BLTIN("umask" , builtin_umask , "Set file creation mask"),
950 BLTIN("unset" , builtin_unset , "Unset variables"),
951 BLTIN("wait" , builtin_wait , "Wait for process"),
952};
953/* For now, echo and test are unconditionally enabled.
954 * Maybe make it configurable? */
955static const struct built_in_command bltins2[] = {
956 BLTIN("[" , builtin_test , NULL),
957 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400958#if ENABLE_PRINTF
959 BLTIN("printf" , builtin_printf , NULL),
960#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200961 BLTIN("pwd" , builtin_pwd , NULL),
962 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000963};
964
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000965
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000966/* Debug printouts.
967 */
968#if HUSH_DEBUG
969/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100970# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000971# define debug_enter() (G.debug_indent++)
972# define debug_leave() (G.debug_indent--)
973#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200974# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000975# define debug_enter() ((void)0)
976# define debug_leave() ((void)0)
977#endif
978
979#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100980# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000981#endif
982
983#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100984# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000985#endif
986
987#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100988#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000989#endif
990
991#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100992# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000993#endif
994
995#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100996# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000997# define DEBUG_JOBS 1
998#else
999# define DEBUG_JOBS 0
1000#endif
1001
1002#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001003# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001004# define DEBUG_EXPAND 1
1005#else
1006# define DEBUG_EXPAND 0
1007#endif
1008
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001009#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001010# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001011#endif
1012
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001013#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001014# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001015# define DEBUG_GLOB 1
1016#else
1017# define DEBUG_GLOB 0
1018#endif
1019
1020#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001021# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001022#endif
1023
1024#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001025# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001026#endif
1027
1028#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001029# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001030# define DEBUG_CLEAN 1
1031#else
1032# define DEBUG_CLEAN 0
1033#endif
1034
1035#if DEBUG_EXPAND
1036static void debug_print_strings(const char *prefix, char **vv)
1037{
1038 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001039 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001040 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001041 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001042}
1043#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001044# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001045#endif
1046
1047
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001048/* Leak hunting. Use hush_leaktool.sh for post-processing.
1049 */
1050#if LEAK_HUNTING
1051static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001052{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001053 void *ptr = xmalloc((size + 0xff) & ~0xff);
1054 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1055 return ptr;
1056}
1057static void *xxrealloc(int lineno, void *ptr, size_t size)
1058{
1059 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1060 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1061 return ptr;
1062}
1063static char *xxstrdup(int lineno, const char *str)
1064{
1065 char *ptr = xstrdup(str);
1066 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1067 return ptr;
1068}
1069static void xxfree(void *ptr)
1070{
1071 fdprintf(2, "free %p\n", ptr);
1072 free(ptr);
1073}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001074# define xmalloc(s) xxmalloc(__LINE__, s)
1075# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1076# define xstrdup(s) xxstrdup(__LINE__, s)
1077# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001078#endif
1079
1080
1081/* Syntax and runtime errors. They always abort scripts.
1082 * In interactive use they usually discard unparsed and/or unexecuted commands
1083 * and return to the prompt.
1084 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1085 */
1086#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001087# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001088# define syntax_error(lineno, msg) syntax_error(msg)
1089# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1090# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1091# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1092# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001093#endif
1094
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001095static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001096{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001097 va_list p;
1098
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001099#if HUSH_DEBUG >= 2
1100 bb_error_msg("hush.c:%u", lineno);
1101#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001102 va_start(p, fmt);
1103 bb_verror_msg(fmt, p, NULL);
1104 va_end(p);
1105 if (!G_interactive_fd)
1106 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001107}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001108
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001109static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001110{
1111 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001112 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001113 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001114 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001115}
1116
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001117static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001118{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001119 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001120}
1121
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001122static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001123{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001124 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001125}
1126
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001127static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001128{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001129 char msg[2] = { ch, '\0' };
1130 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001131}
1132
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001133static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001134{
1135 char msg[2];
1136 msg[0] = ch;
1137 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001138 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001139}
1140
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001141#if HUSH_DEBUG < 2
1142# undef die_if_script
1143# undef syntax_error
1144# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001145# undef syntax_error_unterm_ch
1146# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001147# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001148#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001149# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001150# define syntax_error(msg) syntax_error(__LINE__, msg)
1151# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1152# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1153# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1154# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001155#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001156
Denis Vlasenko552433b2009-04-04 19:29:21 +00001157
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001158#if ENABLE_HUSH_INTERACTIVE
1159static void cmdedit_update_prompt(void);
1160#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001161# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001162#endif
1163
1164
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001165/* Utility functions
1166 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001167/* Replace each \x with x in place, return ptr past NUL. */
1168static char *unbackslash(char *src)
1169{
Denys Vlasenko71885402009-09-24 01:44:13 +02001170 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001171 while (1) {
1172 if (*src == '\\')
1173 src++;
1174 if ((*dst++ = *src++) == '\0')
1175 break;
1176 }
1177 return dst;
1178}
1179
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001180static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001181{
1182 int i;
1183 unsigned count1;
1184 unsigned count2;
1185 char **v;
1186
1187 v = strings;
1188 count1 = 0;
1189 if (v) {
1190 while (*v) {
1191 count1++;
1192 v++;
1193 }
1194 }
1195 count2 = 0;
1196 v = add;
1197 while (*v) {
1198 count2++;
1199 v++;
1200 }
1201 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1202 v[count1 + count2] = NULL;
1203 i = count2;
1204 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001205 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001206 return v;
1207}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001208#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001209static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1210{
1211 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1212 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1213 return ptr;
1214}
1215#define add_strings_to_strings(strings, add, need_to_dup) \
1216 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1217#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001218
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001219/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001220static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001221{
1222 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001223 v[0] = add;
1224 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001225 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001226}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001227#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001228static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1229{
1230 char **ptr = add_string_to_strings(strings, add);
1231 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1232 return ptr;
1233}
1234#define add_string_to_strings(strings, add) \
1235 xx_add_string_to_strings(__LINE__, strings, add)
1236#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001237
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001238static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001239{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001240 char **v;
1241
1242 if (!strings)
1243 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001244 v = strings;
1245 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001246 free(*v);
1247 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001248 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001249 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001250}
1251
Denis Vlasenko76d50412008-06-10 16:19:39 +00001252
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001253/* Helpers for setting new $n and restoring them back
1254 */
1255typedef struct save_arg_t {
1256 char *sv_argv0;
1257 char **sv_g_argv;
1258 int sv_g_argc;
1259 smallint sv_g_malloced;
1260} save_arg_t;
1261
1262static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1263{
1264 int n;
1265
1266 sv->sv_argv0 = argv[0];
1267 sv->sv_g_argv = G.global_argv;
1268 sv->sv_g_argc = G.global_argc;
1269 sv->sv_g_malloced = G.global_args_malloced;
1270
1271 argv[0] = G.global_argv[0]; /* retain $0 */
1272 G.global_argv = argv;
1273 G.global_args_malloced = 0;
1274
1275 n = 1;
1276 while (*++argv)
1277 n++;
1278 G.global_argc = n;
1279}
1280
1281static void restore_G_args(save_arg_t *sv, char **argv)
1282{
1283 char **pp;
1284
1285 if (G.global_args_malloced) {
1286 /* someone ran "set -- arg1 arg2 ...", undo */
1287 pp = G.global_argv;
1288 while (*++pp) /* note: does not free $0 */
1289 free(*pp);
1290 free(G.global_argv);
1291 }
1292 argv[0] = sv->sv_argv0;
1293 G.global_argv = sv->sv_g_argv;
1294 G.global_argc = sv->sv_g_argc;
1295 G.global_args_malloced = sv->sv_g_malloced;
1296}
1297
1298
Denis Vlasenkod5762932009-03-31 11:22:57 +00001299/* Basic theory of signal handling in shell
1300 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001301 * This does not describe what hush does, rather, it is current understanding
1302 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001303 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1304 *
1305 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1306 * is finished or backgrounded. It is the same in interactive and
1307 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001308 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001309 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001310 * backgrounds (i.e. stops) or kills all members of currently running
1311 * pipe.
1312 *
1313 * Wait builtin in interruptible by signals for which user trap is set
1314 * or by SIGINT in interactive shell.
1315 *
1316 * Trap handlers will execute even within trap handlers. (right?)
1317 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001318 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1319 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001320 *
1321 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001322 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001323 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001324 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001325 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001326 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001327 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001328 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001329 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001330 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001331 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001332 *
1333 * SIGQUIT: ignore
1334 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001335 * SIGHUP (interactive):
1336 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001337 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001338 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1339 * that all pipe members are stopped. Try this in bash:
1340 * while :; do :; done - ^Z does not background it
1341 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001342 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001343 * of the command line, show prompt. NB: ^C does not send SIGINT
1344 * to interactive shell while shell is waiting for a pipe,
1345 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001346 * Example 1: this waits 5 sec, but does not execute ls:
1347 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1348 * Example 2: this does not wait and does not execute ls:
1349 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1350 * Example 3: this does not wait 5 sec, but executes ls:
1351 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001352 * Example 4: this does not wait and does not execute ls:
1353 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001354 *
1355 * (What happens to signals which are IGN on shell start?)
1356 * (What happens with signal mask on shell start?)
1357 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001358 * Old implementation
1359 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001360 * We use in-kernel pending signal mask to determine which signals were sent.
1361 * We block all signals which we don't want to take action immediately,
1362 * i.e. we block all signals which need to have special handling as described
1363 * above, and all signals which have traps set.
1364 * After each pipe execution, we extract any pending signals via sigtimedwait()
1365 * and act on them.
1366 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001367 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001368 * sigset_t blocked_set: current blocked signal set
1369 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001370 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001371 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001372 * "trap 'cmd' SIGxxx":
1373 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001374 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001375 * unblock signals with special interactive handling
1376 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001377 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001378 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001379 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001380 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001381 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001382 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001383 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001384 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001385 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001386 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001387 * Standard says "When a subshell is entered, traps that are not being ignored
1388 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001389 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001390 *
1391 * Problem: the above approach makes it unwieldy to catch signals while
1392 * we are in read builtin, of while we read commands from stdin:
1393 * masked signals are not visible!
1394 *
1395 * New implementation
1396 * ==================
1397 * We record each signal we are interested in by installing signal handler
1398 * for them - a bit like emulating kernel pending signal mask in userspace.
1399 * We are interested in: signals which need to have special handling
1400 * as described above, and all signals which have traps set.
1401 * Signals are rocorded in pending_set.
1402 * After each pipe execution, we extract any pending signals
1403 * and act on them.
1404 *
1405 * unsigned special_sig_mask: a mask of shell-special signals.
1406 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1407 * char *traps[sig] if trap for sig is set (even if it's '').
1408 * sigset_t pending_set: set of sigs we received.
1409 *
1410 * "trap - SIGxxx":
1411 * if sig is in special_sig_mask, set handler back to:
1412 * record_pending_signo, or to IGN if it's a tty stop signal
1413 * if sig is in fatal_sig_mask, set handler back to sigexit.
1414 * else: set handler back to SIG_DFL
1415 * "trap 'cmd' SIGxxx":
1416 * set handler to record_pending_signo.
1417 * "trap '' SIGxxx":
1418 * set handler to SIG_IGN.
1419 * after [v]fork, if we plan to be a shell:
1420 * set signals with special interactive handling to SIG_DFL
1421 * (because child shell is not interactive),
1422 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1423 * after [v]fork, if we plan to exec:
1424 * POSIX says fork clears pending signal mask in child - no need to clear it.
1425 *
1426 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1427 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1428 *
1429 * Note (compat):
1430 * Standard says "When a subshell is entered, traps that are not being ignored
1431 * are set to the default actions". bash interprets it so that traps which
1432 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001433 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001434enum {
1435 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001436 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001437 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001438 | (1 << SIGHUP)
1439 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001440 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001441#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001442 | (1 << SIGTTIN)
1443 | (1 << SIGTTOU)
1444 | (1 << SIGTSTP)
1445#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001446 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001447};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001448
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001449static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001450{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001451 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001452#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001453 if (sig == SIGCHLD) {
1454 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001455//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 +02001456 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001457#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001458}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001459
Denys Vlasenko0806e402011-05-12 23:06:20 +02001460static sighandler_t install_sighandler(int sig, sighandler_t handler)
1461{
1462 struct sigaction old_sa;
1463
1464 /* We could use signal() to install handlers... almost:
1465 * except that we need to mask ALL signals while handlers run.
1466 * I saw signal nesting in strace, race window isn't small.
1467 * SA_RESTART is also needed, but in Linux, signal()
1468 * sets SA_RESTART too.
1469 */
1470 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1471 /* sigfillset(&G.sa.sa_mask); - already done */
1472 /* G.sa.sa_flags = SA_RESTART; - already done */
1473 G.sa.sa_handler = handler;
1474 sigaction(sig, &G.sa, &old_sa);
1475 return old_sa.sa_handler;
1476}
1477
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001478#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001479
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001480/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001481# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001482/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001483# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001484
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001485/* Restores tty foreground process group, and exits.
1486 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001487 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001488 * or called directly with -EXITCODE.
1489 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001490static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001491static void sigexit(int sig)
1492{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001493 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001494 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001495 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1496 /* Disable all signals: job control, SIGPIPE, etc.
1497 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1498 */
1499 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001500 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001501 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001502
1503 /* Not a signal, just exit */
1504 if (sig <= 0)
1505 _exit(- sig);
1506
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001507 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001508}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001509#else
1510
Denys Vlasenko8391c482010-05-22 17:50:43 +02001511# define disable_restore_tty_pgrp_on_exit() ((void)0)
1512# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001513
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001514#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001515
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001516static sighandler_t pick_sighandler(unsigned sig)
1517{
1518 sighandler_t handler = SIG_DFL;
1519 if (sig < sizeof(unsigned)*8) {
1520 unsigned sigmask = (1 << sig);
1521
1522#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001523 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001524 if (G_fatal_sig_mask & sigmask)
1525 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001526 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001527#endif
1528 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001529 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001530 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001531 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001532 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001533 * in an endless loop when we try to do some
1534 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001535 */
1536 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1537 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001538 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001539 }
1540 return handler;
1541}
1542
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001543/* Restores tty foreground process group, and exits. */
1544static void hush_exit(int exitcode) NORETURN;
1545static void hush_exit(int exitcode)
1546{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001547#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1548 save_history(G.line_input_state);
1549#endif
1550
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001551 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001552 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001553 char *argv[3];
1554 /* argv[0] is unused */
1555 argv[1] = G.traps[0];
1556 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001557 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001558 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001559 * "trap" will still show it, if executed
1560 * in the handler */
1561 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001562 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001563
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001564#if ENABLE_FEATURE_CLEAN_UP
1565 {
1566 struct variable *cur_var;
1567 if (G.cwd != bb_msg_unknown)
1568 free((char*)G.cwd);
1569 cur_var = G.top_var;
1570 while (cur_var) {
1571 struct variable *tmp = cur_var;
1572 if (!cur_var->max_len)
1573 free(cur_var->varstr);
1574 cur_var = cur_var->next;
1575 free(tmp);
1576 }
1577 }
1578#endif
1579
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001580#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001581 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001582 sigexit(- (exitcode & 0xff));
1583#else
1584 exit(exitcode);
1585#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001586}
1587
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001588
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001589//TODO: return a mask of ALL handled sigs?
1590static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001591{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001592 int last_sig = 0;
1593
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001594 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001595 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001596
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001597 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001598 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001599 sig = 0;
1600 do {
1601 sig++;
1602 if (sigismember(&G.pending_set, sig)) {
1603 sigdelset(&G.pending_set, sig);
1604 goto got_sig;
1605 }
1606 } while (sig < NSIG);
1607 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001608 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001609 if (G.traps && G.traps[sig]) {
1610 if (G.traps[sig][0]) {
1611 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001612 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001613 char *argv[3];
1614 /* argv[0] is unused */
1615 argv[1] = G.traps[sig];
1616 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001617 save_rcode = G.last_exitcode;
1618 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001619 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001620 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001621 } /* else: "" trap, ignoring signal */
1622 continue;
1623 }
1624 /* not a trap: special action */
1625 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001626 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001627 /* Builtin was ^C'ed, make it look prettier: */
1628 bb_putchar('\n');
1629 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001630 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001631 break;
1632#if ENABLE_HUSH_JOB
1633 case SIGHUP: {
1634 struct pipe *job;
1635 /* bash is observed to signal whole process groups,
1636 * not individual processes */
1637 for (job = G.job_list; job; job = job->next) {
1638 if (job->pgrp <= 0)
1639 continue;
1640 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1641 if (kill(- job->pgrp, SIGHUP) == 0)
1642 kill(- job->pgrp, SIGCONT);
1643 }
1644 sigexit(SIGHUP);
1645 }
1646#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001647#if ENABLE_HUSH_FAST
1648 case SIGCHLD:
1649 G.count_SIGCHLD++;
1650//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1651 /* Note:
1652 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1653 * This simplifies wait builtin a bit.
1654 */
1655 break;
1656#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001657 default: /* ignored: */
1658 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001659 /* Note:
1660 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1661 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001662 * in interactive shell, because TERM is ignored.
1663 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001664 break;
1665 }
1666 }
1667 return last_sig;
1668}
1669
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001670
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001671static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001672{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001673 if (force || G.cwd == NULL) {
1674 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1675 * we must not try to free(bb_msg_unknown) */
1676 if (G.cwd == bb_msg_unknown)
1677 G.cwd = NULL;
1678 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1679 if (!G.cwd)
1680 G.cwd = bb_msg_unknown;
1681 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001682 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001683}
1684
Denis Vlasenko83506862007-11-23 13:11:42 +00001685
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001686/*
1687 * Shell and environment variable support
1688 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001689static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001690{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001691 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001692 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001693
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001694 pp = &G.top_var;
1695 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001696 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001697 return pp;
1698 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001699 }
1700 return NULL;
1701}
1702
Denys Vlasenko03dad222010-01-12 23:29:57 +01001703static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001704{
Denys Vlasenko29082232010-07-16 13:52:32 +02001705 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001706 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001707
1708 if (G.expanded_assignments) {
1709 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001710 while (*cpp) {
1711 char *cp = *cpp;
1712 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1713 return cp + len + 1;
1714 cpp++;
1715 }
1716 }
1717
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001718 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001719 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001720 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001721
Denys Vlasenkodea47882009-10-09 15:40:49 +02001722 if (strcmp(name, "PPID") == 0)
1723 return utoa(G.root_ppid);
1724 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001725#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001726 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001727 return utoa(next_random(&G.random_gen));
1728#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001729 return NULL;
1730}
1731
1732/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001733 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001734 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001735 * 0: do not change export flag
1736 * (if creating new variable, flag will be 0)
1737 * 1: set export flag and putenv the variable
1738 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001739 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001740 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001741#if !BB_MMU && ENABLE_HUSH_LOCAL
1742/* all params are used */
1743#elif BB_MMU && ENABLE_HUSH_LOCAL
1744#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1745 set_local_var(str, flg_export, local_lvl)
1746#elif BB_MMU && !ENABLE_HUSH_LOCAL
1747#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001748 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001749#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1750#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1751 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001752#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001753static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001754{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001755 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001756 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001757 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001758 int name_len;
1759
Denis Vlasenko950bd722009-04-21 11:23:56 +00001760 eq_sign = strchr(str, '=');
1761 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001762 free(str);
1763 return -1;
1764 }
1765
Denis Vlasenko950bd722009-04-21 11:23:56 +00001766 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001767 var_pp = &G.top_var;
1768 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001769 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001770 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001771 continue;
1772 }
1773 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001774 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001775#if !BB_MMU
1776 if (!flg_read_only)
1777#endif
1778 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001779 free(str);
1780 return -1;
1781 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001782 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001783 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1784 *eq_sign = '\0';
1785 unsetenv(str);
1786 *eq_sign = '=';
1787 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001788#if ENABLE_HUSH_LOCAL
1789 if (cur->func_nest_level < local_lvl) {
1790 /* New variable is declared as local,
1791 * and existing one is global, or local
1792 * from enclosing function.
1793 * Remove and save old one: */
1794 *var_pp = cur->next;
1795 cur->next = *G.shadowed_vars_pp;
1796 *G.shadowed_vars_pp = cur;
1797 /* bash 3.2.33(1) and exported vars:
1798 * # export z=z
1799 * # f() { local z=a; env | grep ^z; }
1800 * # f
1801 * z=a
1802 * # env | grep ^z
1803 * z=z
1804 */
1805 if (cur->flg_export)
1806 flg_export = 1;
1807 break;
1808 }
1809#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001810 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001811 free_and_exp:
1812 free(str);
1813 goto exp;
1814 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001815 if (cur->max_len != 0) {
1816 if (cur->max_len >= strlen(str)) {
1817 /* This one is from startup env, reuse space */
1818 strcpy(cur->varstr, str);
1819 goto free_and_exp;
1820 }
1821 } else {
1822 /* max_len == 0 signifies "malloced" var, which we can
1823 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001824 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001825 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001826 cur->max_len = 0;
1827 goto set_str_and_exp;
1828 }
1829
Denys Vlasenko295fef82009-06-03 12:47:26 +02001830 /* Not found - create new variable struct */
1831 cur = xzalloc(sizeof(*cur));
1832#if ENABLE_HUSH_LOCAL
1833 cur->func_nest_level = local_lvl;
1834#endif
1835 cur->next = *var_pp;
1836 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001837
1838 set_str_and_exp:
1839 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001840#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001841 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001842#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001843 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001844 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001845 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001846 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1847 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001848 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001849 if (flg_export == -1) {
1850 cur->flg_export = 0;
1851 /* unsetenv was already done */
1852 } else {
1853 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1854 return putenv(cur->varstr);
1855 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001856 }
1857 return 0;
1858}
1859
Denys Vlasenko6db47842009-09-05 20:15:17 +02001860/* Used at startup and after each cd */
1861static void set_pwd_var(int exp)
1862{
1863 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1864 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1865}
1866
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001867static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001868{
1869 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001870 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001871
1872 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001873 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001874 var_pp = &G.top_var;
1875 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001876 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1877 if (cur->flg_read_only) {
1878 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001879 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001880 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001881 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001882 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1883 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001884 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1885 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001886 if (!cur->max_len)
1887 free(cur->varstr);
1888 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001889 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001890 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001891 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001892 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001893 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001894}
1895
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001896static int unset_local_var(const char *name)
1897{
1898 return unset_local_var_len(name, strlen(name));
1899}
1900
1901static void unset_vars(char **strings)
1902{
1903 char **v;
1904
1905 if (!strings)
1906 return;
1907 v = strings;
1908 while (*v) {
1909 const char *eq = strchrnul(*v, '=');
1910 unset_local_var_len(*v, (int)(eq - *v));
1911 v++;
1912 }
1913 free(strings);
1914}
1915
Denys Vlasenko03dad222010-01-12 23:29:57 +01001916static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001917{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001918 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001919 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001920}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001921
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001922
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001923/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001924 * Helpers for "var1=val1 var2=val2 cmd" feature
1925 */
1926static void add_vars(struct variable *var)
1927{
1928 struct variable *next;
1929
1930 while (var) {
1931 next = var->next;
1932 var->next = G.top_var;
1933 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001934 if (var->flg_export) {
1935 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001936 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001937 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001938 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001939 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001940 var = next;
1941 }
1942}
1943
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001944static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001945{
1946 char **s;
1947 struct variable *old = NULL;
1948
1949 if (!strings)
1950 return old;
1951 s = strings;
1952 while (*s) {
1953 struct variable *var_p;
1954 struct variable **var_pp;
1955 char *eq;
1956
1957 eq = strchr(*s, '=');
1958 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001959 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001960 if (var_pp) {
1961 /* Remove variable from global linked list */
1962 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001963 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001964 *var_pp = var_p->next;
1965 /* Add it to returned list */
1966 var_p->next = old;
1967 old = var_p;
1968 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001969 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001970 }
1971 s++;
1972 }
1973 return old;
1974}
1975
1976
1977/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001978 * in_str support
1979 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001980static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001981{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001982 int ch = *i->p;
1983 if (ch != '\0') {
1984 i->p++;
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001985 i->last_char = ch;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001986 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001987 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001988 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001989}
1990
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001991static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001992{
1993 return *i->p;
1994}
1995
1996#if ENABLE_HUSH_INTERACTIVE
1997
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001998static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001999{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002000 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002001 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002002 if (G.PS1 == NULL)
2003 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002004 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002005 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002006 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002007 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002008 if (G.PS2 == NULL)
2009 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002010}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002011
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002012static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002013{
2014 const char *prompt_str;
2015 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002016 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2017 /* Set up the prompt */
2018 if (promptmode == 0) { /* PS1 */
2019 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002020 /* bash uses $PWD value, even if it is set by user.
2021 * It uses current dir only if PWD is unset.
2022 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002023 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002024 prompt_str = G.PS1;
2025 } else
2026 prompt_str = G.PS2;
2027 } else
2028 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002029 debug_printf("result '%s'\n", prompt_str);
2030 return prompt_str;
2031}
2032
2033static void get_user_input(struct in_str *i)
2034{
2035 int r;
2036 const char *prompt_str;
2037
2038 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002039# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002040 /* Enable command line editing only while a command line
2041 * is actually being read */
2042 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01002043 /* Unicode support should be activated even if LANG is set
2044 * _during_ shell execution, not only if it was set when
2045 * shell was started. Therefore, re-check LANG every time:
2046 */
2047 reinit_unicode(get_local_var_value("LANG"));
2048
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002049 G.flag_SIGINT = 0;
2050 /* buglet: SIGINT will not make new prompt to appear _at once_,
2051 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002052 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 +00002053 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002054 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002055 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002056 i->eof_flag = (r < 0);
2057 if (i->eof_flag) { /* EOF/error detected */
2058 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2059 G.user_input_buf[1] = '\0';
2060 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02002061# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002062 do {
2063 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002064 if (i->last_char == '\0' || i->last_char == '\n') {
2065 /* Why check_and_run_traps here? Try this interactively:
2066 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2067 * $ <[enter], repeatedly...>
2068 * Without check_and_run_traps, handler never runs.
2069 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002070 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002071 fputs(prompt_str, stdout);
2072 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002073 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002074 G.user_input_buf[0] = r = fgetc(i->file);
2075 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002076 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002077 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002078# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002079 i->p = G.user_input_buf;
2080}
2081
2082#endif /* INTERACTIVE */
2083
2084/* This is the magic location that prints prompts
2085 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002086static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002087{
2088 int ch;
2089
2090 /* If there is data waiting, eat it up */
2091 if (i->p && *i->p) {
2092#if ENABLE_HUSH_INTERACTIVE
2093 take_cached:
2094#endif
2095 ch = *i->p++;
2096 if (i->eof_flag && !*i->p)
2097 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002098 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002099 } else {
2100 /* need to double check i->file because we might be doing something
2101 * more complicated by now, like sourcing or substituting. */
2102#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002103 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002104 do {
2105 get_user_input(i);
2106 } while (!*i->p); /* need non-empty line */
2107 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002108 goto take_cached;
2109 }
2110#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00002111 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002112 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002113 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002114 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002115 return ch;
2116}
2117
Denis Vlasenko913a2012009-04-05 22:17:04 +00002118/* All callers guarantee this routine will never
2119 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002120 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002121static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002122{
2123 int ch;
2124 if (i->p && *i->p) {
2125 if (i->eof_flag && !i->p[1])
2126 return EOF;
2127 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002128 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002129 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002130 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002131 i->eof_flag = (ch == EOF);
2132 i->peek_buf[0] = ch;
2133 i->peek_buf[1] = '\0';
2134 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002135 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002136 return ch;
2137}
2138
2139static void setup_file_in_str(struct in_str *i, FILE *f)
2140{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002141 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002142 i->peek = file_peek;
2143 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002144 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002145 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002146 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002147}
2148
2149static void setup_string_in_str(struct in_str *i, const char *s)
2150{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002151 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002152 i->peek = static_peek;
2153 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002154 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002155 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002156 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002157}
2158
2159
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002160/*
2161 * o_string support
2162 */
2163#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002164
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002165static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002166{
2167 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002168 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002169 if (o->data)
2170 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002171}
2172
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002173static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002174{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002175 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002176 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002177}
2178
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002179static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2180{
2181 free(o->data);
2182}
2183
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002184static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002185{
2186 if (o->length + len > o->maxlen) {
2187 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2188 o->data = xrealloc(o->data, 1 + o->maxlen);
2189 }
2190}
2191
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002192static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002193{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002194 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2195 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002196 o->data[o->length] = ch;
2197 o->length++;
2198 o->data[o->length] = '\0';
2199}
2200
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002201static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002202{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002203 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002204 memcpy(&o->data[o->length], str, len);
2205 o->length += len;
2206 o->data[o->length] = '\0';
2207}
2208
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002209static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002210{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002211 o_addblock(o, str, strlen(str));
2212}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002213
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002214#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002215static void nommu_addchr(o_string *o, int ch)
2216{
2217 if (o)
2218 o_addchr(o, ch);
2219}
2220#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002221# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002222#endif
2223
2224static void o_addstr_with_NUL(o_string *o, const char *str)
2225{
2226 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002227}
2228
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002229/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002230 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002231 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2232 * Apparently, on unquoted $v bash still does globbing
2233 * ("v='*.txt'; echo $v" prints all .txt files),
2234 * but NOT brace expansion! Thus, there should be TWO independent
2235 * quoting mechanisms on $v expansion side: one protects
2236 * $v from brace expansion, and other additionally protects "$v" against globbing.
2237 * We have only second one.
2238 */
2239
Denys Vlasenko9e800222010-10-03 14:28:04 +02002240#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002241# define MAYBE_BRACES "{}"
2242#else
2243# define MAYBE_BRACES ""
2244#endif
2245
Eric Andersen25f27032001-04-26 23:22:31 +00002246/* My analysis of quoting semantics tells me that state information
2247 * is associated with a destination, not a source.
2248 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002249static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002250{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002251 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002252 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002253 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002254 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002255 o_grow_by(o, sz);
2256 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002257 o->data[o->length] = '\\';
2258 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002259 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002260 o->data[o->length] = ch;
2261 o->length++;
2262 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002263}
2264
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002265static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002266{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002267 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002268 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2269 && strchr("*?[\\" MAYBE_BRACES, ch)
2270 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002271 sz++;
2272 o->data[o->length] = '\\';
2273 o->length++;
2274 }
2275 o_grow_by(o, sz);
2276 o->data[o->length] = ch;
2277 o->length++;
2278 o->data[o->length] = '\0';
2279}
2280
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002281static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002282{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002283 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002284 char ch;
2285 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002286 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002287 if (ordinary_cnt > len) /* paranoia */
2288 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002289 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002290 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002291 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002292 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002293 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002294
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002295 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002296 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002297 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002298 sz++;
2299 o->data[o->length] = '\\';
2300 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002301 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002302 o_grow_by(o, sz);
2303 o->data[o->length] = ch;
2304 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002305 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002306 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002307}
2308
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002309static void o_addQblock(o_string *o, const char *str, int len)
2310{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002311 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002312 o_addblock(o, str, len);
2313 return;
2314 }
2315 o_addqblock(o, str, len);
2316}
2317
Denys Vlasenko38292b62010-09-05 14:49:40 +02002318static void o_addQstr(o_string *o, const char *str)
2319{
2320 o_addQblock(o, str, strlen(str));
2321}
2322
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002323/* A special kind of o_string for $VAR and `cmd` expansion.
2324 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002325 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002326 * list[i] contains an INDEX (int!) into this string data.
2327 * It means that if list[] needs to grow, data needs to be moved higher up
2328 * but list[i]'s need not be modified.
2329 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002330 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002331 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2332 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002333#if DEBUG_EXPAND || DEBUG_GLOB
2334static void debug_print_list(const char *prefix, o_string *o, int n)
2335{
2336 char **list = (char**)o->data;
2337 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2338 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002339
2340 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002341 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 +02002342 prefix, list, n, string_start, o->length, o->maxlen,
2343 !!(o->o_expflags & EXP_FLAG_GLOB),
2344 o->has_quoted_part,
2345 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002346 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002347 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002348 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2349 o->data + (int)(uintptr_t)list[i] + string_start,
2350 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002351 i++;
2352 }
2353 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002354 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002355 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002356 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002357 }
2358}
2359#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002360# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002361#endif
2362
2363/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2364 * in list[n] so that it points past last stored byte so far.
2365 * It returns n+1. */
2366static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002367{
2368 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002369 int string_start;
2370 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002371
2372 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002373 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2374 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002375 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002376 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002377 /* list[n] points to string_start, make space for 16 more pointers */
2378 o->maxlen += 0x10 * sizeof(list[0]);
2379 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002380 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002381 memmove(list + n + 0x10, list + n, string_len);
2382 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002383 } else {
2384 debug_printf_list("list[%d]=%d string_start=%d\n",
2385 n, string_len, string_start);
2386 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002387 } else {
2388 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002389 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2390 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002391 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2392 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002393 o->has_empty_slot = 0;
2394 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002395 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002396 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002397 return n + 1;
2398}
2399
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002400/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002401static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002402{
2403 char **list = (char**)o->data;
2404 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2405
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002406 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002407}
2408
Denys Vlasenko9e800222010-10-03 14:28:04 +02002409#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002410/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2411 * first, it processes even {a} (no commas), second,
2412 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002413 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002414 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002415
2416/* Helper */
2417static int glob_needed(const char *s)
2418{
2419 while (*s) {
2420 if (*s == '\\') {
2421 if (!s[1])
2422 return 0;
2423 s += 2;
2424 continue;
2425 }
2426 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2427 return 1;
2428 s++;
2429 }
2430 return 0;
2431}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002432/* Return pointer to next closing brace or to comma */
2433static const char *next_brace_sub(const char *cp)
2434{
2435 unsigned depth = 0;
2436 cp++;
2437 while (*cp != '\0') {
2438 if (*cp == '\\') {
2439 if (*++cp == '\0')
2440 break;
2441 cp++;
2442 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002443 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002444 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002445 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002446 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002447 depth++;
2448 }
2449
2450 return *cp != '\0' ? cp : NULL;
2451}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002452/* Recursive brace globber. Note: may garble pattern[]. */
2453static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002454{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002455 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002456 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002457 const char *next;
2458 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002459 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002460 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002461
2462 debug_printf_glob("glob_brace('%s')\n", pattern);
2463
2464 begin = pattern;
2465 while (1) {
2466 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002467 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002468 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002469 /* Find the first sub-pattern and at the same time
2470 * find the rest after the closing brace */
2471 next = next_brace_sub(begin);
2472 if (next == NULL) {
2473 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002474 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002475 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002476 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002477 /* "{abc}" with no commas - illegal
2478 * brace expr, disregard and skip it */
2479 begin = next + 1;
2480 continue;
2481 }
2482 break;
2483 }
2484 if (*begin == '\\' && begin[1] != '\0')
2485 begin++;
2486 begin++;
2487 }
2488 debug_printf_glob("begin:%s\n", begin);
2489 debug_printf_glob("next:%s\n", next);
2490
2491 /* Now find the end of the whole brace expression */
2492 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002493 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002494 rest = next_brace_sub(rest);
2495 if (rest == NULL) {
2496 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002497 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002498 }
2499 debug_printf_glob("rest:%s\n", rest);
2500 }
2501 rest_len = strlen(++rest) + 1;
2502
2503 /* We are sure the brace expression is well-formed */
2504
2505 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002506 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002507
2508 /* We have a brace expression. BEGIN points to the opening {,
2509 * NEXT points past the terminator of the first element, and REST
2510 * points past the final }. We will accumulate result names from
2511 * recursive runs for each brace alternative in the buffer using
2512 * GLOB_APPEND. */
2513
2514 p = begin + 1;
2515 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002516 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002517 memcpy(
2518 mempcpy(
2519 mempcpy(new_pattern_buf,
2520 /* We know the prefix for all sub-patterns */
2521 pattern, begin - pattern),
2522 p, next - p),
2523 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002524
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002525 /* Note: glob_brace() may garble new_pattern_buf[].
2526 * That's why we re-copy prefix every time (1st memcpy above).
2527 */
2528 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002529 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002530 /* We saw the last entry */
2531 break;
2532 }
2533 p = next + 1;
2534 next = next_brace_sub(next);
2535 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002536 free(new_pattern_buf);
2537 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002538
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002539 simple_glob:
2540 {
2541 int gr;
2542 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002543
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002544 memset(&globdata, 0, sizeof(globdata));
2545 gr = glob(pattern, 0, NULL, &globdata);
2546 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2547 if (gr != 0) {
2548 if (gr == GLOB_NOMATCH) {
2549 globfree(&globdata);
2550 /* NB: garbles parameter */
2551 unbackslash(pattern);
2552 o_addstr_with_NUL(o, pattern);
2553 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2554 return o_save_ptr_helper(o, n);
2555 }
2556 if (gr == GLOB_NOSPACE)
2557 bb_error_msg_and_die(bb_msg_memory_exhausted);
2558 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2559 * but we didn't specify it. Paranoia again. */
2560 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2561 }
2562 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2563 char **argv = globdata.gl_pathv;
2564 while (1) {
2565 o_addstr_with_NUL(o, *argv);
2566 n = o_save_ptr_helper(o, n);
2567 argv++;
2568 if (!*argv)
2569 break;
2570 }
2571 }
2572 globfree(&globdata);
2573 }
2574 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002575}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002576/* Performs globbing on last list[],
2577 * saving each result as a new list[].
2578 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002579static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002580{
2581 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002582
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002583 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002584 if (!o->data)
2585 return o_save_ptr_helper(o, n);
2586 pattern = o->data + o_get_last_ptr(o, n);
2587 debug_printf_glob("glob pattern '%s'\n", pattern);
2588 if (!glob_needed(pattern)) {
2589 /* unbackslash last string in o in place, fix length */
2590 o->length = unbackslash(pattern) - o->data;
2591 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2592 return o_save_ptr_helper(o, n);
2593 }
2594
2595 copy = xstrdup(pattern);
2596 /* "forget" pattern in o */
2597 o->length = pattern - o->data;
2598 n = glob_brace(copy, o, n);
2599 free(copy);
2600 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002601 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002602 return n;
2603}
2604
Denys Vlasenko238081f2010-10-03 14:26:26 +02002605#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002606
2607/* Helper */
2608static int glob_needed(const char *s)
2609{
2610 while (*s) {
2611 if (*s == '\\') {
2612 if (!s[1])
2613 return 0;
2614 s += 2;
2615 continue;
2616 }
2617 if (*s == '*' || *s == '[' || *s == '?')
2618 return 1;
2619 s++;
2620 }
2621 return 0;
2622}
2623/* Performs globbing on last list[],
2624 * saving each result as a new list[].
2625 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002626static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002627{
2628 glob_t globdata;
2629 int gr;
2630 char *pattern;
2631
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002632 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002633 if (!o->data)
2634 return o_save_ptr_helper(o, n);
2635 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002636 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002637 if (!glob_needed(pattern)) {
2638 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002639 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002640 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002641 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002642 return o_save_ptr_helper(o, n);
2643 }
2644
2645 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002646 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2647 * If we glob "*.\*" and don't find anything, we need
2648 * to fall back to using literal "*.*", but GLOB_NOCHECK
2649 * will return "*.\*"!
2650 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002651 gr = glob(pattern, 0, NULL, &globdata);
2652 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002653 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002654 if (gr == GLOB_NOMATCH) {
2655 globfree(&globdata);
2656 goto literal;
2657 }
2658 if (gr == GLOB_NOSPACE)
2659 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002660 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2661 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002662 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002663 }
2664 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2665 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002666 /* "forget" pattern in o */
2667 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002668 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002669 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002670 n = o_save_ptr_helper(o, n);
2671 argv++;
2672 if (!*argv)
2673 break;
2674 }
2675 }
2676 globfree(&globdata);
2677 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002678 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002679 return n;
2680}
2681
Denys Vlasenko238081f2010-10-03 14:26:26 +02002682#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002683
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002684/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002685 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002686static int o_save_ptr(o_string *o, int n)
2687{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002688 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002689 /* If o->has_empty_slot, list[n] was already globbed
2690 * (if it was requested back then when it was filled)
2691 * so don't do that again! */
2692 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002693 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002694 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002695 return o_save_ptr_helper(o, n);
2696}
2697
2698/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002699static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002700{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002701 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002702 int string_start;
2703
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002704 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2705 if (DEBUG_EXPAND)
2706 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002707 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002708 list = (char**)o->data;
2709 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2710 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002711 while (n) {
2712 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002713 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002714 }
2715 return list;
2716}
2717
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002718static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002719
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002720/* Returns pi->next - next pipe in the list */
2721static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002722{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002723 struct pipe *next;
2724 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002725
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002726 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002727 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002728 struct command *command;
2729 struct redir_struct *r, *rnext;
2730
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002731 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002732 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002733 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002734 if (DEBUG_CLEAN) {
2735 int a;
2736 char **p;
2737 for (a = 0, p = command->argv; *p; a++, p++) {
2738 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2739 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002740 }
2741 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002742 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002743 }
2744 /* not "else if": on syntax error, we may have both! */
2745 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002746 debug_printf_clean(" begin group (cmd_type:%d)\n",
2747 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002748 free_pipe_list(command->group);
2749 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002750 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002751 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002752 /* else is crucial here.
2753 * If group != NULL, child_func is meaningless */
2754#if ENABLE_HUSH_FUNCTIONS
2755 else if (command->child_func) {
2756 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2757 command->child_func->parent_cmd = NULL;
2758 }
2759#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002760#if !BB_MMU
2761 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002762 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002763#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002764 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002765 debug_printf_clean(" redirect %d%s",
2766 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002767 /* guard against the case >$FOO, where foo is unset or blank */
2768 if (r->rd_filename) {
2769 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2770 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002771 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002772 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002773 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002774 rnext = r->next;
2775 free(r);
2776 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002777 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002778 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002779 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002780 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002781#if ENABLE_HUSH_JOB
2782 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002783 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002784#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002785
2786 next = pi->next;
2787 free(pi);
2788 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002789}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002790
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002791static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002792{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002793 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002794#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002795 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002796#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002797 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002798 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002799 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002800}
2801
2802
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002803/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002804
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002805#ifndef debug_print_tree
2806static void debug_print_tree(struct pipe *pi, int lvl)
2807{
2808 static const char *const PIPE[] = {
2809 [PIPE_SEQ] = "SEQ",
2810 [PIPE_AND] = "AND",
2811 [PIPE_OR ] = "OR" ,
2812 [PIPE_BG ] = "BG" ,
2813 };
2814 static const char *RES[] = {
2815 [RES_NONE ] = "NONE" ,
2816# if ENABLE_HUSH_IF
2817 [RES_IF ] = "IF" ,
2818 [RES_THEN ] = "THEN" ,
2819 [RES_ELIF ] = "ELIF" ,
2820 [RES_ELSE ] = "ELSE" ,
2821 [RES_FI ] = "FI" ,
2822# endif
2823# if ENABLE_HUSH_LOOPS
2824 [RES_FOR ] = "FOR" ,
2825 [RES_WHILE] = "WHILE",
2826 [RES_UNTIL] = "UNTIL",
2827 [RES_DO ] = "DO" ,
2828 [RES_DONE ] = "DONE" ,
2829# endif
2830# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2831 [RES_IN ] = "IN" ,
2832# endif
2833# if ENABLE_HUSH_CASE
2834 [RES_CASE ] = "CASE" ,
2835 [RES_CASE_IN ] = "CASE_IN" ,
2836 [RES_MATCH] = "MATCH",
2837 [RES_CASE_BODY] = "CASE_BODY",
2838 [RES_ESAC ] = "ESAC" ,
2839# endif
2840 [RES_XXXX ] = "XXXX" ,
2841 [RES_SNTX ] = "SNTX" ,
2842 };
2843 static const char *const CMDTYPE[] = {
2844 "{}",
2845 "()",
2846 "[noglob]",
2847# if ENABLE_HUSH_FUNCTIONS
2848 "func()",
2849# endif
2850 };
2851
2852 int pin, prn;
2853
2854 pin = 0;
2855 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002856 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002857 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2858 prn = 0;
2859 while (prn < pi->num_cmds) {
2860 struct command *command = &pi->cmds[prn];
2861 char **argv = command->argv;
2862
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002863 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002864 lvl*2, "", prn,
2865 command->assignment_cnt);
2866 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002867 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002868 CMDTYPE[command->cmd_type],
2869 argv
2870# if !BB_MMU
2871 , " group_as_string:", command->group_as_string
2872# else
2873 , "", ""
2874# endif
2875 );
2876 debug_print_tree(command->group, lvl+1);
2877 prn++;
2878 continue;
2879 }
2880 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002881 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002882 argv++;
2883 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002884 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002885 prn++;
2886 }
2887 pi = pi->next;
2888 pin++;
2889 }
2890}
2891#endif /* debug_print_tree */
2892
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002893static struct pipe *new_pipe(void)
2894{
Eric Andersen25f27032001-04-26 23:22:31 +00002895 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002896 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002897 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002898 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002899 return pi;
2900}
2901
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002902/* Command (member of a pipe) is complete, or we start a new pipe
2903 * if ctx->command is NULL.
2904 * No errors possible here.
2905 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002906static int done_command(struct parse_context *ctx)
2907{
2908 /* The command is really already in the pipe structure, so
2909 * advance the pipe counter and make a new, null command. */
2910 struct pipe *pi = ctx->pipe;
2911 struct command *command = ctx->command;
2912
2913 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002914 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002915 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002916 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002917 }
2918 pi->num_cmds++;
2919 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002920 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002921 } else {
2922 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2923 }
2924
2925 /* Only real trickiness here is that the uncommitted
2926 * command structure is not counted in pi->num_cmds. */
2927 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002928 ctx->command = command = &pi->cmds[pi->num_cmds];
2929 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002930 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002931 return pi->num_cmds; /* used only for 0/nonzero check */
2932}
2933
2934static void done_pipe(struct parse_context *ctx, pipe_style type)
2935{
2936 int not_null;
2937
2938 debug_printf_parse("done_pipe entered, followup %d\n", type);
2939 /* Close previous command */
2940 not_null = done_command(ctx);
2941 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002942#if HAS_KEYWORDS
2943 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2944 ctx->ctx_inverted = 0;
2945 ctx->pipe->res_word = ctx->ctx_res_w;
2946#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002947
2948 /* Without this check, even just <enter> on command line generates
2949 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002950 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002951 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002952#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002953 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002954#endif
2955#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002956 || ctx->ctx_res_w == RES_DONE
2957 || ctx->ctx_res_w == RES_FOR
2958 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002959#endif
2960#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002961 || ctx->ctx_res_w == RES_ESAC
2962#endif
2963 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002964 struct pipe *new_p;
2965 debug_printf_parse("done_pipe: adding new pipe: "
2966 "not_null:%d ctx->ctx_res_w:%d\n",
2967 not_null, ctx->ctx_res_w);
2968 new_p = new_pipe();
2969 ctx->pipe->next = new_p;
2970 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002971 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002972 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002973 * This is used to control execution.
2974 * RES_FOR and RES_IN are NOT sticky (needed to support
2975 * cases where variable or value happens to match a keyword):
2976 */
2977#if ENABLE_HUSH_LOOPS
2978 if (ctx->ctx_res_w == RES_FOR
2979 || ctx->ctx_res_w == RES_IN)
2980 ctx->ctx_res_w = RES_NONE;
2981#endif
2982#if ENABLE_HUSH_CASE
2983 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002984 ctx->ctx_res_w = RES_CASE_BODY;
2985 if (ctx->ctx_res_w == RES_CASE)
2986 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002987#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002988 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002989 /* Create the memory for command, roughly:
2990 * ctx->pipe->cmds = new struct command;
2991 * ctx->command = &ctx->pipe->cmds[0];
2992 */
2993 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002994 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002995 }
2996 debug_printf_parse("done_pipe return\n");
2997}
2998
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002999static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003000{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003001 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003002 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003003 /* Create the memory for command, roughly:
3004 * ctx->pipe->cmds = new struct command;
3005 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003006 */
3007 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003008}
3009
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003010/* If a reserved word is found and processed, parse context is modified
3011 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003012 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003013#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003014struct reserved_combo {
3015 char literal[6];
3016 unsigned char res;
3017 unsigned char assignment_flag;
3018 int flag;
3019};
3020enum {
3021 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003022# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003023 FLAG_IF = (1 << RES_IF ),
3024 FLAG_THEN = (1 << RES_THEN ),
3025 FLAG_ELIF = (1 << RES_ELIF ),
3026 FLAG_ELSE = (1 << RES_ELSE ),
3027 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003028# endif
3029# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003030 FLAG_FOR = (1 << RES_FOR ),
3031 FLAG_WHILE = (1 << RES_WHILE),
3032 FLAG_UNTIL = (1 << RES_UNTIL),
3033 FLAG_DO = (1 << RES_DO ),
3034 FLAG_DONE = (1 << RES_DONE ),
3035 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003036# endif
3037# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003038 FLAG_MATCH = (1 << RES_MATCH),
3039 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003040# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003041 FLAG_START = (1 << RES_XXXX ),
3042};
3043
3044static const struct reserved_combo* match_reserved_word(o_string *word)
3045{
Eric Andersen25f27032001-04-26 23:22:31 +00003046 /* Mostly a list of accepted follow-up reserved words.
3047 * FLAG_END means we are done with the sequence, and are ready
3048 * to turn the compound list into a command.
3049 * FLAG_START means the word must start a new compound list.
3050 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003051 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003052# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003053 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3054 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3055 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3056 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3057 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3058 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003059# endif
3060# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003061 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3062 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3063 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3064 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3065 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3066 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003067# endif
3068# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003069 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3070 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003071# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003072 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003073 const struct reserved_combo *r;
3074
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003075 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003076 if (strcmp(word->data, r->literal) == 0)
3077 return r;
3078 }
3079 return NULL;
3080}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003081/* Return 0: not a keyword, 1: keyword
3082 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003083static int reserved_word(o_string *word, struct parse_context *ctx)
3084{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003085# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003086 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003087 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003088 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003089# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003090 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003091
Denys Vlasenko38292b62010-09-05 14:49:40 +02003092 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003093 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003094 r = match_reserved_word(word);
3095 if (!r)
3096 return 0;
3097
3098 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003099# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003100 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3101 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003102 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003103 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003104# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003105 if (r->flag == 0) { /* '!' */
3106 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003107 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003108 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003109 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003110 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003111 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003112 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003113 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003114 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003115
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003116 old = xmalloc(sizeof(*old));
3117 debug_printf_parse("push stack %p\n", old);
3118 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003119 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003120 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003121 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003122 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003123 ctx->ctx_res_w = RES_SNTX;
3124 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003125 } else {
3126 /* "{...} fi" is ok. "{...} if" is not
3127 * Example:
3128 * if { echo foo; } then { echo bar; } fi */
3129 if (ctx->command->group)
3130 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003131 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003132
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003133 ctx->ctx_res_w = r->res;
3134 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003135 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003136 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003137
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003138 if (ctx->old_flag & FLAG_END) {
3139 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003140
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003141 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003142 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003143 old = ctx->stack;
3144 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003145 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003146# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003147 o_addstr(&old->as_string, ctx->as_string.data);
3148 o_free_unsafe(&ctx->as_string);
3149 old->command->group_as_string = xstrdup(old->as_string.data);
3150 debug_printf_parse("pop, remembering as:'%s'\n",
3151 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003152# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003153 *ctx = *old; /* physical copy */
3154 free(old);
3155 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003156 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003157}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003158#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003159
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003160/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003161 * Normal return is 0. Syntax errors return 1.
3162 * Note: on return, word is reset, but not o_free'd!
3163 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003164static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003165{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003166 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003167
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003168 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003169 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003170 debug_printf_parse("done_word return 0: true null, ignored\n");
3171 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003172 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003173
Eric Andersen25f27032001-04-26 23:22:31 +00003174 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003175 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3176 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003177 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3178 * "2.7 Redirection
3179 * ...the word that follows the redirection operator
3180 * shall be subjected to tilde expansion, parameter expansion,
3181 * command substitution, arithmetic expansion, and quote
3182 * removal. Pathname expansion shall not be performed
3183 * on the word by a non-interactive shell; an interactive
3184 * shell may perform it, but shall do so only when
3185 * the expansion would result in one word."
3186 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003187 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003188 /* Cater for >\file case:
3189 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3190 * Same with heredocs:
3191 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3192 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003193 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3194 unbackslash(ctx->pending_redirect->rd_filename);
3195 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003196 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003197 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3198 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003199 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003200 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003201 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003202 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003203#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003204# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003205 if (ctx->ctx_dsemicolon
3206 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3207 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003208 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003209 /* ctx->ctx_res_w = RES_MATCH; */
3210 ctx->ctx_dsemicolon = 0;
3211 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003212# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003213 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003214# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003215 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3216 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003217# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003218# if ENABLE_HUSH_CASE
3219 && ctx->ctx_res_w != RES_CASE
3220# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003221 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003222 int reserved = reserved_word(word, ctx);
3223 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3224 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003225 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003226 debug_printf_parse("done_word return %d\n",
3227 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003228 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003229 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003230# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003231 if (strcmp(word->data, "[[") == 0) {
3232 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3233 }
3234 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003235# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003236 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003237#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003238 if (command->group) {
3239 /* "{ echo foo; } echo bar" - bad */
3240 syntax_error_at(word->data);
3241 debug_printf_parse("done_word return 1: syntax error, "
3242 "groups and arglists don't mix\n");
3243 return 1;
3244 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003245
3246 /* If this word wasn't an assignment, next ones definitely
3247 * can't be assignments. Even if they look like ones. */
3248 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3249 && word->o_assignment != WORD_IS_KEYWORD
3250 ) {
3251 word->o_assignment = NOT_ASSIGNMENT;
3252 } else {
3253 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3254 command->assignment_cnt++;
3255 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3256 }
3257 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3258 word->o_assignment = MAYBE_ASSIGNMENT;
3259 }
3260 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3261
Denys Vlasenko38292b62010-09-05 14:49:40 +02003262 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003263 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3264 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003265 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003266 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003267 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003268 char *p = word->data;
3269 while (p[0] == SPECIAL_VAR_SYMBOL
3270 && (p[1] & 0x7f) == '@'
3271 && p[2] == SPECIAL_VAR_SYMBOL
3272 ) {
3273 p += 3;
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
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004228 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004229 ) {
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
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004381 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;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004518 if (next == '\'' && !ctx.pending_redirect) {
4519 insert_empty_quoted_str_marker:
4520 nommu_addchr(&ctx.as_string, next);
4521 i_getch(input); /* eat second ' */
4522 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4523 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4524 } else {
4525 while (1) {
4526 ch = i_getch(input);
4527 if (ch == EOF) {
4528 syntax_error_unterm_ch('\'');
4529 goto parse_error;
4530 }
4531 nommu_addchr(&ctx.as_string, ch);
4532 if (ch == '\'')
4533 break;
4534 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004535 }
Eric Andersen25f27032001-04-26 23:22:31 +00004536 }
Eric Andersen25f27032001-04-26 23:22:31 +00004537 break;
4538 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004539 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004540 if (next == '"' && !ctx.pending_redirect)
4541 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004542 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004543 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004544 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004545 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004546 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004547 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004548#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004549 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004550 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004551
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004552 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4553 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004554 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004555 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4556 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004557# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004558 o_addstr(&ctx.as_string, dest.data + pos);
4559 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004560# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004561 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4562 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004563 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004564 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004565#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004566 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004567#if ENABLE_HUSH_CASE
4568 case_semi:
4569#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004570 if (done_word(&dest, &ctx)) {
4571 goto parse_error;
4572 }
4573 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004574#if ENABLE_HUSH_CASE
4575 /* Eat multiple semicolons, detect
4576 * whether it means something special */
4577 while (1) {
4578 ch = i_peek(input);
4579 if (ch != ';')
4580 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004581 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004582 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004583 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004584 ctx.ctx_dsemicolon = 1;
4585 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004586 break;
4587 }
4588 }
4589#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004590 new_cmd:
4591 /* We just finished a cmd. New one may start
4592 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004593 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004594 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004595 break;
4596 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004597 if (done_word(&dest, &ctx)) {
4598 goto parse_error;
4599 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004600 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004601 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004602 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004603 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004604 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004605 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004606 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004607 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004608 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004609 if (done_word(&dest, &ctx)) {
4610 goto parse_error;
4611 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004612#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004613 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004614 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004615#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004616 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004617 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004618 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004619 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004620 } else {
4621 /* we could pick up a file descriptor choice here
4622 * with redirect_opt_num(), but bash doesn't do it.
4623 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004624 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004625#if !BB_MMU
4626 o_reset_to_empty_unquoted(&ctx.as_string);
4627#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004628 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004629 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004630 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004631#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004632 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004633 if (ctx.ctx_res_w == RES_MATCH
4634 && ctx.command->argv == NULL /* not (word|(... */
4635 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004636 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004637 ) {
4638 continue;
4639 }
4640#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004641 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004642 if (parse_group(&dest, &ctx, input, ch) != 0) {
4643 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004644 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004645 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004646 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004647#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004648 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004649 goto case_semi;
4650#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004651 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004652 /* proper use of this character is caught by end_trigger:
4653 * if we see {, we call parse_group(..., end_trigger='}')
4654 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004655 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004656 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004657 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004658 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004659 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004660 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004661 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004662
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004663 parse_error:
4664 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004665 struct parse_context *pctx;
4666 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004667
4668 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004669 * Sample for finding leaks on syntax error recovery path.
4670 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004671 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004672 * Samples to catch leaks at execution:
4673 * while if (true | {true;}); then echo ok; fi; do break; done
4674 * 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 +00004675 */
4676 pctx = &ctx;
4677 do {
4678 /* Update pipe/command counts,
4679 * otherwise freeing may miss some */
4680 done_pipe(pctx, PIPE_SEQ);
4681 debug_printf_clean("freeing list %p from ctx %p\n",
4682 pctx->list_head, pctx);
4683 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004684 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004685 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004686#if !BB_MMU
4687 o_free_unsafe(&pctx->as_string);
4688#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004689 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004690 if (pctx != &ctx) {
4691 free(pctx);
4692 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004693 IF_HAS_KEYWORDS(pctx = p2;)
4694 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004695
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004696 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004697 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004698#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004699 if (pstring)
4700 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004701#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004702 debug_leave();
4703 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004704 }
Eric Andersen25f27032001-04-26 23:22:31 +00004705}
4706
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004707
4708/*** Execution routines ***/
4709
4710/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004711#if !ENABLE_HUSH_BASH_COMPAT
4712/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4713#define expand_string_to_string(str, do_unbackslash) \
4714 expand_string_to_string(str)
4715#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004716static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004717#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004718static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004719#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004720
4721/* expand_strvec_to_strvec() takes a list of strings, expands
4722 * all variable references within and returns a pointer to
4723 * a list of expanded strings, possibly with larger number
4724 * of strings. (Think VAR="a b"; echo $VAR).
4725 * This new list is allocated as a single malloc block.
4726 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004727 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004728 * Caller can deallocate entire list by single free(list). */
4729
Denys Vlasenko238081f2010-10-03 14:26:26 +02004730/* A horde of its helpers come first: */
4731
4732static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4733{
4734 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004735 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004736
Denys Vlasenko9e800222010-10-03 14:28:04 +02004737#if ENABLE_HUSH_BRACE_EXPANSION
4738 if (c == '{' || c == '}') {
4739 /* { -> \{, } -> \} */
4740 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004741 /* And now we want to add { or } and continue:
4742 * o_addchr(o, c);
4743 * continue;
4744 * luckily, just falling throught achieves this.
4745 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004746 }
4747#endif
4748 o_addchr(o, c);
4749 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004750 /* \z -> \\\z; \<eol> -> \\<eol> */
4751 o_addchr(o, '\\');
4752 if (len) {
4753 len--;
4754 o_addchr(o, '\\');
4755 o_addchr(o, *str++);
4756 }
4757 }
4758 }
4759}
4760
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004761/* Store given string, finalizing the word and starting new one whenever
4762 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004763 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4764 * Return in *ended_with_ifs:
4765 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4766 */
4767static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004768{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004769 int last_is_ifs = 0;
4770
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004771 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004772 int word_len;
4773
4774 if (!*str) /* EOL - do not finalize word */
4775 break;
4776 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004777 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004778 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02004779 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004780 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004781 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004782 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004783 * Example: "v='\*'; echo b$v" prints "b\*"
4784 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004785 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004786 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004787 /*/ Why can't we do it easier? */
4788 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4789 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4790 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004791 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004792 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004793 if (!*str) /* EOL - do not finalize word */
4794 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004795 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004796
4797 /* We know str here points to at least one IFS char */
4798 last_is_ifs = 1;
4799 str += strspn(str, G.ifs); /* skip IFS chars */
4800 if (!*str) /* EOL - do not finalize word */
4801 break;
4802
4803 /* Start new word... but not always! */
4804 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004805 if (output->has_quoted_part
4806 /* Case "v=' a'; echo $v":
4807 * here nothing precedes the space in $v expansion,
4808 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004809 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004810 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004811 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004812 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004813 o_addchr(output, '\0');
4814 debug_print_list("expand_on_ifs", output, n);
4815 n = o_save_ptr(output, n);
4816 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004817 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004818
4819 if (ended_with_ifs)
4820 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004821 debug_print_list("expand_on_ifs[1]", output, n);
4822 return n;
4823}
4824
4825/* Helper to expand $((...)) and heredoc body. These act as if
4826 * they are in double quotes, with the exception that they are not :).
4827 * Just the rules are similar: "expand only $var and `cmd`"
4828 *
4829 * Returns malloced string.
4830 * As an optimization, we return NULL if expansion is not needed.
4831 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004832#if !ENABLE_HUSH_BASH_COMPAT
4833/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4834#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4835 encode_then_expand_string(str)
4836#endif
4837static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004838{
4839 char *exp_str;
4840 struct in_str input;
4841 o_string dest = NULL_O_STRING;
4842
4843 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004844 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004845#if ENABLE_HUSH_TICK
4846 && !strchr(str, '`')
4847#endif
4848 ) {
4849 return NULL;
4850 }
4851
4852 /* We need to expand. Example:
4853 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4854 */
4855 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004856 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004857//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004858 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004859 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004860 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4861 o_free_unsafe(&dest);
4862 return exp_str;
4863}
4864
4865#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004866static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004867{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004868 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004869 arith_t res;
4870 char *exp_str;
4871
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004872 math_state.lookupvar = get_local_var_value;
4873 math_state.setvar = set_local_var_from_halves;
4874 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004875 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004876 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004877 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004878 if (errmsg_p)
4879 *errmsg_p = math_state.errmsg;
4880 if (math_state.errmsg)
4881 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004882 return res;
4883}
4884#endif
4885
4886#if ENABLE_HUSH_BASH_COMPAT
4887/* ${var/[/]pattern[/repl]} helpers */
4888static char *strstr_pattern(char *val, const char *pattern, int *size)
4889{
4890 while (1) {
4891 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4892 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4893 if (end) {
4894 *size = end - val;
4895 return val;
4896 }
4897 if (*val == '\0')
4898 return NULL;
4899 /* Optimization: if "*pat" did not match the start of "string",
4900 * we know that "tring", "ring" etc will not match too:
4901 */
4902 if (pattern[0] == '*')
4903 return NULL;
4904 val++;
4905 }
4906}
4907static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4908{
4909 char *result = NULL;
4910 unsigned res_len = 0;
4911 unsigned repl_len = strlen(repl);
4912
4913 while (1) {
4914 int size;
4915 char *s = strstr_pattern(val, pattern, &size);
4916 if (!s)
4917 break;
4918
4919 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4920 memcpy(result + res_len, val, s - val);
4921 res_len += s - val;
4922 strcpy(result + res_len, repl);
4923 res_len += repl_len;
4924 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4925
4926 val = s + size;
4927 if (exp_op == '/')
4928 break;
4929 }
4930 if (val[0] && result) {
4931 result = xrealloc(result, res_len + strlen(val) + 1);
4932 strcpy(result + res_len, val);
4933 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4934 }
4935 debug_printf_varexp("result:'%s'\n", result);
4936 return result;
4937}
4938#endif
4939
4940/* Helper:
4941 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4942 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004943static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004944{
4945 const char *val = NULL;
4946 char *to_be_freed = NULL;
4947 char *p = *pp;
4948 char *var;
4949 char first_char;
4950 char exp_op;
4951 char exp_save = exp_save; /* for compiler */
4952 char *exp_saveptr; /* points to expansion operator */
4953 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004954 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004955
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004956 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004957 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004958 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004959 arg0 = arg[0];
4960 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004961 exp_op = 0;
4962
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004963 if (first_char == '#' /* ${#... */
4964 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4965 ) {
4966 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004967 var++;
4968 exp_op = 'L';
4969 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004970 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004971 if (exp_saveptr /* if 2nd char is one of expansion operators */
4972 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4973 ) {
4974 /* ${?:0}, ${#[:]%0} etc */
4975 exp_saveptr = var + 1;
4976 } else {
4977 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4978 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4979 }
4980 exp_op = exp_save = *exp_saveptr;
4981 if (exp_op) {
4982 exp_word = exp_saveptr + 1;
4983 if (exp_op == ':') {
4984 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004985//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004986 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004987 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004988 ) {
4989 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4990 exp_op = ':';
4991 exp_word--;
4992 }
4993 }
4994 *exp_saveptr = '\0';
4995 } /* else: it's not an expansion op, but bare ${var} */
4996 }
4997
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004998 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004999 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005000 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005001 int n = xatoi_positive(var);
5002 if (n < G.global_argc)
5003 val = G.global_argv[n];
5004 /* else val remains NULL: $N with too big N */
5005 } else {
5006 switch (var[0]) {
5007 case '$': /* pid */
5008 val = utoa(G.root_pid);
5009 break;
5010 case '!': /* bg pid */
5011 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5012 break;
5013 case '?': /* exitcode */
5014 val = utoa(G.last_exitcode);
5015 break;
5016 case '#': /* argc */
5017 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5018 break;
5019 default:
5020 val = get_local_var_value(var);
5021 }
5022 }
5023
5024 /* Handle any expansions */
5025 if (exp_op == 'L') {
5026 debug_printf_expand("expand: length(%s)=", val);
5027 val = utoa(val ? strlen(val) : 0);
5028 debug_printf_expand("%s\n", val);
5029 } else if (exp_op) {
5030 if (exp_op == '%' || exp_op == '#') {
5031 /* Standard-mandated substring removal ops:
5032 * ${parameter%word} - remove smallest suffix pattern
5033 * ${parameter%%word} - remove largest suffix pattern
5034 * ${parameter#word} - remove smallest prefix pattern
5035 * ${parameter##word} - remove largest prefix pattern
5036 *
5037 * Word is expanded to produce a glob pattern.
5038 * Then var's value is matched to it and matching part removed.
5039 */
5040 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005041 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005042 char *exp_exp_word;
5043 char *loc;
5044 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005045 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005046 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005047 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005048 if (exp_exp_word)
5049 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005050 /* HACK ALERT. We depend here on the fact that
5051 * G.global_argv and results of utoa and get_local_var_value
5052 * are actually in writable memory:
5053 * scan_and_match momentarily stores NULs there. */
5054 t = (char*)val;
5055 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005056 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005057 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005058 free(exp_exp_word);
5059 if (loc) { /* match was found */
5060 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005061 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005062 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005063 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005064 }
5065 }
5066 }
5067#if ENABLE_HUSH_BASH_COMPAT
5068 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005069 /* It's ${var/[/]pattern[/repl]} thing.
5070 * Note that in encoded form it has TWO parts:
5071 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005072 * and if // is used, it is encoded as \:
5073 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005074 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005075 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005076 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005077 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005078 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005079 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005080 * by the usual expansion rules:
5081 * >az; >bz;
5082 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5083 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5084 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5085 * v='a bz'; echo ${v/a*z/\z} prints "z"
5086 * (note that a*z _pattern_ is never globbed!)
5087 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005088 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005089 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005090 if (!pattern)
5091 pattern = xstrdup(exp_word);
5092 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5093 *p++ = SPECIAL_VAR_SYMBOL;
5094 exp_word = p;
5095 p = strchr(p, SPECIAL_VAR_SYMBOL);
5096 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005097 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005098 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5099 /* HACK ALERT. We depend here on the fact that
5100 * G.global_argv and results of utoa and get_local_var_value
5101 * are actually in writable memory:
5102 * replace_pattern momentarily stores NULs there. */
5103 t = (char*)val;
5104 to_be_freed = replace_pattern(t,
5105 pattern,
5106 (repl ? repl : exp_word),
5107 exp_op);
5108 if (to_be_freed) /* at least one replace happened */
5109 val = to_be_freed;
5110 free(pattern);
5111 free(repl);
5112 }
5113 }
5114#endif
5115 else if (exp_op == ':') {
5116#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5117 /* It's ${var:N[:M]} bashism.
5118 * Note that in encoded form it has TWO parts:
5119 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5120 */
5121 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005122 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005123
Denys Vlasenko063847d2010-09-15 13:33:02 +02005124 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5125 if (errmsg)
5126 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005127 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5128 *p++ = SPECIAL_VAR_SYMBOL;
5129 exp_word = p;
5130 p = strchr(p, SPECIAL_VAR_SYMBOL);
5131 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005132 len = expand_and_evaluate_arith(exp_word, &errmsg);
5133 if (errmsg)
5134 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005135 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005136 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005137 if (beg < 0) /* bash compat */
5138 beg = 0;
5139 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005140 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005141 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005142 val = NULL;
5143 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005144 /* Paranoia. What if user entered 9999999999999
5145 * which fits in arith_t but not int? */
5146 if (len >= INT_MAX)
5147 len = INT_MAX;
5148 val = to_be_freed = xstrndup(val + beg, len);
5149 }
5150 debug_printf_varexp("val:'%s'\n", val);
5151 } else
5152#endif
5153 {
5154 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005155 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005156 }
5157 } else { /* one of "-=+?" */
5158 /* Standard-mandated substitution ops:
5159 * ${var?word} - indicate error if unset
5160 * If var is unset, word (or a message indicating it is unset
5161 * if word is null) is written to standard error
5162 * and the shell exits with a non-zero exit status.
5163 * Otherwise, the value of var is substituted.
5164 * ${var-word} - use default value
5165 * If var is unset, word is substituted.
5166 * ${var=word} - assign and use default value
5167 * If var is unset, word is assigned to var.
5168 * In all cases, final value of var is substituted.
5169 * ${var+word} - use alternative value
5170 * If var is unset, null is substituted.
5171 * Otherwise, word is substituted.
5172 *
5173 * Word is subjected to tilde expansion, parameter expansion,
5174 * command substitution, and arithmetic expansion.
5175 * If word is not needed, it is not expanded.
5176 *
5177 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5178 * but also treat null var as if it is unset.
5179 */
5180 int use_word = (!val || ((exp_save == ':') && !val[0]));
5181 if (exp_op == '+')
5182 use_word = !use_word;
5183 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5184 (exp_save == ':') ? "true" : "false", use_word);
5185 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005186 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005187 if (to_be_freed)
5188 exp_word = to_be_freed;
5189 if (exp_op == '?') {
5190 /* mimic bash message */
5191 die_if_script("%s: %s",
5192 var,
5193 exp_word[0] ? exp_word : "parameter null or not set"
5194 );
5195//TODO: how interactive bash aborts expansion mid-command?
5196 } else {
5197 val = exp_word;
5198 }
5199
5200 if (exp_op == '=') {
5201 /* ${var=[word]} or ${var:=[word]} */
5202 if (isdigit(var[0]) || var[0] == '#') {
5203 /* mimic bash message */
5204 die_if_script("$%s: cannot assign in this way", var);
5205 val = NULL;
5206 } else {
5207 char *new_var = xasprintf("%s=%s", var, val);
5208 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5209 }
5210 }
5211 }
5212 } /* one of "-=+?" */
5213
5214 *exp_saveptr = exp_save;
5215 } /* if (exp_op) */
5216
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005217 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005218
5219 *pp = p;
5220 *to_be_freed_pp = to_be_freed;
5221 return val;
5222}
5223
5224/* Expand all variable references in given string, adding words to list[]
5225 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5226 * to be filled). This routine is extremely tricky: has to deal with
5227 * variables/parameters with whitespace, $* and $@, and constructs like
5228 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005229static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005230{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005231 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005232 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005233 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005234 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005235 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005236 char *p;
5237
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005238 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5239 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005240 debug_print_list("expand_vars_to_list", output, n);
5241 n = o_save_ptr(output, n);
5242 debug_print_list("expand_vars_to_list[0]", output, n);
5243
5244 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5245 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005246 char *to_be_freed = NULL;
5247 const char *val = NULL;
5248#if ENABLE_HUSH_TICK
5249 o_string subst_result = NULL_O_STRING;
5250#endif
5251#if ENABLE_SH_MATH_SUPPORT
5252 char arith_buf[sizeof(arith_t)*3 + 2];
5253#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005254
5255 if (ended_in_ifs) {
5256 o_addchr(output, '\0');
5257 n = o_save_ptr(output, n);
5258 ended_in_ifs = 0;
5259 }
5260
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005261 o_addblock(output, arg, p - arg);
5262 debug_print_list("expand_vars_to_list[1]", output, n);
5263 arg = ++p;
5264 p = strchr(p, SPECIAL_VAR_SYMBOL);
5265
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005266 /* Fetch special var name (if it is indeed one of them)
5267 * and quote bit, force the bit on if singleword expansion -
5268 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005269 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005270
5271 /* Is this variable quoted and thus expansion can't be null?
5272 * "$@" is special. Even if quoted, it can still
5273 * expand to nothing (not even an empty string),
5274 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005275 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005276 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005277
5278 switch (first_ch & 0x7f) {
5279 /* Highest bit in first_ch indicates that var is double-quoted */
5280 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005281 case '@': {
5282 int i;
5283 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005284 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005285 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005286 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005287 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005288 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005289 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005290 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5291 if (G.global_argv[i++][0] && G.global_argv[i]) {
5292 /* this argv[] is not empty and not last:
5293 * put terminating NUL, start new word */
5294 o_addchr(output, '\0');
5295 debug_print_list("expand_vars_to_list[2]", output, n);
5296 n = o_save_ptr(output, n);
5297 debug_print_list("expand_vars_to_list[3]", output, n);
5298 }
5299 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005300 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005301 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005302 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005303 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005304 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005305 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005306 while (1) {
5307 o_addQstr(output, G.global_argv[i]);
5308 if (++i >= G.global_argc)
5309 break;
5310 o_addchr(output, '\0');
5311 debug_print_list("expand_vars_to_list[4]", output, n);
5312 n = o_save_ptr(output, n);
5313 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005314 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005315 while (1) {
5316 o_addQstr(output, G.global_argv[i]);
5317 if (!G.global_argv[++i])
5318 break;
5319 if (G.ifs[0])
5320 o_addchr(output, G.ifs[0]);
5321 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005322 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005323 }
5324 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005325 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005326 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5327 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005328 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005329 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005330 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005331 break;
5332#if ENABLE_HUSH_TICK
5333 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005334 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005335 arg++;
5336 /* Can't just stuff it into output o_string,
5337 * expanded result may need to be globbed
5338 * and $IFS-splitted */
5339 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5340 G.last_exitcode = process_command_subs(&subst_result, arg);
5341 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5342 val = subst_result.data;
5343 goto store_val;
5344#endif
5345#if ENABLE_SH_MATH_SUPPORT
5346 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5347 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005348
5349 arg++; /* skip '+' */
5350 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5351 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005352 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005353 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5354 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005355 val = arith_buf;
5356 break;
5357 }
5358#endif
5359 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005360 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005361 IF_HUSH_TICK(store_val:)
5362 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005363 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5364 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005365 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005366 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005367 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005368 }
5369 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005370 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005371 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5372 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005373 }
5374 break;
5375
5376 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5377
5378 if (val && val[0]) {
5379 o_addQstr(output, val);
5380 }
5381 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005382
5383 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5384 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005385 if (*p != SPECIAL_VAR_SYMBOL)
5386 *p = SPECIAL_VAR_SYMBOL;
5387
5388#if ENABLE_HUSH_TICK
5389 o_free(&subst_result);
5390#endif
5391 arg = ++p;
5392 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5393
5394 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005395 if (ended_in_ifs) {
5396 o_addchr(output, '\0');
5397 n = o_save_ptr(output, n);
5398 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005399 debug_print_list("expand_vars_to_list[a]", output, n);
5400 /* this part is literal, and it was already pre-quoted
5401 * if needed (much earlier), do not use o_addQstr here! */
5402 o_addstr_with_NUL(output, arg);
5403 debug_print_list("expand_vars_to_list[b]", output, n);
5404 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005405 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005406 ) {
5407 n--;
5408 /* allow to reuse list[n] later without re-growth */
5409 output->has_empty_slot = 1;
5410 } else {
5411 o_addchr(output, '\0');
5412 }
5413
5414 return n;
5415}
5416
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005417static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005418{
5419 int n;
5420 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005421 o_string output = NULL_O_STRING;
5422
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005423 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005424
5425 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005426 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005427 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005428 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005429 }
5430 debug_print_list("expand_variables", &output, n);
5431
5432 /* output.data (malloced in one block) gets returned in "list" */
5433 list = o_finalize_list(&output, n);
5434 debug_print_strings("expand_variables[1]", list);
5435 return list;
5436}
5437
5438static char **expand_strvec_to_strvec(char **argv)
5439{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005440 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005441}
5442
5443#if ENABLE_HUSH_BASH_COMPAT
5444static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5445{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005446 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005447}
5448#endif
5449
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005450/* Used for expansion of right hand of assignments,
5451 * $((...)), heredocs, variable espansion parts.
5452 *
5453 * NB: should NOT do globbing!
5454 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5455 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005456static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005457{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005458#if !ENABLE_HUSH_BASH_COMPAT
5459 const int do_unbackslash = 1;
5460#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005461 char *argv[2], **list;
5462
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005463 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005464 /* This is generally an optimization, but it also
5465 * handles "", which otherwise trips over !list[0] check below.
5466 * (is this ever happens that we actually get str="" here?)
5467 */
5468 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5469 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005470 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005471 return xstrdup(str);
5472 }
5473
5474 argv[0] = (char*)str;
5475 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005476 list = expand_variables(argv, do_unbackslash
5477 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5478 : EXP_FLAG_SINGLEWORD
5479 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005480 if (HUSH_DEBUG)
5481 if (!list[0] || list[1])
5482 bb_error_msg_and_die("BUG in varexp2");
5483 /* actually, just move string 2*sizeof(char*) bytes back */
5484 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005485 if (do_unbackslash)
5486 unbackslash((char*)list);
5487 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005488 return (char*)list;
5489}
5490
5491/* Used for "eval" builtin */
5492static char* expand_strvec_to_string(char **argv)
5493{
5494 char **list;
5495
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005496 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005497 /* Convert all NULs to spaces */
5498 if (list[0]) {
5499 int n = 1;
5500 while (list[n]) {
5501 if (HUSH_DEBUG)
5502 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5503 bb_error_msg_and_die("BUG in varexp3");
5504 /* bash uses ' ' regardless of $IFS contents */
5505 list[n][-1] = ' ';
5506 n++;
5507 }
5508 }
5509 overlapping_strcpy((char*)list, list[0]);
5510 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5511 return (char*)list;
5512}
5513
5514static char **expand_assignments(char **argv, int count)
5515{
5516 int i;
5517 char **p;
5518
5519 G.expanded_assignments = p = NULL;
5520 /* Expand assignments into one string each */
5521 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005522 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005523 }
5524 G.expanded_assignments = NULL;
5525 return p;
5526}
5527
5528
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005529static void switch_off_special_sigs(unsigned mask)
5530{
5531 unsigned sig = 0;
5532 while ((mask >>= 1) != 0) {
5533 sig++;
5534 if (!(mask & 1))
5535 continue;
5536 if (G.traps) {
5537 if (G.traps[sig] && !G.traps[sig][0])
5538 /* trap is '', has to remain SIG_IGN */
5539 continue;
5540 free(G.traps[sig]);
5541 G.traps[sig] = NULL;
5542 }
5543 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005544 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005545 }
5546}
5547
Denys Vlasenkob347df92011-08-09 22:49:15 +02005548#if BB_MMU
5549/* never called */
5550void re_execute_shell(char ***to_free, const char *s,
5551 char *g_argv0, char **g_argv,
5552 char **builtin_argv) NORETURN;
5553
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005554static void reset_traps_to_defaults(void)
5555{
5556 /* This function is always called in a child shell
5557 * after fork (not vfork, NOMMU doesn't use this function).
5558 */
5559 unsigned sig;
5560 unsigned mask;
5561
5562 /* Child shells are not interactive.
5563 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5564 * Testcase: (while :; do :; done) + ^Z should background.
5565 * Same goes for SIGTERM, SIGHUP, SIGINT.
5566 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005567 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5568 if (!G.traps && !mask)
5569 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005570
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005571 /* Switch off special sigs */
5572 switch_off_special_sigs(mask);
5573#if ENABLE_HUSH_JOB
5574 G_fatal_sig_mask = 0;
5575#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005576 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005577 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5578 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005579
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005580 if (!G.traps)
5581 return;
5582
5583 /* Reset all sigs to default except ones with empty traps */
5584 for (sig = 0; sig < NSIG; sig++) {
5585 if (!G.traps[sig])
5586 continue; /* no trap: nothing to do */
5587 if (!G.traps[sig][0])
5588 continue; /* empty trap: has to remain SIG_IGN */
5589 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005590 free(G.traps[sig]);
5591 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005592 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005593 if (sig == 0)
5594 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005595 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005596 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005597}
5598
5599#else /* !BB_MMU */
5600
5601static void re_execute_shell(char ***to_free, const char *s,
5602 char *g_argv0, char **g_argv,
5603 char **builtin_argv) NORETURN;
5604static void re_execute_shell(char ***to_free, const char *s,
5605 char *g_argv0, char **g_argv,
5606 char **builtin_argv)
5607{
5608# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5609 /* delims + 2 * (number of bytes in printed hex numbers) */
5610 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5611 char *heredoc_argv[4];
5612 struct variable *cur;
5613# if ENABLE_HUSH_FUNCTIONS
5614 struct function *funcp;
5615# endif
5616 char **argv, **pp;
5617 unsigned cnt;
5618 unsigned long long empty_trap_mask;
5619
5620 if (!g_argv0) { /* heredoc */
5621 argv = heredoc_argv;
5622 argv[0] = (char *) G.argv0_for_re_execing;
5623 argv[1] = (char *) "-<";
5624 argv[2] = (char *) s;
5625 argv[3] = NULL;
5626 pp = &argv[3]; /* used as pointer to empty environment */
5627 goto do_exec;
5628 }
5629
5630 cnt = 0;
5631 pp = builtin_argv;
5632 if (pp) while (*pp++)
5633 cnt++;
5634
5635 empty_trap_mask = 0;
5636 if (G.traps) {
5637 int sig;
5638 for (sig = 1; sig < NSIG; sig++) {
5639 if (G.traps[sig] && !G.traps[sig][0])
5640 empty_trap_mask |= 1LL << sig;
5641 }
5642 }
5643
5644 sprintf(param_buf, NOMMU_HACK_FMT
5645 , (unsigned) G.root_pid
5646 , (unsigned) G.root_ppid
5647 , (unsigned) G.last_bg_pid
5648 , (unsigned) G.last_exitcode
5649 , cnt
5650 , empty_trap_mask
5651 IF_HUSH_LOOPS(, G.depth_of_loop)
5652 );
5653# undef NOMMU_HACK_FMT
5654 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5655 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5656 */
5657 cnt += 6;
5658 for (cur = G.top_var; cur; cur = cur->next) {
5659 if (!cur->flg_export || cur->flg_read_only)
5660 cnt += 2;
5661 }
5662# if ENABLE_HUSH_FUNCTIONS
5663 for (funcp = G.top_func; funcp; funcp = funcp->next)
5664 cnt += 3;
5665# endif
5666 pp = g_argv;
5667 while (*pp++)
5668 cnt++;
5669 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5670 *pp++ = (char *) G.argv0_for_re_execing;
5671 *pp++ = param_buf;
5672 for (cur = G.top_var; cur; cur = cur->next) {
5673 if (strcmp(cur->varstr, hush_version_str) == 0)
5674 continue;
5675 if (cur->flg_read_only) {
5676 *pp++ = (char *) "-R";
5677 *pp++ = cur->varstr;
5678 } else if (!cur->flg_export) {
5679 *pp++ = (char *) "-V";
5680 *pp++ = cur->varstr;
5681 }
5682 }
5683# if ENABLE_HUSH_FUNCTIONS
5684 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5685 *pp++ = (char *) "-F";
5686 *pp++ = funcp->name;
5687 *pp++ = funcp->body_as_string;
5688 }
5689# endif
5690 /* We can pass activated traps here. Say, -Tnn:trap_string
5691 *
5692 * However, POSIX says that subshells reset signals with traps
5693 * to SIG_DFL.
5694 * I tested bash-3.2 and it not only does that with true subshells
5695 * of the form ( list ), but with any forked children shells.
5696 * I set trap "echo W" WINCH; and then tried:
5697 *
5698 * { echo 1; sleep 20; echo 2; } &
5699 * while true; do echo 1; sleep 20; echo 2; break; done &
5700 * true | { echo 1; sleep 20; echo 2; } | cat
5701 *
5702 * In all these cases sending SIGWINCH to the child shell
5703 * did not run the trap. If I add trap "echo V" WINCH;
5704 * _inside_ group (just before echo 1), it works.
5705 *
5706 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005707 */
5708 *pp++ = (char *) "-c";
5709 *pp++ = (char *) s;
5710 if (builtin_argv) {
5711 while (*++builtin_argv)
5712 *pp++ = *builtin_argv;
5713 *pp++ = (char *) "";
5714 }
5715 *pp++ = g_argv0;
5716 while (*g_argv)
5717 *pp++ = *g_argv++;
5718 /* *pp = NULL; - is already there */
5719 pp = environ;
5720
5721 do_exec:
5722 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02005723 /* Don't propagate SIG_IGN to the child */
5724 if (SPECIAL_JOBSTOP_SIGS != 0)
5725 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005726 execve(bb_busybox_exec_path, argv, pp);
5727 /* Fallback. Useful for init=/bin/hush usage etc */
5728 if (argv[0][0] == '/')
5729 execve(argv[0], argv, pp);
5730 xfunc_error_retval = 127;
5731 bb_error_msg_and_die("can't re-execute the shell");
5732}
5733#endif /* !BB_MMU */
5734
5735
5736static int run_and_free_list(struct pipe *pi);
5737
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005738/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005739 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5740 * end_trigger controls how often we stop parsing
5741 * NUL: parse all, execute, return
5742 * ';': parse till ';' or newline, execute, repeat till EOF
5743 */
5744static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005745{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005746 /* Why we need empty flag?
5747 * An obscure corner case "false; ``; echo $?":
5748 * empty command in `` should still set $? to 0.
5749 * But we can't just set $? to 0 at the start,
5750 * this breaks "false; echo `echo $?`" case.
5751 */
5752 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005753 while (1) {
5754 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005755
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005756#if ENABLE_HUSH_INTERACTIVE
5757 if (end_trigger == ';')
5758 inp->promptmode = 0; /* PS1 */
5759#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005760 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005761 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5762 /* If we are in "big" script
5763 * (not in `cmd` or something similar)...
5764 */
5765 if (pipe_list == ERR_PTR && end_trigger == ';') {
5766 /* Discard cached input (rest of line) */
5767 int ch = inp->last_char;
5768 while (ch != EOF && ch != '\n') {
5769 //bb_error_msg("Discarded:'%c'", ch);
5770 ch = i_getch(inp);
5771 }
5772 /* Force prompt */
5773 inp->p = NULL;
5774 /* This stream isn't empty */
5775 empty = 0;
5776 continue;
5777 }
5778 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01005779 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005780 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005781 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005782 debug_print_tree(pipe_list, 0);
5783 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5784 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005785 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005786#if ENABLE_HUSH_FUNCTIONS
5787 if (G.flag_return_in_progress == 1)
5788 break;
5789#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005790 }
Eric Andersen25f27032001-04-26 23:22:31 +00005791}
5792
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005793static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005794{
5795 struct in_str input;
5796 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005797 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005798}
5799
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005800static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005801{
Eric Andersen25f27032001-04-26 23:22:31 +00005802 struct in_str input;
5803 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005804 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005805}
5806
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005807#if ENABLE_HUSH_TICK
5808static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5809{
5810 pid_t pid;
5811 int channel[2];
5812# if !BB_MMU
5813 char **to_free = NULL;
5814# endif
5815
5816 xpipe(channel);
5817 pid = BB_MMU ? xfork() : xvfork();
5818 if (pid == 0) { /* child */
5819 disable_restore_tty_pgrp_on_exit();
5820 /* Process substitution is not considered to be usual
5821 * 'command execution'.
5822 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5823 */
5824 bb_signals(0
5825 + (1 << SIGTSTP)
5826 + (1 << SIGTTIN)
5827 + (1 << SIGTTOU)
5828 , SIG_IGN);
5829 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5830 close(channel[0]); /* NB: close _first_, then move fd! */
5831 xmove_fd(channel[1], 1);
5832 /* Prevent it from trying to handle ctrl-z etc */
5833 IF_HUSH_JOB(G.run_list_level = 1;)
5834 /* Awful hack for `trap` or $(trap).
5835 *
5836 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5837 * contains an example where "trap" is executed in a subshell:
5838 *
5839 * save_traps=$(trap)
5840 * ...
5841 * eval "$save_traps"
5842 *
5843 * Standard does not say that "trap" in subshell shall print
5844 * parent shell's traps. It only says that its output
5845 * must have suitable form, but then, in the above example
5846 * (which is not supposed to be normative), it implies that.
5847 *
5848 * bash (and probably other shell) does implement it
5849 * (traps are reset to defaults, but "trap" still shows them),
5850 * but as a result, "trap" logic is hopelessly messed up:
5851 *
5852 * # trap
5853 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5854 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5855 * # true | trap <--- trap is in subshell - no output (ditto)
5856 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5857 * trap -- 'echo Ho' SIGWINCH
5858 * # echo `(trap)` <--- in subshell in subshell - output
5859 * trap -- 'echo Ho' SIGWINCH
5860 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5861 * trap -- 'echo Ho' SIGWINCH
5862 *
5863 * The rules when to forget and when to not forget traps
5864 * get really complex and nonsensical.
5865 *
5866 * Our solution: ONLY bare $(trap) or `trap` is special.
5867 */
5868 s = skip_whitespace(s);
5869 if (strncmp(s, "trap", 4) == 0
5870 && skip_whitespace(s + 4)[0] == '\0'
5871 ) {
5872 static const char *const argv[] = { NULL, NULL };
5873 builtin_trap((char**)argv);
5874 exit(0); /* not _exit() - we need to fflush */
5875 }
5876# if BB_MMU
5877 reset_traps_to_defaults();
5878 parse_and_run_string(s);
5879 _exit(G.last_exitcode);
5880# else
5881 /* We re-execute after vfork on NOMMU. This makes this script safe:
5882 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5883 * huge=`cat BIG` # was blocking here forever
5884 * echo OK
5885 */
5886 re_execute_shell(&to_free,
5887 s,
5888 G.global_argv[0],
5889 G.global_argv + 1,
5890 NULL);
5891# endif
5892 }
5893
5894 /* parent */
5895 *pid_p = pid;
5896# if ENABLE_HUSH_FAST
5897 G.count_SIGCHLD++;
5898//bb_error_msg("[%d] fork in generate_stream_from_string:"
5899// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5900// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5901# endif
5902 enable_restore_tty_pgrp_on_exit();
5903# if !BB_MMU
5904 free(to_free);
5905# endif
5906 close(channel[1]);
5907 close_on_exec_on(channel[0]);
5908 return xfdopen_for_read(channel[0]);
5909}
5910
5911/* Return code is exit status of the process that is run. */
5912static int process_command_subs(o_string *dest, const char *s)
5913{
5914 FILE *fp;
5915 struct in_str pipe_str;
5916 pid_t pid;
5917 int status, ch, eol_cnt;
5918
5919 fp = generate_stream_from_string(s, &pid);
5920
5921 /* Now send results of command back into original context */
5922 setup_file_in_str(&pipe_str, fp);
5923 eol_cnt = 0;
5924 while ((ch = i_getch(&pipe_str)) != EOF) {
5925 if (ch == '\n') {
5926 eol_cnt++;
5927 continue;
5928 }
5929 while (eol_cnt) {
5930 o_addchr(dest, '\n');
5931 eol_cnt--;
5932 }
5933 o_addQchr(dest, ch);
5934 }
5935
5936 debug_printf("done reading from `cmd` pipe, closing it\n");
5937 fclose(fp);
5938 /* We need to extract exitcode. Test case
5939 * "true; echo `sleep 1; false` $?"
5940 * should print 1 */
5941 safe_waitpid(pid, &status, 0);
5942 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5943 return WEXITSTATUS(status);
5944}
5945#endif /* ENABLE_HUSH_TICK */
5946
5947
5948static void setup_heredoc(struct redir_struct *redir)
5949{
5950 struct fd_pair pair;
5951 pid_t pid;
5952 int len, written;
5953 /* the _body_ of heredoc (misleading field name) */
5954 const char *heredoc = redir->rd_filename;
5955 char *expanded;
5956#if !BB_MMU
5957 char **to_free;
5958#endif
5959
5960 expanded = NULL;
5961 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005962 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005963 if (expanded)
5964 heredoc = expanded;
5965 }
5966 len = strlen(heredoc);
5967
5968 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5969 xpiped_pair(pair);
5970 xmove_fd(pair.rd, redir->rd_fd);
5971
5972 /* Try writing without forking. Newer kernels have
5973 * dynamically growing pipes. Must use non-blocking write! */
5974 ndelay_on(pair.wr);
5975 while (1) {
5976 written = write(pair.wr, heredoc, len);
5977 if (written <= 0)
5978 break;
5979 len -= written;
5980 if (len == 0) {
5981 close(pair.wr);
5982 free(expanded);
5983 return;
5984 }
5985 heredoc += written;
5986 }
5987 ndelay_off(pair.wr);
5988
5989 /* Okay, pipe buffer was not big enough */
5990 /* Note: we must not create a stray child (bastard? :)
5991 * for the unsuspecting parent process. Child creates a grandchild
5992 * and exits before parent execs the process which consumes heredoc
5993 * (that exec happens after we return from this function) */
5994#if !BB_MMU
5995 to_free = NULL;
5996#endif
5997 pid = xvfork();
5998 if (pid == 0) {
5999 /* child */
6000 disable_restore_tty_pgrp_on_exit();
6001 pid = BB_MMU ? xfork() : xvfork();
6002 if (pid != 0)
6003 _exit(0);
6004 /* grandchild */
6005 close(redir->rd_fd); /* read side of the pipe */
6006#if BB_MMU
6007 full_write(pair.wr, heredoc, len); /* may loop or block */
6008 _exit(0);
6009#else
6010 /* Delegate blocking writes to another process */
6011 xmove_fd(pair.wr, STDOUT_FILENO);
6012 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6013#endif
6014 }
6015 /* parent */
6016#if ENABLE_HUSH_FAST
6017 G.count_SIGCHLD++;
6018//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6019#endif
6020 enable_restore_tty_pgrp_on_exit();
6021#if !BB_MMU
6022 free(to_free);
6023#endif
6024 close(pair.wr);
6025 free(expanded);
6026 wait(NULL); /* wait till child has died */
6027}
6028
6029/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6030 * and stderr if they are redirected. */
6031static int setup_redirects(struct command *prog, int squirrel[])
6032{
6033 int openfd, mode;
6034 struct redir_struct *redir;
6035
6036 for (redir = prog->redirects; redir; redir = redir->next) {
6037 if (redir->rd_type == REDIRECT_HEREDOC2) {
6038 /* rd_fd<<HERE case */
6039 if (squirrel && redir->rd_fd < 3
6040 && squirrel[redir->rd_fd] < 0
6041 ) {
6042 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6043 }
6044 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6045 * of the heredoc */
6046 debug_printf_parse("set heredoc '%s'\n",
6047 redir->rd_filename);
6048 setup_heredoc(redir);
6049 continue;
6050 }
6051
6052 if (redir->rd_dup == REDIRFD_TO_FILE) {
6053 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6054 char *p;
6055 if (redir->rd_filename == NULL) {
6056 /* Something went wrong in the parse.
6057 * Pretend it didn't happen */
6058 bb_error_msg("bug in redirect parse");
6059 continue;
6060 }
6061 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006062 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006063 openfd = open_or_warn(p, mode);
6064 free(p);
6065 if (openfd < 0) {
6066 /* this could get lost if stderr has been redirected, but
6067 * bash and ash both lose it as well (though zsh doesn't!) */
6068//what the above comment tries to say?
6069 return 1;
6070 }
6071 } else {
6072 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6073 openfd = redir->rd_dup;
6074 }
6075
6076 if (openfd != redir->rd_fd) {
6077 if (squirrel && redir->rd_fd < 3
6078 && squirrel[redir->rd_fd] < 0
6079 ) {
6080 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6081 }
6082 if (openfd == REDIRFD_CLOSE) {
6083 /* "n>-" means "close me" */
6084 close(redir->rd_fd);
6085 } else {
6086 xdup2(openfd, redir->rd_fd);
6087 if (redir->rd_dup == REDIRFD_TO_FILE)
6088 close(openfd);
6089 }
6090 }
6091 }
6092 return 0;
6093}
6094
6095static void restore_redirects(int squirrel[])
6096{
6097 int i, fd;
6098 for (i = 0; i < 3; i++) {
6099 fd = squirrel[i];
6100 if (fd != -1) {
6101 /* We simply die on error */
6102 xmove_fd(fd, i);
6103 }
6104 }
6105}
6106
6107static char *find_in_path(const char *arg)
6108{
6109 char *ret = NULL;
6110 const char *PATH = get_local_var_value("PATH");
6111
6112 if (!PATH)
6113 return NULL;
6114
6115 while (1) {
6116 const char *end = strchrnul(PATH, ':');
6117 int sz = end - PATH; /* must be int! */
6118
6119 free(ret);
6120 if (sz != 0) {
6121 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6122 } else {
6123 /* We have xxx::yyyy in $PATH,
6124 * it means "use current dir" */
6125 ret = xstrdup(arg);
6126 }
6127 if (access(ret, F_OK) == 0)
6128 break;
6129
6130 if (*end == '\0') {
6131 free(ret);
6132 return NULL;
6133 }
6134 PATH = end + 1;
6135 }
6136
6137 return ret;
6138}
6139
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006140static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006141 const struct built_in_command *x,
6142 const struct built_in_command *end)
6143{
6144 while (x != end) {
6145 if (strcmp(name, x->b_cmd) != 0) {
6146 x++;
6147 continue;
6148 }
6149 debug_printf_exec("found builtin '%s'\n", name);
6150 return x;
6151 }
6152 return NULL;
6153}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006154static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006155{
6156 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6157}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006158static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006159{
6160 const struct built_in_command *x = find_builtin1(name);
6161 if (x)
6162 return x;
6163 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6164}
6165
6166#if ENABLE_HUSH_FUNCTIONS
6167static struct function **find_function_slot(const char *name)
6168{
6169 struct function **funcpp = &G.top_func;
6170 while (*funcpp) {
6171 if (strcmp(name, (*funcpp)->name) == 0) {
6172 break;
6173 }
6174 funcpp = &(*funcpp)->next;
6175 }
6176 return funcpp;
6177}
6178
6179static const struct function *find_function(const char *name)
6180{
6181 const struct function *funcp = *find_function_slot(name);
6182 if (funcp)
6183 debug_printf_exec("found function '%s'\n", name);
6184 return funcp;
6185}
6186
6187/* Note: takes ownership on name ptr */
6188static struct function *new_function(char *name)
6189{
6190 struct function **funcpp = find_function_slot(name);
6191 struct function *funcp = *funcpp;
6192
6193 if (funcp != NULL) {
6194 struct command *cmd = funcp->parent_cmd;
6195 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6196 if (!cmd) {
6197 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6198 free(funcp->name);
6199 /* Note: if !funcp->body, do not free body_as_string!
6200 * This is a special case of "-F name body" function:
6201 * body_as_string was not malloced! */
6202 if (funcp->body) {
6203 free_pipe_list(funcp->body);
6204# if !BB_MMU
6205 free(funcp->body_as_string);
6206# endif
6207 }
6208 } else {
6209 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6210 cmd->argv[0] = funcp->name;
6211 cmd->group = funcp->body;
6212# if !BB_MMU
6213 cmd->group_as_string = funcp->body_as_string;
6214# endif
6215 }
6216 } else {
6217 debug_printf_exec("remembering new function '%s'\n", name);
6218 funcp = *funcpp = xzalloc(sizeof(*funcp));
6219 /*funcp->next = NULL;*/
6220 }
6221
6222 funcp->name = name;
6223 return funcp;
6224}
6225
6226static void unset_func(const char *name)
6227{
6228 struct function **funcpp = find_function_slot(name);
6229 struct function *funcp = *funcpp;
6230
6231 if (funcp != NULL) {
6232 debug_printf_exec("freeing function '%s'\n", funcp->name);
6233 *funcpp = funcp->next;
6234 /* funcp is unlinked now, deleting it.
6235 * Note: if !funcp->body, the function was created by
6236 * "-F name body", do not free ->body_as_string
6237 * and ->name as they were not malloced. */
6238 if (funcp->body) {
6239 free_pipe_list(funcp->body);
6240 free(funcp->name);
6241# if !BB_MMU
6242 free(funcp->body_as_string);
6243# endif
6244 }
6245 free(funcp);
6246 }
6247}
6248
6249# if BB_MMU
6250#define exec_function(to_free, funcp, argv) \
6251 exec_function(funcp, argv)
6252# endif
6253static void exec_function(char ***to_free,
6254 const struct function *funcp,
6255 char **argv) NORETURN;
6256static void exec_function(char ***to_free,
6257 const struct function *funcp,
6258 char **argv)
6259{
6260# if BB_MMU
6261 int n = 1;
6262
6263 argv[0] = G.global_argv[0];
6264 G.global_argv = argv;
6265 while (*++argv)
6266 n++;
6267 G.global_argc = n;
6268 /* On MMU, funcp->body is always non-NULL */
6269 n = run_list(funcp->body);
6270 fflush_all();
6271 _exit(n);
6272# else
6273 re_execute_shell(to_free,
6274 funcp->body_as_string,
6275 G.global_argv[0],
6276 argv + 1,
6277 NULL);
6278# endif
6279}
6280
6281static int run_function(const struct function *funcp, char **argv)
6282{
6283 int rc;
6284 save_arg_t sv;
6285 smallint sv_flg;
6286
6287 save_and_replace_G_args(&sv, argv);
6288
6289 /* "we are in function, ok to use return" */
6290 sv_flg = G.flag_return_in_progress;
6291 G.flag_return_in_progress = -1;
6292# if ENABLE_HUSH_LOCAL
6293 G.func_nest_level++;
6294# endif
6295
6296 /* On MMU, funcp->body is always non-NULL */
6297# if !BB_MMU
6298 if (!funcp->body) {
6299 /* Function defined by -F */
6300 parse_and_run_string(funcp->body_as_string);
6301 rc = G.last_exitcode;
6302 } else
6303# endif
6304 {
6305 rc = run_list(funcp->body);
6306 }
6307
6308# if ENABLE_HUSH_LOCAL
6309 {
6310 struct variable *var;
6311 struct variable **var_pp;
6312
6313 var_pp = &G.top_var;
6314 while ((var = *var_pp) != NULL) {
6315 if (var->func_nest_level < G.func_nest_level) {
6316 var_pp = &var->next;
6317 continue;
6318 }
6319 /* Unexport */
6320 if (var->flg_export)
6321 bb_unsetenv(var->varstr);
6322 /* Remove from global list */
6323 *var_pp = var->next;
6324 /* Free */
6325 if (!var->max_len)
6326 free(var->varstr);
6327 free(var);
6328 }
6329 G.func_nest_level--;
6330 }
6331# endif
6332 G.flag_return_in_progress = sv_flg;
6333
6334 restore_G_args(&sv, argv);
6335
6336 return rc;
6337}
6338#endif /* ENABLE_HUSH_FUNCTIONS */
6339
6340
6341#if BB_MMU
6342#define exec_builtin(to_free, x, argv) \
6343 exec_builtin(x, argv)
6344#else
6345#define exec_builtin(to_free, x, argv) \
6346 exec_builtin(to_free, argv)
6347#endif
6348static void exec_builtin(char ***to_free,
6349 const struct built_in_command *x,
6350 char **argv) NORETURN;
6351static void exec_builtin(char ***to_free,
6352 const struct built_in_command *x,
6353 char **argv)
6354{
6355#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006356 int rcode;
6357 fflush_all();
6358 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006359 fflush_all();
6360 _exit(rcode);
6361#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006362 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006363 /* On NOMMU, we must never block!
6364 * Example: { sleep 99 | read line; } & echo Ok
6365 */
6366 re_execute_shell(to_free,
6367 argv[0],
6368 G.global_argv[0],
6369 G.global_argv + 1,
6370 argv);
6371#endif
6372}
6373
6374
6375static void execvp_or_die(char **argv) NORETURN;
6376static void execvp_or_die(char **argv)
6377{
6378 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006379 /* Don't propagate SIG_IGN to the child */
6380 if (SPECIAL_JOBSTOP_SIGS != 0)
6381 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006382 execvp(argv[0], argv);
6383 bb_perror_msg("can't execute '%s'", argv[0]);
6384 _exit(127); /* bash compat */
6385}
6386
6387#if ENABLE_HUSH_MODE_X
6388static void dump_cmd_in_x_mode(char **argv)
6389{
6390 if (G_x_mode && argv) {
6391 /* We want to output the line in one write op */
6392 char *buf, *p;
6393 int len;
6394 int n;
6395
6396 len = 3;
6397 n = 0;
6398 while (argv[n])
6399 len += strlen(argv[n++]) + 1;
6400 buf = xmalloc(len);
6401 buf[0] = '+';
6402 p = buf + 1;
6403 n = 0;
6404 while (argv[n])
6405 p += sprintf(p, " %s", argv[n++]);
6406 *p++ = '\n';
6407 *p = '\0';
6408 fputs(buf, stderr);
6409 free(buf);
6410 }
6411}
6412#else
6413# define dump_cmd_in_x_mode(argv) ((void)0)
6414#endif
6415
6416#if BB_MMU
6417#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6418 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6419#define pseudo_exec(nommu_save, command, argv_expanded) \
6420 pseudo_exec(command, argv_expanded)
6421#endif
6422
6423/* Called after [v]fork() in run_pipe, or from builtin_exec.
6424 * Never returns.
6425 * Don't exit() here. If you don't exec, use _exit instead.
6426 * The at_exit handlers apparently confuse the calling process,
6427 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6428static void pseudo_exec_argv(nommu_save_t *nommu_save,
6429 char **argv, int assignment_cnt,
6430 char **argv_expanded) NORETURN;
6431static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6432 char **argv, int assignment_cnt,
6433 char **argv_expanded)
6434{
6435 char **new_env;
6436
6437 new_env = expand_assignments(argv, assignment_cnt);
6438 dump_cmd_in_x_mode(new_env);
6439
6440 if (!argv[assignment_cnt]) {
6441 /* Case when we are here: ... | var=val | ...
6442 * (note that we do not exit early, i.e., do not optimize out
6443 * expand_assignments(): think about ... | var=`sleep 1` | ...
6444 */
6445 free_strings(new_env);
6446 _exit(EXIT_SUCCESS);
6447 }
6448
6449#if BB_MMU
6450 set_vars_and_save_old(new_env);
6451 free(new_env); /* optional */
6452 /* we can also destroy set_vars_and_save_old's return value,
6453 * to save memory */
6454#else
6455 nommu_save->new_env = new_env;
6456 nommu_save->old_vars = set_vars_and_save_old(new_env);
6457#endif
6458
6459 if (argv_expanded) {
6460 argv = argv_expanded;
6461 } else {
6462 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6463#if !BB_MMU
6464 nommu_save->argv = argv;
6465#endif
6466 }
6467 dump_cmd_in_x_mode(argv);
6468
6469#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6470 if (strchr(argv[0], '/') != NULL)
6471 goto skip;
6472#endif
6473
6474 /* Check if the command matches any of the builtins.
6475 * Depending on context, this might be redundant. But it's
6476 * easier to waste a few CPU cycles than it is to figure out
6477 * if this is one of those cases.
6478 */
6479 {
6480 /* On NOMMU, it is more expensive to re-execute shell
6481 * just in order to run echo or test builtin.
6482 * It's better to skip it here and run corresponding
6483 * non-builtin later. */
6484 const struct built_in_command *x;
6485 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6486 if (x) {
6487 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6488 }
6489 }
6490#if ENABLE_HUSH_FUNCTIONS
6491 /* Check if the command matches any functions */
6492 {
6493 const struct function *funcp = find_function(argv[0]);
6494 if (funcp) {
6495 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6496 }
6497 }
6498#endif
6499
6500#if ENABLE_FEATURE_SH_STANDALONE
6501 /* Check if the command matches any busybox applets */
6502 {
6503 int a = find_applet_by_name(argv[0]);
6504 if (a >= 0) {
6505# if BB_MMU /* see above why on NOMMU it is not allowed */
6506 if (APPLET_IS_NOEXEC(a)) {
6507 debug_printf_exec("running applet '%s'\n", argv[0]);
6508 run_applet_no_and_exit(a, argv);
6509 }
6510# endif
6511 /* Re-exec ourselves */
6512 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006513 /* Don't propagate SIG_IGN to the child */
6514 if (SPECIAL_JOBSTOP_SIGS != 0)
6515 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006516 execv(bb_busybox_exec_path, argv);
6517 /* If they called chroot or otherwise made the binary no longer
6518 * executable, fall through */
6519 }
6520 }
6521#endif
6522
6523#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6524 skip:
6525#endif
6526 execvp_or_die(argv);
6527}
6528
6529/* Called after [v]fork() in run_pipe
6530 */
6531static void pseudo_exec(nommu_save_t *nommu_save,
6532 struct command *command,
6533 char **argv_expanded) NORETURN;
6534static void pseudo_exec(nommu_save_t *nommu_save,
6535 struct command *command,
6536 char **argv_expanded)
6537{
6538 if (command->argv) {
6539 pseudo_exec_argv(nommu_save, command->argv,
6540 command->assignment_cnt, argv_expanded);
6541 }
6542
6543 if (command->group) {
6544 /* Cases when we are here:
6545 * ( list )
6546 * { list } &
6547 * ... | ( list ) | ...
6548 * ... | { list } | ...
6549 */
6550#if BB_MMU
6551 int rcode;
6552 debug_printf_exec("pseudo_exec: run_list\n");
6553 reset_traps_to_defaults();
6554 rcode = run_list(command->group);
6555 /* OK to leak memory by not calling free_pipe_list,
6556 * since this process is about to exit */
6557 _exit(rcode);
6558#else
6559 re_execute_shell(&nommu_save->argv_from_re_execing,
6560 command->group_as_string,
6561 G.global_argv[0],
6562 G.global_argv + 1,
6563 NULL);
6564#endif
6565 }
6566
6567 /* Case when we are here: ... | >file */
6568 debug_printf_exec("pseudo_exec'ed null command\n");
6569 _exit(EXIT_SUCCESS);
6570}
6571
6572#if ENABLE_HUSH_JOB
6573static const char *get_cmdtext(struct pipe *pi)
6574{
6575 char **argv;
6576 char *p;
6577 int len;
6578
6579 /* This is subtle. ->cmdtext is created only on first backgrounding.
6580 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6581 * On subsequent bg argv is trashed, but we won't use it */
6582 if (pi->cmdtext)
6583 return pi->cmdtext;
6584 argv = pi->cmds[0].argv;
6585 if (!argv || !argv[0]) {
6586 pi->cmdtext = xzalloc(1);
6587 return pi->cmdtext;
6588 }
6589
6590 len = 0;
6591 do {
6592 len += strlen(*argv) + 1;
6593 } while (*++argv);
6594 p = xmalloc(len);
6595 pi->cmdtext = p;
6596 argv = pi->cmds[0].argv;
6597 do {
6598 len = strlen(*argv);
6599 memcpy(p, *argv, len);
6600 p += len;
6601 *p++ = ' ';
6602 } while (*++argv);
6603 p[-1] = '\0';
6604 return pi->cmdtext;
6605}
6606
6607static void insert_bg_job(struct pipe *pi)
6608{
6609 struct pipe *job, **jobp;
6610 int i;
6611
6612 /* Linear search for the ID of the job to use */
6613 pi->jobid = 1;
6614 for (job = G.job_list; job; job = job->next)
6615 if (job->jobid >= pi->jobid)
6616 pi->jobid = job->jobid + 1;
6617
6618 /* Add job to the list of running jobs */
6619 jobp = &G.job_list;
6620 while ((job = *jobp) != NULL)
6621 jobp = &job->next;
6622 job = *jobp = xmalloc(sizeof(*job));
6623
6624 *job = *pi; /* physical copy */
6625 job->next = NULL;
6626 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6627 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6628 for (i = 0; i < pi->num_cmds; i++) {
6629 job->cmds[i].pid = pi->cmds[i].pid;
6630 /* all other fields are not used and stay zero */
6631 }
6632 job->cmdtext = xstrdup(get_cmdtext(pi));
6633
6634 if (G_interactive_fd)
6635 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6636 G.last_jobid = job->jobid;
6637}
6638
6639static void remove_bg_job(struct pipe *pi)
6640{
6641 struct pipe *prev_pipe;
6642
6643 if (pi == G.job_list) {
6644 G.job_list = pi->next;
6645 } else {
6646 prev_pipe = G.job_list;
6647 while (prev_pipe->next != pi)
6648 prev_pipe = prev_pipe->next;
6649 prev_pipe->next = pi->next;
6650 }
6651 if (G.job_list)
6652 G.last_jobid = G.job_list->jobid;
6653 else
6654 G.last_jobid = 0;
6655}
6656
6657/* Remove a backgrounded job */
6658static void delete_finished_bg_job(struct pipe *pi)
6659{
6660 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006661 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006662}
6663#endif /* JOB */
6664
6665/* Check to see if any processes have exited -- if they
6666 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006667static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006668{
6669 int attributes;
6670 int status;
6671#if ENABLE_HUSH_JOB
6672 struct pipe *pi;
6673#endif
6674 pid_t childpid;
6675 int rcode = 0;
6676
6677 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6678
6679 attributes = WUNTRACED;
6680 if (fg_pipe == NULL)
6681 attributes |= WNOHANG;
6682
6683 errno = 0;
6684#if ENABLE_HUSH_FAST
6685 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6686//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6687//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6688 /* There was neither fork nor SIGCHLD since last waitpid */
6689 /* Avoid doing waitpid syscall if possible */
6690 if (!G.we_have_children) {
6691 errno = ECHILD;
6692 return -1;
6693 }
6694 if (fg_pipe == NULL) { /* is WNOHANG set? */
6695 /* We have children, but they did not exit
6696 * or stop yet (we saw no SIGCHLD) */
6697 return 0;
6698 }
6699 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6700 }
6701#endif
6702
6703/* Do we do this right?
6704 * bash-3.00# sleep 20 | false
6705 * <ctrl-Z pressed>
6706 * [3]+ Stopped sleep 20 | false
6707 * bash-3.00# echo $?
6708 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6709 * [hush 1.14.0: yes we do it right]
6710 */
6711 wait_more:
6712 while (1) {
6713 int i;
6714 int dead;
6715
6716#if ENABLE_HUSH_FAST
6717 i = G.count_SIGCHLD;
6718#endif
6719 childpid = waitpid(-1, &status, attributes);
6720 if (childpid <= 0) {
6721 if (childpid && errno != ECHILD)
6722 bb_perror_msg("waitpid");
6723#if ENABLE_HUSH_FAST
6724 else { /* Until next SIGCHLD, waitpid's are useless */
6725 G.we_have_children = (childpid == 0);
6726 G.handled_SIGCHLD = i;
6727//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6728 }
6729#endif
6730 break;
6731 }
6732 dead = WIFEXITED(status) || WIFSIGNALED(status);
6733
6734#if DEBUG_JOBS
6735 if (WIFSTOPPED(status))
6736 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6737 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6738 if (WIFSIGNALED(status))
6739 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6740 childpid, WTERMSIG(status), WEXITSTATUS(status));
6741 if (WIFEXITED(status))
6742 debug_printf_jobs("pid %d exited, exitcode %d\n",
6743 childpid, WEXITSTATUS(status));
6744#endif
6745 /* Were we asked to wait for fg pipe? */
6746 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006747 i = fg_pipe->num_cmds;
6748 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006749 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6750 if (fg_pipe->cmds[i].pid != childpid)
6751 continue;
6752 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006753 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006754 fg_pipe->cmds[i].pid = 0;
6755 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006756 ex = WEXITSTATUS(status);
6757 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006758 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006759 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6760 */
6761 if (WIFSIGNALED(status)) {
6762 int sig = WTERMSIG(status);
6763 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006764 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6765 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6766 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006767 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6768 * Maybe we need to use sig | 128? */
6769 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006770 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006771 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006772 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006773 fg_pipe->stopped_cmds++;
6774 }
6775 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6776 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006777 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006778 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006779 i = fg_pipe->num_cmds;
6780 while (--i >= 0) {
6781 rcode = fg_pipe->cmds[i].cmd_exitcode;
6782 /* usually last process gives overall exitstatus,
6783 * but with "set -o pipefail", last *failed* process does */
6784 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6785 break;
6786 }
6787 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006788/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6789 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6790 * and "killall -STOP cat" */
6791 if (G_interactive_fd) {
6792#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006793 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006794 insert_bg_job(fg_pipe);
6795#endif
6796 return rcode;
6797 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006798 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006799 return rcode;
6800 }
6801 /* There are still running processes in the fg pipe */
6802 goto wait_more; /* do waitpid again */
6803 }
6804 /* it wasnt fg_pipe, look for process in bg pipes */
6805 }
6806
6807#if ENABLE_HUSH_JOB
6808 /* We asked to wait for bg or orphaned children */
6809 /* No need to remember exitcode in this case */
6810 for (pi = G.job_list; pi; pi = pi->next) {
6811 for (i = 0; i < pi->num_cmds; i++) {
6812 if (pi->cmds[i].pid == childpid)
6813 goto found_pi_and_prognum;
6814 }
6815 }
6816 /* Happens when shell is used as init process (init=/bin/sh) */
6817 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6818 continue; /* do waitpid again */
6819
6820 found_pi_and_prognum:
6821 if (dead) {
6822 /* child exited */
6823 pi->cmds[i].pid = 0;
6824 pi->alive_cmds--;
6825 if (!pi->alive_cmds) {
6826 if (G_interactive_fd)
6827 printf(JOB_STATUS_FORMAT, pi->jobid,
6828 "Done", pi->cmdtext);
6829 delete_finished_bg_job(pi);
6830 }
6831 } else {
6832 /* child stopped */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006833 pi->stopped_cmds++;
6834 }
6835#endif
6836 } /* while (waitpid succeeds)... */
6837
6838 return rcode;
6839}
6840
6841#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006842static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006843{
6844 pid_t p;
6845 int rcode = checkjobs(fg_pipe);
6846 if (G_saved_tty_pgrp) {
6847 /* Job finished, move the shell to the foreground */
6848 p = getpgrp(); /* our process group id */
6849 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6850 tcsetpgrp(G_interactive_fd, p);
6851 }
6852 return rcode;
6853}
6854#endif
6855
6856/* Start all the jobs, but don't wait for anything to finish.
6857 * See checkjobs().
6858 *
6859 * Return code is normally -1, when the caller has to wait for children
6860 * to finish to determine the exit status of the pipe. If the pipe
6861 * is a simple builtin command, however, the action is done by the
6862 * time run_pipe returns, and the exit code is provided as the
6863 * return value.
6864 *
6865 * Returns -1 only if started some children. IOW: we have to
6866 * mask out retvals of builtins etc with 0xff!
6867 *
6868 * The only case when we do not need to [v]fork is when the pipe
6869 * is single, non-backgrounded, non-subshell command. Examples:
6870 * cmd ; ... { list } ; ...
6871 * cmd && ... { list } && ...
6872 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006873 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006874 * or (if SH_STANDALONE) an applet, and we can run the { list }
6875 * with run_list. If it isn't one of these, we fork and exec cmd.
6876 *
6877 * Cases when we must fork:
6878 * non-single: cmd | cmd
6879 * backgrounded: cmd & { list } &
6880 * subshell: ( list ) [&]
6881 */
6882#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006883#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006884 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6885#endif
6886static int redirect_and_varexp_helper(char ***new_env_p,
6887 struct variable **old_vars_p,
6888 struct command *command,
6889 int squirrel[3],
6890 char **argv_expanded)
6891{
6892 /* setup_redirects acts on file descriptors, not FILEs.
6893 * This is perfect for work that comes after exec().
6894 * Is it really safe for inline use? Experimentally,
6895 * things seem to work. */
6896 int rcode = setup_redirects(command, squirrel);
6897 if (rcode == 0) {
6898 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6899 *new_env_p = new_env;
6900 dump_cmd_in_x_mode(new_env);
6901 dump_cmd_in_x_mode(argv_expanded);
6902 if (old_vars_p)
6903 *old_vars_p = set_vars_and_save_old(new_env);
6904 }
6905 return rcode;
6906}
6907static NOINLINE int run_pipe(struct pipe *pi)
6908{
6909 static const char *const null_ptr = NULL;
6910
6911 int cmd_no;
6912 int next_infd;
6913 struct command *command;
6914 char **argv_expanded;
6915 char **argv;
6916 /* it is not always needed, but we aim to smaller code */
6917 int squirrel[] = { -1, -1, -1 };
6918 int rcode;
6919
6920 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6921 debug_enter();
6922
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006923 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6924 * Result should be 3 lines: q w e, qwe, q w e
6925 */
6926 G.ifs = get_local_var_value("IFS");
6927 if (!G.ifs)
6928 G.ifs = defifs;
6929
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006930 IF_HUSH_JOB(pi->pgrp = -1;)
6931 pi->stopped_cmds = 0;
6932 command = &pi->cmds[0];
6933 argv_expanded = NULL;
6934
6935 if (pi->num_cmds != 1
6936 || pi->followup == PIPE_BG
6937 || command->cmd_type == CMD_SUBSHELL
6938 ) {
6939 goto must_fork;
6940 }
6941
6942 pi->alive_cmds = 1;
6943
6944 debug_printf_exec(": group:%p argv:'%s'\n",
6945 command->group, command->argv ? command->argv[0] : "NONE");
6946
6947 if (command->group) {
6948#if ENABLE_HUSH_FUNCTIONS
6949 if (command->cmd_type == CMD_FUNCDEF) {
6950 /* "executing" func () { list } */
6951 struct function *funcp;
6952
6953 funcp = new_function(command->argv[0]);
6954 /* funcp->name is already set to argv[0] */
6955 funcp->body = command->group;
6956# if !BB_MMU
6957 funcp->body_as_string = command->group_as_string;
6958 command->group_as_string = NULL;
6959# endif
6960 command->group = NULL;
6961 command->argv[0] = NULL;
6962 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6963 funcp->parent_cmd = command;
6964 command->child_func = funcp;
6965
6966 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6967 debug_leave();
6968 return EXIT_SUCCESS;
6969 }
6970#endif
6971 /* { list } */
6972 debug_printf("non-subshell group\n");
6973 rcode = 1; /* exitcode if redir failed */
6974 if (setup_redirects(command, squirrel) == 0) {
6975 debug_printf_exec(": run_list\n");
6976 rcode = run_list(command->group) & 0xff;
6977 }
6978 restore_redirects(squirrel);
6979 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6980 debug_leave();
6981 debug_printf_exec("run_pipe: return %d\n", rcode);
6982 return rcode;
6983 }
6984
6985 argv = command->argv ? command->argv : (char **) &null_ptr;
6986 {
6987 const struct built_in_command *x;
6988#if ENABLE_HUSH_FUNCTIONS
6989 const struct function *funcp;
6990#else
6991 enum { funcp = 0 };
6992#endif
6993 char **new_env = NULL;
6994 struct variable *old_vars = NULL;
6995
6996 if (argv[command->assignment_cnt] == NULL) {
6997 /* Assignments, but no command */
6998 /* Ensure redirects take effect (that is, create files).
6999 * Try "a=t >file" */
7000#if 0 /* A few cases in testsuite fail with this code. FIXME */
7001 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7002 /* Set shell variables */
7003 if (new_env) {
7004 argv = new_env;
7005 while (*argv) {
7006 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7007 /* Do we need to flag set_local_var() errors?
7008 * "assignment to readonly var" and "putenv error"
7009 */
7010 argv++;
7011 }
7012 }
7013 /* Redirect error sets $? to 1. Otherwise,
7014 * if evaluating assignment value set $?, retain it.
7015 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7016 if (rcode == 0)
7017 rcode = G.last_exitcode;
7018 /* Exit, _skipping_ variable restoring code: */
7019 goto clean_up_and_ret0;
7020
7021#else /* Older, bigger, but more correct code */
7022
7023 rcode = setup_redirects(command, squirrel);
7024 restore_redirects(squirrel);
7025 /* Set shell variables */
7026 if (G_x_mode)
7027 bb_putchar_stderr('+');
7028 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007029 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007030 if (G_x_mode)
7031 fprintf(stderr, " %s", p);
7032 debug_printf_exec("set shell var:'%s'->'%s'\n",
7033 *argv, p);
7034 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7035 /* Do we need to flag set_local_var() errors?
7036 * "assignment to readonly var" and "putenv error"
7037 */
7038 argv++;
7039 }
7040 if (G_x_mode)
7041 bb_putchar_stderr('\n');
7042 /* Redirect error sets $? to 1. Otherwise,
7043 * if evaluating assignment value set $?, retain it.
7044 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7045 if (rcode == 0)
7046 rcode = G.last_exitcode;
7047 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7048 debug_leave();
7049 debug_printf_exec("run_pipe: return %d\n", rcode);
7050 return rcode;
7051#endif
7052 }
7053
7054 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007055#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007056 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007057 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007058 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007059#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007060 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007061 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7062 }
7063
7064 /* if someone gives us an empty string: `cmd with empty output` */
7065 if (!argv_expanded[0]) {
7066 free(argv_expanded);
7067 debug_leave();
7068 return G.last_exitcode;
7069 }
7070
7071 x = find_builtin(argv_expanded[0]);
7072#if ENABLE_HUSH_FUNCTIONS
7073 funcp = NULL;
7074 if (!x)
7075 funcp = find_function(argv_expanded[0]);
7076#endif
7077 if (x || funcp) {
7078 if (!funcp) {
7079 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7080 debug_printf("exec with redirects only\n");
7081 rcode = setup_redirects(command, NULL);
7082 goto clean_up_and_ret1;
7083 }
7084 }
7085 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7086 if (rcode == 0) {
7087 if (!funcp) {
7088 debug_printf_exec(": builtin '%s' '%s'...\n",
7089 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007090 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007091 rcode = x->b_function(argv_expanded) & 0xff;
7092 fflush_all();
7093 }
7094#if ENABLE_HUSH_FUNCTIONS
7095 else {
7096# if ENABLE_HUSH_LOCAL
7097 struct variable **sv;
7098 sv = G.shadowed_vars_pp;
7099 G.shadowed_vars_pp = &old_vars;
7100# endif
7101 debug_printf_exec(": function '%s' '%s'...\n",
7102 funcp->name, argv_expanded[1]);
7103 rcode = run_function(funcp, argv_expanded) & 0xff;
7104# if ENABLE_HUSH_LOCAL
7105 G.shadowed_vars_pp = sv;
7106# endif
7107 }
7108#endif
7109 }
7110 clean_up_and_ret:
7111 unset_vars(new_env);
7112 add_vars(old_vars);
7113/* clean_up_and_ret0: */
7114 restore_redirects(squirrel);
7115 clean_up_and_ret1:
7116 free(argv_expanded);
7117 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7118 debug_leave();
7119 debug_printf_exec("run_pipe return %d\n", rcode);
7120 return rcode;
7121 }
7122
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007123 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007124 int n = find_applet_by_name(argv_expanded[0]);
7125 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7126 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7127 if (rcode == 0) {
7128 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7129 argv_expanded[0], argv_expanded[1]);
7130 rcode = run_nofork_applet(n, argv_expanded);
7131 }
7132 goto clean_up_and_ret;
7133 }
7134 }
7135 /* It is neither builtin nor applet. We must fork. */
7136 }
7137
7138 must_fork:
7139 /* NB: argv_expanded may already be created, and that
7140 * might include `cmd` runs! Do not rerun it! We *must*
7141 * use argv_expanded if it's non-NULL */
7142
7143 /* Going to fork a child per each pipe member */
7144 pi->alive_cmds = 0;
7145 next_infd = 0;
7146
7147 cmd_no = 0;
7148 while (cmd_no < pi->num_cmds) {
7149 struct fd_pair pipefds;
7150#if !BB_MMU
7151 volatile nommu_save_t nommu_save;
7152 nommu_save.new_env = NULL;
7153 nommu_save.old_vars = NULL;
7154 nommu_save.argv = NULL;
7155 nommu_save.argv_from_re_execing = NULL;
7156#endif
7157 command = &pi->cmds[cmd_no];
7158 cmd_no++;
7159 if (command->argv) {
7160 debug_printf_exec(": pipe member '%s' '%s'...\n",
7161 command->argv[0], command->argv[1]);
7162 } else {
7163 debug_printf_exec(": pipe member with no argv\n");
7164 }
7165
7166 /* pipes are inserted between pairs of commands */
7167 pipefds.rd = 0;
7168 pipefds.wr = 1;
7169 if (cmd_no < pi->num_cmds)
7170 xpiped_pair(pipefds);
7171
7172 command->pid = BB_MMU ? fork() : vfork();
7173 if (!command->pid) { /* child */
7174#if ENABLE_HUSH_JOB
7175 disable_restore_tty_pgrp_on_exit();
7176 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7177
7178 /* Every child adds itself to new process group
7179 * with pgid == pid_of_first_child_in_pipe */
7180 if (G.run_list_level == 1 && G_interactive_fd) {
7181 pid_t pgrp;
7182 pgrp = pi->pgrp;
7183 if (pgrp < 0) /* true for 1st process only */
7184 pgrp = getpid();
7185 if (setpgid(0, pgrp) == 0
7186 && pi->followup != PIPE_BG
7187 && G_saved_tty_pgrp /* we have ctty */
7188 ) {
7189 /* We do it in *every* child, not just first,
7190 * to avoid races */
7191 tcsetpgrp(G_interactive_fd, pgrp);
7192 }
7193 }
7194#endif
7195 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7196 /* 1st cmd in backgrounded pipe
7197 * should have its stdin /dev/null'ed */
7198 close(0);
7199 if (open(bb_dev_null, O_RDONLY))
7200 xopen("/", O_RDONLY);
7201 } else {
7202 xmove_fd(next_infd, 0);
7203 }
7204 xmove_fd(pipefds.wr, 1);
7205 if (pipefds.rd > 1)
7206 close(pipefds.rd);
7207 /* Like bash, explicit redirects override pipes,
7208 * and the pipe fd is available for dup'ing. */
7209 if (setup_redirects(command, NULL))
7210 _exit(1);
7211
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007212 /* Stores to nommu_save list of env vars putenv'ed
7213 * (NOMMU, on MMU we don't need that) */
7214 /* cast away volatility... */
7215 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7216 /* pseudo_exec() does not return */
7217 }
7218
7219 /* parent or error */
7220#if ENABLE_HUSH_FAST
7221 G.count_SIGCHLD++;
7222//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7223#endif
7224 enable_restore_tty_pgrp_on_exit();
7225#if !BB_MMU
7226 /* Clean up after vforked child */
7227 free(nommu_save.argv);
7228 free(nommu_save.argv_from_re_execing);
7229 unset_vars(nommu_save.new_env);
7230 add_vars(nommu_save.old_vars);
7231#endif
7232 free(argv_expanded);
7233 argv_expanded = NULL;
7234 if (command->pid < 0) { /* [v]fork failed */
7235 /* Clearly indicate, was it fork or vfork */
7236 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7237 } else {
7238 pi->alive_cmds++;
7239#if ENABLE_HUSH_JOB
7240 /* Second and next children need to know pid of first one */
7241 if (pi->pgrp < 0)
7242 pi->pgrp = command->pid;
7243#endif
7244 }
7245
7246 if (cmd_no > 1)
7247 close(next_infd);
7248 if (cmd_no < pi->num_cmds)
7249 close(pipefds.wr);
7250 /* Pass read (output) pipe end to next iteration */
7251 next_infd = pipefds.rd;
7252 }
7253
7254 if (!pi->alive_cmds) {
7255 debug_leave();
7256 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7257 return 1;
7258 }
7259
7260 debug_leave();
7261 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7262 return -1;
7263}
7264
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007265/* NB: called by pseudo_exec, and therefore must not modify any
7266 * global data until exec/_exit (we can be a child after vfork!) */
7267static int run_list(struct pipe *pi)
7268{
7269#if ENABLE_HUSH_CASE
7270 char *case_word = NULL;
7271#endif
7272#if ENABLE_HUSH_LOOPS
7273 struct pipe *loop_top = NULL;
7274 char **for_lcur = NULL;
7275 char **for_list = NULL;
7276#endif
7277 smallint last_followup;
7278 smalluint rcode;
7279#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7280 smalluint cond_code = 0;
7281#else
7282 enum { cond_code = 0 };
7283#endif
7284#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007285 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007286 smallint last_rword; /* ditto */
7287#endif
7288
7289 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7290 debug_enter();
7291
7292#if ENABLE_HUSH_LOOPS
7293 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007294 {
7295 struct pipe *cpipe;
7296 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7297 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7298 continue;
7299 /* current word is FOR or IN (BOLD in comments below) */
7300 if (cpipe->next == NULL) {
7301 syntax_error("malformed for");
7302 debug_leave();
7303 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7304 return 1;
7305 }
7306 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7307 if (cpipe->next->res_word == RES_DO)
7308 continue;
7309 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7310 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7311 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7312 ) {
7313 syntax_error("malformed for");
7314 debug_leave();
7315 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7316 return 1;
7317 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007318 }
7319 }
7320#endif
7321
7322 /* Past this point, all code paths should jump to ret: label
7323 * in order to return, no direct "return" statements please.
7324 * This helps to ensure that no memory is leaked. */
7325
7326#if ENABLE_HUSH_JOB
7327 G.run_list_level++;
7328#endif
7329
7330#if HAS_KEYWORDS
7331 rword = RES_NONE;
7332 last_rword = RES_XXXX;
7333#endif
7334 last_followup = PIPE_SEQ;
7335 rcode = G.last_exitcode;
7336
7337 /* Go through list of pipes, (maybe) executing them. */
7338 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7339 if (G.flag_SIGINT)
7340 break;
7341
7342 IF_HAS_KEYWORDS(rword = pi->res_word;)
7343 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7344 rword, cond_code, last_rword);
7345#if ENABLE_HUSH_LOOPS
7346 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7347 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7348 ) {
7349 /* start of a loop: remember where loop starts */
7350 loop_top = pi;
7351 G.depth_of_loop++;
7352 }
7353#endif
7354 /* Still in the same "if...", "then..." or "do..." branch? */
7355 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7356 if ((rcode == 0 && last_followup == PIPE_OR)
7357 || (rcode != 0 && last_followup == PIPE_AND)
7358 ) {
7359 /* It is "<true> || CMD" or "<false> && CMD"
7360 * and we should not execute CMD */
7361 debug_printf_exec("skipped cmd because of || or &&\n");
7362 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02007363 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007364 }
7365 }
7366 last_followup = pi->followup;
7367 IF_HAS_KEYWORDS(last_rword = rword;)
7368#if ENABLE_HUSH_IF
7369 if (cond_code) {
7370 if (rword == RES_THEN) {
7371 /* if false; then ... fi has exitcode 0! */
7372 G.last_exitcode = rcode = EXIT_SUCCESS;
7373 /* "if <false> THEN cmd": skip cmd */
7374 continue;
7375 }
7376 } else {
7377 if (rword == RES_ELSE || rword == RES_ELIF) {
7378 /* "if <true> then ... ELSE/ELIF cmd":
7379 * skip cmd and all following ones */
7380 break;
7381 }
7382 }
7383#endif
7384#if ENABLE_HUSH_LOOPS
7385 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7386 if (!for_lcur) {
7387 /* first loop through for */
7388
7389 static const char encoded_dollar_at[] ALIGN1 = {
7390 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7391 }; /* encoded representation of "$@" */
7392 static const char *const encoded_dollar_at_argv[] = {
7393 encoded_dollar_at, NULL
7394 }; /* argv list with one element: "$@" */
7395 char **vals;
7396
7397 vals = (char**)encoded_dollar_at_argv;
7398 if (pi->next->res_word == RES_IN) {
7399 /* if no variable values after "in" we skip "for" */
7400 if (!pi->next->cmds[0].argv) {
7401 G.last_exitcode = rcode = EXIT_SUCCESS;
7402 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7403 break;
7404 }
7405 vals = pi->next->cmds[0].argv;
7406 } /* else: "for var; do..." -> assume "$@" list */
7407 /* create list of variable values */
7408 debug_print_strings("for_list made from", vals);
7409 for_list = expand_strvec_to_strvec(vals);
7410 for_lcur = for_list;
7411 debug_print_strings("for_list", for_list);
7412 }
7413 if (!*for_lcur) {
7414 /* "for" loop is over, clean up */
7415 free(for_list);
7416 for_list = NULL;
7417 for_lcur = NULL;
7418 break;
7419 }
7420 /* Insert next value from for_lcur */
7421 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7422 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7423 continue;
7424 }
7425 if (rword == RES_IN) {
7426 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7427 }
7428 if (rword == RES_DONE) {
7429 continue; /* "done" has no cmds too */
7430 }
7431#endif
7432#if ENABLE_HUSH_CASE
7433 if (rword == RES_CASE) {
7434 case_word = expand_strvec_to_string(pi->cmds->argv);
7435 continue;
7436 }
7437 if (rword == RES_MATCH) {
7438 char **argv;
7439
7440 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7441 break;
7442 /* all prev words didn't match, does this one match? */
7443 argv = pi->cmds->argv;
7444 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007445 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007446 /* TODO: which FNM_xxx flags to use? */
7447 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7448 free(pattern);
7449 if (cond_code == 0) { /* match! we will execute this branch */
7450 free(case_word); /* make future "word)" stop */
7451 case_word = NULL;
7452 break;
7453 }
7454 argv++;
7455 }
7456 continue;
7457 }
7458 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7459 if (cond_code != 0)
7460 continue; /* not matched yet, skip this pipe */
7461 }
7462#endif
7463 /* Just pressing <enter> in shell should check for jobs.
7464 * OTOH, in non-interactive shell this is useless
7465 * and only leads to extra job checks */
7466 if (pi->num_cmds == 0) {
7467 if (G_interactive_fd)
7468 goto check_jobs_and_continue;
7469 continue;
7470 }
7471
7472 /* After analyzing all keywords and conditions, we decided
7473 * to execute this pipe. NB: have to do checkjobs(NULL)
7474 * after run_pipe to collect any background children,
7475 * even if list execution is to be stopped. */
7476 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7477 {
7478 int r;
7479#if ENABLE_HUSH_LOOPS
7480 G.flag_break_continue = 0;
7481#endif
7482 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7483 if (r != -1) {
7484 /* We ran a builtin, function, or group.
7485 * rcode is already known
7486 * and we don't need to wait for anything. */
7487 G.last_exitcode = rcode;
7488 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007489 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007490#if ENABLE_HUSH_LOOPS
7491 /* Was it "break" or "continue"? */
7492 if (G.flag_break_continue) {
7493 smallint fbc = G.flag_break_continue;
7494 /* We might fall into outer *loop*,
7495 * don't want to break it too */
7496 if (loop_top) {
7497 G.depth_break_continue--;
7498 if (G.depth_break_continue == 0)
7499 G.flag_break_continue = 0;
7500 /* else: e.g. "continue 2" should *break* once, *then* continue */
7501 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denys Vlasenko3beab832013-04-07 18:16:58 +02007502 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7503 checkjobs(NULL);
7504 break;
7505 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007506 /* "continue": simulate end of loop */
7507 rword = RES_DONE;
7508 continue;
7509 }
7510#endif
7511#if ENABLE_HUSH_FUNCTIONS
7512 if (G.flag_return_in_progress == 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007513 checkjobs(NULL);
7514 break;
7515 }
7516#endif
7517 } else if (pi->followup == PIPE_BG) {
7518 /* What does bash do with attempts to background builtins? */
7519 /* even bash 3.2 doesn't do that well with nested bg:
7520 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7521 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007522 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007523#if ENABLE_HUSH_JOB
7524 if (G.run_list_level == 1)
7525 insert_bg_job(pi);
7526#endif
7527 /* Last command's pid goes to $! */
7528 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7529 G.last_exitcode = rcode = EXIT_SUCCESS;
7530 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7531 } else {
7532#if ENABLE_HUSH_JOB
7533 if (G.run_list_level == 1 && G_interactive_fd) {
7534 /* Waits for completion, then fg's main shell */
7535 rcode = checkjobs_and_fg_shell(pi);
7536 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007537 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007538 } else
7539#endif
7540 { /* This one just waits for completion */
7541 rcode = checkjobs(pi);
7542 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007543 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007544 }
7545 G.last_exitcode = rcode;
7546 }
7547 }
7548
7549 /* Analyze how result affects subsequent commands */
7550#if ENABLE_HUSH_IF
7551 if (rword == RES_IF || rword == RES_ELIF)
7552 cond_code = rcode;
7553#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02007554 check_jobs_and_continue:
7555 checkjobs(NULL);
7556 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007557#if ENABLE_HUSH_LOOPS
7558 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007559 if (pi->next
7560 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02007561 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007562 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007563 if (rword == RES_WHILE) {
7564 if (rcode) {
7565 /* "while false; do...done" - exitcode 0 */
7566 G.last_exitcode = rcode = EXIT_SUCCESS;
7567 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02007568 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007569 }
7570 }
7571 if (rword == RES_UNTIL) {
7572 if (!rcode) {
7573 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007574 break;
7575 }
7576 }
7577 }
7578#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007579 } /* for (pi) */
7580
7581#if ENABLE_HUSH_JOB
7582 G.run_list_level--;
7583#endif
7584#if ENABLE_HUSH_LOOPS
7585 if (loop_top)
7586 G.depth_of_loop--;
7587 free(for_list);
7588#endif
7589#if ENABLE_HUSH_CASE
7590 free(case_word);
7591#endif
7592 debug_leave();
7593 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7594 return rcode;
7595}
7596
7597/* Select which version we will use */
7598static int run_and_free_list(struct pipe *pi)
7599{
7600 int rcode = 0;
7601 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007602 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007603 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7604 rcode = run_list(pi);
7605 }
7606 /* free_pipe_list has the side effect of clearing memory.
7607 * In the long run that function can be merged with run_list,
7608 * but doing that now would hobble the debugging effort. */
7609 free_pipe_list(pi);
7610 debug_printf_exec("run_and_free_list return %d\n", rcode);
7611 return rcode;
7612}
7613
7614
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007615static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007616{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007617 sighandler_t old_handler;
7618 unsigned sig = 0;
7619 while ((mask >>= 1) != 0) {
7620 sig++;
7621 if (!(mask & 1))
7622 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007623 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007624 /* POSIX allows shell to re-enable SIGCHLD
7625 * even if it was SIG_IGN on entry.
7626 * Therefore we skip IGN check for it:
7627 */
7628 if (sig == SIGCHLD)
7629 continue;
7630 if (old_handler == SIG_IGN) {
7631 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007632 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007633 if (!G.traps)
7634 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7635 free(G.traps[sig]);
7636 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7637 }
7638 }
7639}
7640
7641/* Called a few times only (or even once if "sh -c") */
7642static void install_special_sighandlers(void)
7643{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007644 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007645
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007646 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007647 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007648 if (G_interactive_fd) {
7649 mask |= SPECIAL_INTERACTIVE_SIGS;
7650 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007651 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007652 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007653 /* Careful, do not re-install handlers we already installed */
7654 if (G.special_sig_mask != mask) {
7655 unsigned diff = mask & ~G.special_sig_mask;
7656 G.special_sig_mask = mask;
7657 install_sighandlers(diff);
7658 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007659}
7660
7661#if ENABLE_HUSH_JOB
7662/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007663/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007664static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007665{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007666 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007667
7668 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007669 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007670 + (1 << SIGILL ) * HUSH_DEBUG
7671 + (1 << SIGFPE ) * HUSH_DEBUG
7672 + (1 << SIGBUS ) * HUSH_DEBUG
7673 + (1 << SIGSEGV) * HUSH_DEBUG
7674 + (1 << SIGTRAP) * HUSH_DEBUG
7675 + (1 << SIGABRT)
7676 /* bash 3.2 seems to handle these just like 'fatal' ones */
7677 + (1 << SIGPIPE)
7678 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007679 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007680 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007681 * we never want to restore pgrp on exit, and this fn is not called
7682 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007683 /*+ (1 << SIGHUP )*/
7684 /*+ (1 << SIGTERM)*/
7685 /*+ (1 << SIGINT )*/
7686 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007687 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007688
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007689 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007690}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007691#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007692
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007693static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007694{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007695 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007696 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007697 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007698 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007699 break;
7700 case 'x':
7701 IF_HUSH_MODE_X(G_x_mode = state;)
7702 break;
7703 case 'o':
7704 if (!o_opt) {
7705 /* "set -+o" without parameter.
7706 * in bash, set -o produces this output:
7707 * pipefail off
7708 * and set +o:
7709 * set +o pipefail
7710 * We always use the second form.
7711 */
7712 const char *p = o_opt_strings;
7713 idx = 0;
7714 while (*p) {
7715 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7716 idx++;
7717 p += strlen(p) + 1;
7718 }
7719 break;
7720 }
7721 idx = index_in_strings(o_opt_strings, o_opt);
7722 if (idx >= 0) {
7723 G.o_opt[idx] = state;
7724 break;
7725 }
7726 default:
7727 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007728 }
7729 return EXIT_SUCCESS;
7730}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007731
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007732int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007733int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007734{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007735 enum {
7736 OPT_login = (1 << 0),
7737 };
7738 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00007739 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007740 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007741 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007742 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007743 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007744
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007745 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02007746 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007747 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenko10c01312011-05-11 11:49:21 +02007748#if ENABLE_HUSH_FAST
7749 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7750#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007751#if !BB_MMU
7752 G.argv0_for_re_execing = argv[0];
7753#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007754 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007755 shell_ver = xzalloc(sizeof(*shell_ver));
7756 shell_ver->flg_export = 1;
7757 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007758 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007759 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007760 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007761 /* Create shell local variables from the values
7762 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007763 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007764 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007765 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007766 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007767 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007768 if (e) while (*e) {
7769 char *value = strchr(*e, '=');
7770 if (value) { /* paranoia */
7771 cur_var->next = xzalloc(sizeof(*cur_var));
7772 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007773 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007774 cur_var->max_len = strlen(*e);
7775 cur_var->flg_export = 1;
7776 }
7777 e++;
7778 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007779 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007780 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7781 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007782
7783 /* Export PWD */
7784 set_pwd_var(/*exp:*/ 1);
7785 /* bash also exports SHLVL and _,
7786 * and sets (but doesn't export) the following variables:
7787 * BASH=/bin/bash
7788 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7789 * BASH_VERSION='3.2.0(1)-release'
7790 * HOSTTYPE=i386
7791 * MACHTYPE=i386-pc-linux-gnu
7792 * OSTYPE=linux-gnu
7793 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007794 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007795 * EUID=<NNNNN>
7796 * UID=<NNNNN>
7797 * GROUPS=()
7798 * LINES=<NNN>
7799 * COLUMNS=<NNN>
7800 * BASH_ARGC=()
7801 * BASH_ARGV=()
7802 * BASH_LINENO=()
7803 * BASH_SOURCE=()
7804 * DIRSTACK=()
7805 * PIPESTATUS=([0]="0")
7806 * HISTFILE=/<xxx>/.bash_history
7807 * HISTFILESIZE=500
7808 * HISTSIZE=500
7809 * MAILCHECK=60
7810 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7811 * SHELL=/bin/bash
7812 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7813 * TERM=dumb
7814 * OPTERR=1
7815 * OPTIND=1
7816 * IFS=$' \t\n'
7817 * PS1='\s-\v\$ '
7818 * PS2='> '
7819 * PS4='+ '
7820 */
7821
Denis Vlasenko38f63192007-01-22 09:03:07 +00007822#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02007823 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007824#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007825
Eric Andersen94ac2442001-05-22 19:05:18 +00007826 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007827 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007828
Denis Vlasenkoed782372009-04-10 00:45:02 +00007829 if (setjmp(die_jmp)) {
7830 /* xfunc has failed! die die die */
7831 /* no EXIT traps, this is an escape hatch! */
7832 G.exiting = 1;
7833 hush_exit(xfunc_error_retval);
7834 }
7835
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007836 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007837 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007838 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007839 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007840 * in order to intercept (more) signals.
7841 */
7842
7843 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007844 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007845 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007846 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007847 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007848 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007849#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007850 "<:$:R:V:"
7851# if ENABLE_HUSH_FUNCTIONS
7852 "F:"
7853# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007854#endif
7855 );
7856 if (opt <= 0)
7857 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007858 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007859 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007860 /* Possibilities:
7861 * sh ... -c 'script'
7862 * sh ... -c 'script' ARG0 [ARG1...]
7863 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007864 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007865 * "" needs to be replaced with NULL
7866 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007867 * Note: the form without ARG0 never happens:
7868 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007869 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007870 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007871 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007872 G.root_ppid = getppid();
7873 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007874 G.global_argv = argv + optind;
7875 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007876 if (builtin_argc) {
7877 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7878 const struct built_in_command *x;
7879
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007880 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007881 x = find_builtin(optarg);
7882 if (x) { /* paranoia */
7883 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7884 G.global_argv += builtin_argc;
7885 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007886 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007887 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007888 }
7889 goto final_return;
7890 }
7891 if (!G.global_argv[0]) {
7892 /* -c 'script' (no params): prevent empty $0 */
7893 G.global_argv--; /* points to argv[i] of 'script' */
7894 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007895 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007896 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007897 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007898 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007899 goto final_return;
7900 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007901 /* Well, we cannot just declare interactiveness,
7902 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007903 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007904 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007905 case 's':
7906 /* "-s" means "read from stdin", but this is how we always
7907 * operate, so simply do nothing here. */
7908 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007909 case 'l':
7910 flags |= OPT_login;
7911 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007912#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007913 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007914 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007915 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007916 case '$': {
7917 unsigned long long empty_trap_mask;
7918
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007919 G.root_pid = bb_strtou(optarg, &optarg, 16);
7920 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007921 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7922 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007923 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7924 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007925 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007926 optarg++;
7927 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007928 optarg++;
7929 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7930 if (empty_trap_mask != 0) {
7931 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007932 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007933 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7934 for (sig = 1; sig < NSIG; sig++) {
7935 if (empty_trap_mask & (1LL << sig)) {
7936 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007937 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007938 }
7939 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007940 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007941# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007942 optarg++;
7943 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007944# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007945 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007946 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007947 case 'R':
7948 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007949 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007950 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007951# if ENABLE_HUSH_FUNCTIONS
7952 case 'F': {
7953 struct function *funcp = new_function(optarg);
7954 /* funcp->name is already set to optarg */
7955 /* funcp->body is set to NULL. It's a special case. */
7956 funcp->body_as_string = argv[optind];
7957 optind++;
7958 break;
7959 }
7960# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007961#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007962 case 'n':
7963 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007964 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007965 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007966 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007967#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007968 fprintf(stderr, "Usage: sh [FILE]...\n"
7969 " or: sh -c command [args]...\n\n");
7970 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007971#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007972 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007973#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007974 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007975 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007976
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007977 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7978 G.global_argc = argc - (optind - 1);
7979 G.global_argv = argv + (optind - 1);
7980 G.global_argv[0] = argv[0];
7981
Denys Vlasenkodea47882009-10-09 15:40:49 +02007982 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007983 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007984 G.root_ppid = getppid();
7985 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007986
7987 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007988 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007989 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007990 debug_printf("sourcing /etc/profile\n");
7991 input = fopen_for_read("/etc/profile");
7992 if (input != NULL) {
7993 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007994 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007995 parse_and_run_file(input);
7996 fclose(input);
7997 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007998 /* bash: after sourcing /etc/profile,
7999 * tries to source (in the given order):
8000 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008001 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008002 * bash also sources ~/.bash_logout on exit.
8003 * If called as sh, skips .bash_XXX files.
8004 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008005 }
8006
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008007 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008008 FILE *input;
8009 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008010 * "bash <script>" (which is never interactive (unless -i?))
8011 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008012 * If called as sh, does the same but with $ENV.
8013 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008014 G.global_argc--;
8015 G.global_argv++;
8016 debug_printf("running script '%s'\n", G.global_argv[0]);
8017 input = xfopen_for_read(G.global_argv[0]);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008018 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008019 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008020 parse_and_run_file(input);
8021#if ENABLE_FEATURE_CLEAN_UP
8022 fclose(input);
8023#endif
8024 goto final_return;
8025 }
8026
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008027 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008028 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008029 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008030
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008031 /* A shell is interactive if the '-i' flag was given,
8032 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008033 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008034 * no arguments remaining or the -s flag given
8035 * standard input is a terminal
8036 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008037 * Refer to Posix.2, the description of the 'sh' utility.
8038 */
8039#if ENABLE_HUSH_JOB
8040 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008041 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8042 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8043 if (G_saved_tty_pgrp < 0)
8044 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008045
8046 /* try to dup stdin to high fd#, >= 255 */
8047 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8048 if (G_interactive_fd < 0) {
8049 /* try to dup to any fd */
8050 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008051 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008052 /* give up */
8053 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008054 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008055 }
8056 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008057// TODO: track & disallow any attempts of user
8058// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008059 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008060 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008061 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008062 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008063
Mike Frysinger38478a62009-05-20 04:48:06 -04008064 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008065 /* If we were run as 'hush &', sleep until we are
8066 * in the foreground (tty pgrp == our pgrp).
8067 * If we get started under a job aware app (like bash),
8068 * make sure we are now in charge so we don't fight over
8069 * who gets the foreground */
8070 while (1) {
8071 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008072 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8073 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008074 break;
8075 /* send TTIN to ourself (should stop us) */
8076 kill(- shell_pgrp, SIGTTIN);
8077 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008078 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008079
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008080 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008081 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008082
Mike Frysinger38478a62009-05-20 04:48:06 -04008083 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008084 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008085 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008086 /* Put ourselves in our own process group
8087 * (bash, too, does this only if ctty is available) */
8088 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8089 /* Grab control of the terminal */
8090 tcsetpgrp(G_interactive_fd, getpid());
8091 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00008092 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00008093 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00008094 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008095
8096# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8097 {
8098 const char *hp = get_local_var_value("HISTFILE");
8099 if (!hp) {
8100 hp = get_local_var_value("HOME");
8101 if (hp)
8102 hp = concat_path_file(hp, ".hush_history");
8103 } else {
8104 hp = xstrdup(hp);
8105 }
8106 if (hp) {
8107 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008108 //set_local_var(xasprintf("HISTFILE=%s", ...));
8109 }
8110# if ENABLE_FEATURE_SH_HISTFILESIZE
8111 hp = get_local_var_value("HISTFILESIZE");
8112 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8113# endif
8114 }
8115# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008116 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008117 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008118 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008119#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008120 /* No job control compiled in, only prompt/line editing */
8121 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008122 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8123 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008124 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008125 G_interactive_fd = dup(STDIN_FILENO);
8126 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008127 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008128 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008129 }
8130 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008131 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008132 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008133 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008134 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008135#else
8136 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008137 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008138#endif
8139 /* bash:
8140 * if interactive but not a login shell, sources ~/.bashrc
8141 * (--norc turns this off, --rcfile <file> overrides)
8142 */
8143
8144 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008145 /* note: ash and hush share this string */
8146 printf("\n\n%s %s\n"
8147 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8148 "\n",
8149 bb_banner,
8150 "hush - the humble shell"
8151 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008152 }
8153
Denis Vlasenkof9375282009-04-05 19:13:39 +00008154 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008155
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008156 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008157 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008158}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008159
8160
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008161#if ENABLE_MSH
8162int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8163int msh_main(int argc, char **argv)
8164{
8165 //bb_error_msg("msh is deprecated, please use hush instead");
8166 return hush_main(argc, argv);
8167}
8168#endif
8169
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008170
8171/*
8172 * Built-ins
8173 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008174static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008175{
8176 return 0;
8177}
8178
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008179static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008180{
8181 int argc = 0;
8182 while (*argv) {
8183 argc++;
8184 argv++;
8185 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008186 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008187}
8188
8189static int FAST_FUNC builtin_test(char **argv)
8190{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008191 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008192}
8193
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008194static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008195{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008196 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008197}
8198
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008199#if ENABLE_PRINTF
8200static int FAST_FUNC builtin_printf(char **argv)
8201{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008202 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008203}
8204#endif
8205
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008206static char **skip_dash_dash(char **argv)
8207{
8208 argv++;
8209 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8210 argv++;
8211 return argv;
8212}
8213
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008214static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008215{
8216 int rcode = EXIT_SUCCESS;
8217
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008218 argv = skip_dash_dash(argv);
8219 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008220 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008221 /* bash:
8222 * eval "echo Hi; done" ("done" is syntax error):
8223 * "echo Hi" will not execute too.
8224 */
8225 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008226 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008227 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008228 }
8229 return rcode;
8230}
8231
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008232static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008233{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008234 const char *newdir;
8235
8236 argv = skip_dash_dash(argv);
8237 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008238 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008239 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008240 * bash says "bash: cd: HOME not set" and does nothing
8241 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008242 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008243 const char *home = get_local_var_value("HOME");
8244 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008245 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008246 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008247 /* Mimic bash message exactly */
8248 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008249 return EXIT_FAILURE;
8250 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008251 /* Read current dir (get_cwd(1) is inside) and set PWD.
8252 * Note: do not enforce exporting. If PWD was unset or unexported,
8253 * set it again, but do not export. bash does the same.
8254 */
8255 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008256 return EXIT_SUCCESS;
8257}
8258
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008259static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008260{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008261 argv = skip_dash_dash(argv);
8262 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008263 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008264
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008265 /* Careful: we can end up here after [v]fork. Do not restore
8266 * tty pgrp then, only top-level shell process does that */
8267 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8268 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8269
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008270 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008271 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008272 * and tcsetpgrp, and this is inherently racy.
8273 */
8274 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008275}
8276
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008277static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008278{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008279 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008280
8281 /* interactive bash:
8282 * # trap "echo EEE" EXIT
8283 * # exit
8284 * exit
8285 * There are stopped jobs.
8286 * (if there are _stopped_ jobs, running ones don't count)
8287 * # exit
8288 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01008289 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00008290 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008291 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008292 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008293
8294 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008295 argv = skip_dash_dash(argv);
8296 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008297 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008298 /* mimic bash: exit 123abc == exit 255 + error msg */
8299 xfunc_error_retval = 255;
8300 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008301 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008302}
8303
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008304static void print_escaped(const char *s)
8305{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008306 if (*s == '\'')
8307 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008308 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008309 const char *p = strchrnul(s, '\'');
8310 /* print 'xxxx', possibly just '' */
8311 printf("'%.*s'", (int)(p - s), s);
8312 if (*p == '\0')
8313 break;
8314 s = p;
8315 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008316 /* s points to '; print "'''...'''" */
8317 putchar('"');
8318 do putchar('\''); while (*++s == '\'');
8319 putchar('"');
8320 } while (*s);
8321}
8322
Denys Vlasenko295fef82009-06-03 12:47:26 +02008323#if !ENABLE_HUSH_LOCAL
8324#define helper_export_local(argv, exp, lvl) \
8325 helper_export_local(argv, exp)
8326#endif
8327static void helper_export_local(char **argv, int exp, int lvl)
8328{
8329 do {
8330 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008331 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008332
8333 /* So far we do not check that name is valid (TODO?) */
8334
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008335 if (*name_end == '\0') {
8336 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008337
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008338 vpp = get_ptr_to_local_var(name, name_end - name);
8339 var = vpp ? *vpp : NULL;
8340
Denys Vlasenko295fef82009-06-03 12:47:26 +02008341 if (exp == -1) { /* unexporting? */
8342 /* export -n NAME (without =VALUE) */
8343 if (var) {
8344 var->flg_export = 0;
8345 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8346 unsetenv(name);
8347 } /* else: export -n NOT_EXISTING_VAR: no-op */
8348 continue;
8349 }
8350 if (exp == 1) { /* exporting? */
8351 /* export NAME (without =VALUE) */
8352 if (var) {
8353 var->flg_export = 1;
8354 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8355 putenv(var->varstr);
8356 continue;
8357 }
8358 }
8359 /* Exporting non-existing variable.
8360 * bash does not put it in environment,
8361 * but remembers that it is exported,
8362 * and does put it in env when it is set later.
8363 * We just set it to "" and export. */
8364 /* Or, it's "local NAME" (without =VALUE).
8365 * bash sets the value to "". */
8366 name = xasprintf("%s=", name);
8367 } else {
8368 /* (Un)exporting/making local NAME=VALUE */
8369 name = xstrdup(name);
8370 }
8371 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8372 } while (*++argv);
8373}
8374
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008375static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008376{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008377 unsigned opt_unexport;
8378
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008379#if ENABLE_HUSH_EXPORT_N
8380 /* "!": do not abort on errors */
8381 opt_unexport = getopt32(argv, "!n");
8382 if (opt_unexport == (uint32_t)-1)
8383 return EXIT_FAILURE;
8384 argv += optind;
8385#else
8386 opt_unexport = 0;
8387 argv++;
8388#endif
8389
8390 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008391 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008392 if (e) {
8393 while (*e) {
8394#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008395 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008396#else
8397 /* ash emits: export VAR='VAL'
8398 * bash: declare -x VAR="VAL"
8399 * we follow ash example */
8400 const char *s = *e++;
8401 const char *p = strchr(s, '=');
8402
8403 if (!p) /* wtf? take next variable */
8404 continue;
8405 /* export var= */
8406 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008407 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008408 putchar('\n');
8409#endif
8410 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008411 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008412 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008413 return EXIT_SUCCESS;
8414 }
8415
Denys Vlasenko295fef82009-06-03 12:47:26 +02008416 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008417
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008418 return EXIT_SUCCESS;
8419}
8420
Denys Vlasenko295fef82009-06-03 12:47:26 +02008421#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008422static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008423{
8424 if (G.func_nest_level == 0) {
8425 bb_error_msg("%s: not in a function", argv[0]);
8426 return EXIT_FAILURE; /* bash compat */
8427 }
8428 helper_export_local(argv, 0, G.func_nest_level);
8429 return EXIT_SUCCESS;
8430}
8431#endif
8432
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008433static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008434{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008435 int sig;
8436 char *new_cmd;
8437
8438 if (!G.traps)
8439 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8440
8441 argv++;
8442 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008443 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008444 /* No args: print all trapped */
8445 for (i = 0; i < NSIG; ++i) {
8446 if (G.traps[i]) {
8447 printf("trap -- ");
8448 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008449 /* note: bash adds "SIG", but only if invoked
8450 * as "bash". If called as "sh", or if set -o posix,
8451 * then it prints short signal names.
8452 * We are printing short names: */
8453 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008454 }
8455 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008456 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008457 return EXIT_SUCCESS;
8458 }
8459
8460 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008461 /* If first arg is a number: reset all specified signals */
8462 sig = bb_strtou(*argv, NULL, 10);
8463 if (errno == 0) {
8464 int ret;
8465 process_sig_list:
8466 ret = EXIT_SUCCESS;
8467 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008468 sighandler_t handler;
8469
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008470 sig = get_signum(*argv++);
8471 if (sig < 0 || sig >= NSIG) {
8472 ret = EXIT_FAILURE;
8473 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008474 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008475 continue;
8476 }
8477
8478 free(G.traps[sig]);
8479 G.traps[sig] = xstrdup(new_cmd);
8480
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008481 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008482 get_signame(sig), sig, G.traps[sig]);
8483
8484 /* There is no signal for 0 (EXIT) */
8485 if (sig == 0)
8486 continue;
8487
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008488 if (new_cmd)
8489 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8490 else
8491 /* We are removing trap handler */
8492 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02008493 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008494 }
8495 return ret;
8496 }
8497
8498 if (!argv[1]) { /* no second arg */
8499 bb_error_msg("trap: invalid arguments");
8500 return EXIT_FAILURE;
8501 }
8502
8503 /* First arg is "-": reset all specified to default */
8504 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8505 /* Everything else: set arg as signal handler
8506 * (includes "" case, which ignores signal) */
8507 if (argv[0][0] == '-') {
8508 if (argv[0][1] == '\0') { /* "-" */
8509 /* new_cmd remains NULL: "reset these sigs" */
8510 goto reset_traps;
8511 }
8512 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8513 argv++;
8514 }
8515 /* else: "-something", no special meaning */
8516 }
8517 new_cmd = *argv;
8518 reset_traps:
8519 argv++;
8520 goto process_sig_list;
8521}
8522
Mike Frysinger93cadc22009-05-27 17:06:25 -04008523/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008524static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008525{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008526 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008527
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008528 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008529 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008530 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008531
8532 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008533 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008534 type = "an alias";*/
8535#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008536 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008537 type = "a function";
8538#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008539 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008540 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008541 else if ((path = find_in_path(*argv)) != NULL)
8542 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008543 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008544 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008545 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008546 continue;
8547 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008548
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008549 printf("%s is %s\n", *argv, type);
8550 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008551 }
8552
8553 return ret;
8554}
8555
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008556#if ENABLE_HUSH_JOB
8557/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008558static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008559{
8560 int i, jobnum;
8561 struct pipe *pi;
8562
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008563 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008564 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008565
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008566 /* If they gave us no args, assume they want the last backgrounded task */
8567 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008568 for (pi = G.job_list; pi; pi = pi->next) {
8569 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008570 goto found;
8571 }
8572 }
8573 bb_error_msg("%s: no current job", argv[0]);
8574 return EXIT_FAILURE;
8575 }
8576 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8577 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8578 return EXIT_FAILURE;
8579 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008580 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008581 if (pi->jobid == jobnum) {
8582 goto found;
8583 }
8584 }
8585 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8586 return EXIT_FAILURE;
8587 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008588 /* TODO: bash prints a string representation
8589 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008590 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008591 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008592 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008593 }
8594
8595 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008596 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8597 for (i = 0; i < pi->num_cmds; i++) {
8598 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008599 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008600 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008601
8602 i = kill(- pi->pgrp, SIGCONT);
8603 if (i < 0) {
8604 if (errno == ESRCH) {
8605 delete_finished_bg_job(pi);
8606 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008607 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008608 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008609 }
8610
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008611 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008612 remove_bg_job(pi);
8613 return checkjobs_and_fg_shell(pi);
8614 }
8615 return EXIT_SUCCESS;
8616}
8617#endif
8618
8619#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008620static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008621{
8622 const struct built_in_command *x;
8623
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008624 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008625 "Built-in commands:\n"
8626 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008627 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008628 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008629 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008630 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008631 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008632 return EXIT_SUCCESS;
8633}
8634#endif
8635
Flemming Madsend96ffda2013-04-07 18:47:24 +02008636#if MAX_HISTORY
8637static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
8638{
8639 show_history(G.line_input_state);
8640 return EXIT_SUCCESS;
8641}
8642#endif
8643
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008644#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008645static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008646{
8647 struct pipe *job;
8648 const char *status_string;
8649
Denis Vlasenko87a86552008-07-29 19:43:10 +00008650 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008651 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008652 status_string = "Stopped";
8653 else
8654 status_string = "Running";
8655
8656 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8657 }
8658 return EXIT_SUCCESS;
8659}
8660#endif
8661
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008662#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008663static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008664{
8665 void *p;
8666 unsigned long l;
8667
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008668# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008669 /* Optional. Reduces probability of false positives */
8670 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008671# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008672 /* Crude attempt to find where "free memory" starts,
8673 * sans fragmentation. */
8674 p = malloc(240);
8675 l = (unsigned long)p;
8676 free(p);
8677 p = malloc(3400);
8678 if (l < (unsigned long)p) l = (unsigned long)p;
8679 free(p);
8680
8681 if (!G.memleak_value)
8682 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008683
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008684 l -= G.memleak_value;
8685 if ((long)l < 0)
8686 l = 0;
8687 l /= 1024;
8688 if (l > 127)
8689 l = 127;
8690
8691 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8692 return l;
8693}
8694#endif
8695
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008696static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008697{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008698 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008699 return EXIT_SUCCESS;
8700}
8701
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008702/* Interruptibility of read builtin in bash
8703 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8704 *
8705 * Empty trap makes read ignore corresponding signal, for any signal.
8706 *
8707 * SIGINT:
8708 * - terminates non-interactive shell;
8709 * - interrupts read in interactive shell;
8710 * if it has non-empty trap:
8711 * - executes trap and returns to command prompt in interactive shell;
8712 * - executes trap and returns to read in non-interactive shell;
8713 * SIGTERM:
8714 * - is ignored (does not interrupt) read in interactive shell;
8715 * - terminates non-interactive shell;
8716 * if it has non-empty trap:
8717 * - executes trap and returns to read;
8718 * SIGHUP:
8719 * - terminates shell (regardless of interactivity);
8720 * if it has non-empty trap:
8721 * - executes trap and returns to read;
8722 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008723static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008724{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008725 const char *r;
8726 char *opt_n = NULL;
8727 char *opt_p = NULL;
8728 char *opt_t = NULL;
8729 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008730 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01008731 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008732
Denys Vlasenko03dad222010-01-12 23:29:57 +01008733 /* "!": do not abort on errors.
8734 * Option string must start with "sr" to match BUILTIN_READ_xxx
8735 */
8736 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8737 if (read_flags == (uint32_t)-1)
8738 return EXIT_FAILURE;
8739 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008740 ifs = get_local_var_value("IFS"); /* can be NULL */
8741
8742 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01008743 r = shell_builtin_read(set_local_var_from_halves,
8744 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008745 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01008746 read_flags,
8747 opt_n,
8748 opt_p,
8749 opt_t,
8750 opt_u
8751 );
8752
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008753 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008754 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008755 if (sig && sig != SIGINT)
8756 goto again;
8757 }
8758
Denys Vlasenko03dad222010-01-12 23:29:57 +01008759 if ((uintptr_t)r > 1) {
8760 bb_error_msg("%s", r);
8761 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008762 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008763
Denys Vlasenko03dad222010-01-12 23:29:57 +01008764 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008765}
8766
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008767/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8768 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008769 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008770 * set [-abCefhmnuvx] [-o option] [argument...]
8771 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008772 * set -- [argument...]
8773 * set -o
8774 * set +o
8775 * Implementations shall support the options in both their hyphen and
8776 * plus-sign forms. These options can also be specified as options to sh.
8777 * Examples:
8778 * Write out all variables and their values: set
8779 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8780 * Turn on the -x and -v options: set -xv
8781 * Unset all positional parameters: set --
8782 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8783 * Set the positional parameters to the expansion of x, even if x expands
8784 * with a leading '-' or '+': set -- $x
8785 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008786 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008787 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008788static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008789{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008790 int n;
8791 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008792 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008793
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008794 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008795 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008796 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008797 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008798 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008799 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008800
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008801 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008802 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008803 ++argv;
8804 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008805 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008806 if (arg[0] != '+' && arg[0] != '-')
8807 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008808 for (n = 1; arg[n]; ++n) {
8809 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008810 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008811 if (arg[n] == 'o' && argv[1])
8812 argv++;
8813 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008814 } while ((arg = *++argv) != NULL);
8815 /* Now argv[0] is 1st argument */
8816
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008817 if (arg == NULL)
8818 return EXIT_SUCCESS;
8819 set_argv:
8820
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008821 /* NB: G.global_argv[0] ($0) is never freed/changed */
8822 g_argv = G.global_argv;
8823 if (G.global_args_malloced) {
8824 pp = g_argv;
8825 while (*++pp)
8826 free(*pp);
8827 g_argv[1] = NULL;
8828 } else {
8829 G.global_args_malloced = 1;
8830 pp = xzalloc(sizeof(pp[0]) * 2);
8831 pp[0] = g_argv[0]; /* retain $0 */
8832 g_argv = pp;
8833 }
8834 /* This realloc's G.global_argv */
8835 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8836
8837 n = 1;
8838 while (*++pp)
8839 n++;
8840 G.global_argc = n;
8841
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008842 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008843
8844 /* Nothing known, so abort */
8845 error:
8846 bb_error_msg("set: %s: invalid option", arg);
8847 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008848}
8849
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008850static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008851{
8852 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008853 argv = skip_dash_dash(argv);
8854 if (argv[0]) {
8855 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008856 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008857 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008858 if (G.global_args_malloced) {
8859 int m = 1;
8860 while (m <= n)
8861 free(G.global_argv[m++]);
8862 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008863 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008864 memmove(&G.global_argv[1], &G.global_argv[n+1],
8865 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008866 return EXIT_SUCCESS;
8867 }
8868 return EXIT_FAILURE;
8869}
8870
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008871static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008872{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008873 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008874 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008875 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008876#if ENABLE_HUSH_FUNCTIONS
8877 smallint sv_flg;
8878#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008879
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008880 argv = skip_dash_dash(argv);
8881 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008882 if (!filename) {
8883 /* bash says: "bash: .: filename argument required" */
8884 return 2; /* bash compat */
8885 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008886 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008887 if (!strchr(filename, '/')) {
8888 arg_path = find_in_path(filename);
8889 if (arg_path)
8890 filename = arg_path;
8891 }
8892 input = fopen_or_warn(filename, "r");
8893 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008894 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008895 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01008896 /* POSIX: non-interactive shell should abort here,
8897 * not merely fail. So far no one complained :)
8898 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008899 return EXIT_FAILURE;
8900 }
8901 close_on_exec_on(fileno(input));
8902
Mike Frysinger885b6f22009-04-18 21:04:25 +00008903#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008904 sv_flg = G.flag_return_in_progress;
8905 /* "we are inside sourced file, ok to use return" */
8906 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008907#endif
Denys Vlasenko88b532d2013-03-17 14:11:04 +01008908 if (argv[1])
8909 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008910
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008911 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008912 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008913
Denys Vlasenko88b532d2013-03-17 14:11:04 +01008914 if (argv[1])
8915 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008916#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008917 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008918#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008919
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008920 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008921}
8922
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008923static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008924{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008925 int rc;
8926 mode_t mask;
8927
8928 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008929 argv = skip_dash_dash(argv);
8930 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008931 mode_t old_mask = mask;
8932
8933 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008934 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008935 mask ^= 0777;
8936 if (rc == 0) {
8937 mask = old_mask;
8938 /* bash messages:
8939 * bash: umask: 'q': invalid symbolic mode operator
8940 * bash: umask: 999: octal number out of range
8941 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008942 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008943 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008944 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008945 rc = 1;
8946 /* Mimic bash */
8947 printf("%04o\n", (unsigned) mask);
8948 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008949 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008950 umask(mask);
8951
8952 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008953}
8954
Mike Frysingerd690f682009-03-30 06:50:54 +00008955/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008956static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008957{
Mike Frysingerd690f682009-03-30 06:50:54 +00008958 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008959 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008960
Denis Vlasenko28e67962009-04-26 23:22:40 +00008961 /* "!": do not abort on errors */
8962 /* "+": stop at 1st non-option */
8963 opts = getopt32(argv, "!+vf");
8964 if (opts == (unsigned)-1)
8965 return EXIT_FAILURE;
8966 if (opts == 3) {
8967 bb_error_msg("unset: -v and -f are exclusive");
8968 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008969 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008970 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008971
8972 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008973 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008974 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008975 if (unset_local_var(*argv)) {
8976 /* unset <nonexistent_var> doesn't fail.
8977 * Error is when one tries to unset RO var.
8978 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008979 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008980 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008981 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008982#if ENABLE_HUSH_FUNCTIONS
8983 else {
8984 unset_func(*argv);
8985 }
8986#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008987 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008988 }
8989 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008990}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008991
Mike Frysinger56bdea12009-03-28 20:01:58 +00008992/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008993static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008994{
8995 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008996 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008997
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008998 argv = skip_dash_dash(argv);
8999 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009000 /* Don't care about wait results */
9001 /* Note 1: must wait until there are no more children */
9002 /* Note 2: must be interruptible */
9003 /* Examples:
9004 * $ sleep 3 & sleep 6 & wait
9005 * [1] 30934 sleep 3
9006 * [2] 30935 sleep 6
9007 * [1] Done sleep 3
9008 * [2] Done sleep 6
9009 * $ sleep 3 & sleep 6 & wait
9010 * [1] 30936 sleep 3
9011 * [2] 30937 sleep 6
9012 * [1] Done sleep 3
9013 * ^C <-- after ~4 sec from keyboard
9014 * $
9015 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009016 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009017 int sig;
9018 sigset_t oldset, allsigs;
9019
9020 /* waitpid is not interruptible by SA_RESTARTed
9021 * signals which we use. Thus, this ugly dance:
9022 */
9023
9024 /* Make sure possible SIGCHLD is stored in kernel's
9025 * pending signal mask before we call waitpid.
9026 * Or else we may race with SIGCHLD, lose it,
9027 * and get stuck in sigwaitinfo...
9028 */
9029 sigfillset(&allsigs);
9030 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9031
9032 if (!sigisemptyset(&G.pending_set)) {
9033 /* Crap! we raced with some signal! */
9034 // sig = 0;
9035 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009036 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009037
9038 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9039 if (errno == ECHILD) {
9040 sigprocmask(SIG_SETMASK, &oldset, NULL);
9041 break;
9042 }
9043
9044 /* Wait for SIGCHLD or any other signal */
9045 //sig = sigwaitinfo(&allsigs, NULL);
9046 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9047 /* Note: sigsuspend invokes signal handler */
9048 sigsuspend(&oldset);
9049 restore:
9050 sigprocmask(SIG_SETMASK, &oldset, NULL);
9051
9052 /* So, did we get a signal? */
9053 //if (sig > 0)
9054 // raise(sig); /* run handler */
9055 sig = check_and_run_traps();
9056 if (sig /*&& sig != SIGCHLD - always true */) {
9057 /* see note 2 */
9058 ret = 128 + sig;
9059 break;
9060 }
9061 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009062 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009063 return ret;
9064 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009065
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009066 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009067 while (*argv) {
9068 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00009069 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009070 /* mimic bash message */
9071 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009072 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009073 }
9074 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00009075 if (WIFSIGNALED(status))
9076 ret = 128 + WTERMSIG(status);
9077 else if (WIFEXITED(status))
9078 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00009079 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00009080 ret = EXIT_FAILURE;
9081 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009082 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009083 ret = 127;
9084 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00009085 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009086 }
9087
9088 return ret;
9089}
9090
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009091#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9092static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9093{
9094 if (argv[1]) {
9095 def = bb_strtou(argv[1], NULL, 10);
9096 if (errno || def < def_min || argv[2]) {
9097 bb_error_msg("%s: bad arguments", argv[0]);
9098 def = UINT_MAX;
9099 }
9100 }
9101 return def;
9102}
9103#endif
9104
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009105#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009106static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009107{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009108 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009109 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009110 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009111 return EXIT_SUCCESS; /* bash compat */
9112 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009113 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009114
9115 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9116 if (depth == UINT_MAX)
9117 G.flag_break_continue = BC_BREAK;
9118 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009119 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009120
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009121 return EXIT_SUCCESS;
9122}
9123
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009124static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009125{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009126 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9127 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009128}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009129#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009130
9131#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009132static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009133{
9134 int rc;
9135
9136 if (G.flag_return_in_progress != -1) {
9137 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9138 return EXIT_FAILURE; /* bash compat */
9139 }
9140
9141 G.flag_return_in_progress = 1;
9142
9143 /* bash:
9144 * out of range: wraps around at 256, does not error out
9145 * non-numeric param:
9146 * f() { false; return qwe; }; f; echo $?
9147 * bash: return: qwe: numeric argument required <== we do this
9148 * 255 <== we also do this
9149 */
9150 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9151 return rc;
9152}
9153#endif