blob: b9e763cc84053717c27934708854f043784f41cb [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
Denys Vlasenko295fef82009-06-03 12:47:26 +0200853#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200854static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200855#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000856#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200857static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000858#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400859#if ENABLE_PRINTF
860static int builtin_printf(char **argv) FAST_FUNC;
861#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200862static int builtin_pwd(char **argv) FAST_FUNC;
863static int builtin_read(char **argv) FAST_FUNC;
864static int builtin_set(char **argv) FAST_FUNC;
865static int builtin_shift(char **argv) FAST_FUNC;
866static int builtin_source(char **argv) FAST_FUNC;
867static int builtin_test(char **argv) FAST_FUNC;
868static int builtin_trap(char **argv) FAST_FUNC;
869static int builtin_type(char **argv) FAST_FUNC;
870static int builtin_true(char **argv) FAST_FUNC;
871static int builtin_umask(char **argv) FAST_FUNC;
872static int builtin_unset(char **argv) FAST_FUNC;
873static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000874#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200875static int builtin_break(char **argv) FAST_FUNC;
876static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000877#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000878#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200879static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000880#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000881
882/* Table of built-in functions. They can be forked or not, depending on
883 * context: within pipes, they fork. As simple commands, they do not.
884 * When used in non-forking context, they can change global variables
885 * in the parent shell process. If forked, of course they cannot.
886 * For example, 'unset foo | whatever' will parse and run, but foo will
887 * still be set at the end. */
888struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100889 const char *b_cmd;
890 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000891#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100892 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200893# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000894#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200895# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000896#endif
897};
898
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200899static const struct built_in_command bltins1[] = {
900 BLTIN("." , builtin_source , "Run commands in a file"),
901 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000902#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200903 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000904#endif
905#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200906 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000907#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200908 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000909#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200910 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000911#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200912 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
913 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
914 BLTIN("exit" , builtin_exit , "Exit"),
915 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000916#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200917 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000918#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000919#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200920 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000921#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000922#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200923 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000924#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200925#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200926 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200927#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000928#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200929 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000930#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200931 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000932#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200933 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000934#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200935 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
936 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200937#if ENABLE_HUSH_BASH_COMPAT
938 BLTIN("source" , builtin_source , "Run commands in a file"),
939#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200940 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100941 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100942 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200943 BLTIN("umask" , builtin_umask , "Set file creation mask"),
944 BLTIN("unset" , builtin_unset , "Unset variables"),
945 BLTIN("wait" , builtin_wait , "Wait for process"),
946};
947/* For now, echo and test are unconditionally enabled.
948 * Maybe make it configurable? */
949static const struct built_in_command bltins2[] = {
950 BLTIN("[" , builtin_test , NULL),
951 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400952#if ENABLE_PRINTF
953 BLTIN("printf" , builtin_printf , NULL),
954#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200955 BLTIN("pwd" , builtin_pwd , NULL),
956 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000957};
958
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000959
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000960/* Debug printouts.
961 */
962#if HUSH_DEBUG
963/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100964# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000965# define debug_enter() (G.debug_indent++)
966# define debug_leave() (G.debug_indent--)
967#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200968# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000969# define debug_enter() ((void)0)
970# define debug_leave() ((void)0)
971#endif
972
973#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100974# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000975#endif
976
977#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100978# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000979#endif
980
981#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100982#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000983#endif
984
985#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100986# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000987#endif
988
989#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100990# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000991# define DEBUG_JOBS 1
992#else
993# define DEBUG_JOBS 0
994#endif
995
996#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100997# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000998# define DEBUG_EXPAND 1
999#else
1000# define DEBUG_EXPAND 0
1001#endif
1002
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001003#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001004# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001005#endif
1006
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001007#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001008# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001009# define DEBUG_GLOB 1
1010#else
1011# define DEBUG_GLOB 0
1012#endif
1013
1014#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001015# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001016#endif
1017
1018#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001019# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001020#endif
1021
1022#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001023# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001024# define DEBUG_CLEAN 1
1025#else
1026# define DEBUG_CLEAN 0
1027#endif
1028
1029#if DEBUG_EXPAND
1030static void debug_print_strings(const char *prefix, char **vv)
1031{
1032 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001033 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001034 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001035 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001036}
1037#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001038# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001039#endif
1040
1041
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001042/* Leak hunting. Use hush_leaktool.sh for post-processing.
1043 */
1044#if LEAK_HUNTING
1045static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001046{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001047 void *ptr = xmalloc((size + 0xff) & ~0xff);
1048 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1049 return ptr;
1050}
1051static void *xxrealloc(int lineno, void *ptr, size_t size)
1052{
1053 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1054 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1055 return ptr;
1056}
1057static char *xxstrdup(int lineno, const char *str)
1058{
1059 char *ptr = xstrdup(str);
1060 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1061 return ptr;
1062}
1063static void xxfree(void *ptr)
1064{
1065 fdprintf(2, "free %p\n", ptr);
1066 free(ptr);
1067}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001068# define xmalloc(s) xxmalloc(__LINE__, s)
1069# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1070# define xstrdup(s) xxstrdup(__LINE__, s)
1071# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001072#endif
1073
1074
1075/* Syntax and runtime errors. They always abort scripts.
1076 * In interactive use they usually discard unparsed and/or unexecuted commands
1077 * and return to the prompt.
1078 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1079 */
1080#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001081# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001082# define syntax_error(lineno, msg) syntax_error(msg)
1083# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1084# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1085# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1086# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001087#endif
1088
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001089static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001090{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001091 va_list p;
1092
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001093#if HUSH_DEBUG >= 2
1094 bb_error_msg("hush.c:%u", lineno);
1095#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001096 va_start(p, fmt);
1097 bb_verror_msg(fmt, p, NULL);
1098 va_end(p);
1099 if (!G_interactive_fd)
1100 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001101}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001102
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001103static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001104{
1105 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001106 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001107 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001108 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001109}
1110
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001111static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001112{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001113 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001114}
1115
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001116static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001117{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001118 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001119}
1120
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001121static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001122{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001123 char msg[2] = { ch, '\0' };
1124 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001125}
1126
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001127static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001128{
1129 char msg[2];
1130 msg[0] = ch;
1131 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001132 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001133}
1134
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001135#if HUSH_DEBUG < 2
1136# undef die_if_script
1137# undef syntax_error
1138# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001139# undef syntax_error_unterm_ch
1140# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001141# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001142#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001143# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001144# define syntax_error(msg) syntax_error(__LINE__, msg)
1145# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1146# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1147# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1148# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001149#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001150
Denis Vlasenko552433b2009-04-04 19:29:21 +00001151
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001152#if ENABLE_HUSH_INTERACTIVE
1153static void cmdedit_update_prompt(void);
1154#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001155# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001156#endif
1157
1158
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001159/* Utility functions
1160 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001161/* Replace each \x with x in place, return ptr past NUL. */
1162static char *unbackslash(char *src)
1163{
Denys Vlasenko71885402009-09-24 01:44:13 +02001164 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001165 while (1) {
1166 if (*src == '\\')
1167 src++;
1168 if ((*dst++ = *src++) == '\0')
1169 break;
1170 }
1171 return dst;
1172}
1173
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001174static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001175{
1176 int i;
1177 unsigned count1;
1178 unsigned count2;
1179 char **v;
1180
1181 v = strings;
1182 count1 = 0;
1183 if (v) {
1184 while (*v) {
1185 count1++;
1186 v++;
1187 }
1188 }
1189 count2 = 0;
1190 v = add;
1191 while (*v) {
1192 count2++;
1193 v++;
1194 }
1195 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1196 v[count1 + count2] = NULL;
1197 i = count2;
1198 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001199 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001200 return v;
1201}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001202#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001203static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1204{
1205 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1206 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1207 return ptr;
1208}
1209#define add_strings_to_strings(strings, add, need_to_dup) \
1210 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1211#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001212
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001213/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001214static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001215{
1216 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001217 v[0] = add;
1218 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001219 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001220}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001221#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001222static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1223{
1224 char **ptr = add_string_to_strings(strings, add);
1225 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1226 return ptr;
1227}
1228#define add_string_to_strings(strings, add) \
1229 xx_add_string_to_strings(__LINE__, strings, add)
1230#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001231
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001232static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001233{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001234 char **v;
1235
1236 if (!strings)
1237 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001238 v = strings;
1239 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001240 free(*v);
1241 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001242 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001243 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001244}
1245
Denis Vlasenko76d50412008-06-10 16:19:39 +00001246
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001247/* Helpers for setting new $n and restoring them back
1248 */
1249typedef struct save_arg_t {
1250 char *sv_argv0;
1251 char **sv_g_argv;
1252 int sv_g_argc;
1253 smallint sv_g_malloced;
1254} save_arg_t;
1255
1256static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1257{
1258 int n;
1259
1260 sv->sv_argv0 = argv[0];
1261 sv->sv_g_argv = G.global_argv;
1262 sv->sv_g_argc = G.global_argc;
1263 sv->sv_g_malloced = G.global_args_malloced;
1264
1265 argv[0] = G.global_argv[0]; /* retain $0 */
1266 G.global_argv = argv;
1267 G.global_args_malloced = 0;
1268
1269 n = 1;
1270 while (*++argv)
1271 n++;
1272 G.global_argc = n;
1273}
1274
1275static void restore_G_args(save_arg_t *sv, char **argv)
1276{
1277 char **pp;
1278
1279 if (G.global_args_malloced) {
1280 /* someone ran "set -- arg1 arg2 ...", undo */
1281 pp = G.global_argv;
1282 while (*++pp) /* note: does not free $0 */
1283 free(*pp);
1284 free(G.global_argv);
1285 }
1286 argv[0] = sv->sv_argv0;
1287 G.global_argv = sv->sv_g_argv;
1288 G.global_argc = sv->sv_g_argc;
1289 G.global_args_malloced = sv->sv_g_malloced;
1290}
1291
1292
Denis Vlasenkod5762932009-03-31 11:22:57 +00001293/* Basic theory of signal handling in shell
1294 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001295 * This does not describe what hush does, rather, it is current understanding
1296 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001297 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1298 *
1299 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1300 * is finished or backgrounded. It is the same in interactive and
1301 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001302 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001303 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001304 * backgrounds (i.e. stops) or kills all members of currently running
1305 * pipe.
1306 *
1307 * Wait builtin in interruptible by signals for which user trap is set
1308 * or by SIGINT in interactive shell.
1309 *
1310 * Trap handlers will execute even within trap handlers. (right?)
1311 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001312 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1313 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001314 *
1315 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001316 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001317 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001318 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001319 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001320 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001321 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001322 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001323 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001324 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001325 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001326 *
1327 * SIGQUIT: ignore
1328 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001329 * SIGHUP (interactive):
1330 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001331 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001332 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1333 * that all pipe members are stopped. Try this in bash:
1334 * while :; do :; done - ^Z does not background it
1335 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001336 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001337 * of the command line, show prompt. NB: ^C does not send SIGINT
1338 * to interactive shell while shell is waiting for a pipe,
1339 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001340 * Example 1: this waits 5 sec, but does not execute ls:
1341 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1342 * Example 2: this does not wait and does not execute ls:
1343 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1344 * Example 3: this does not wait 5 sec, but executes ls:
1345 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001346 * Example 4: this does not wait and does not execute ls:
1347 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001348 *
1349 * (What happens to signals which are IGN on shell start?)
1350 * (What happens with signal mask on shell start?)
1351 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001352 * Old implementation
1353 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001354 * We use in-kernel pending signal mask to determine which signals were sent.
1355 * We block all signals which we don't want to take action immediately,
1356 * i.e. we block all signals which need to have special handling as described
1357 * above, and all signals which have traps set.
1358 * After each pipe execution, we extract any pending signals via sigtimedwait()
1359 * and act on them.
1360 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001361 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001362 * sigset_t blocked_set: current blocked signal set
1363 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001364 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001365 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001366 * "trap 'cmd' SIGxxx":
1367 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001368 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001369 * unblock signals with special interactive handling
1370 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001371 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001372 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001373 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001374 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001375 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001376 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001377 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001378 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001379 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001380 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001381 * Standard says "When a subshell is entered, traps that are not being ignored
1382 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001383 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001384 *
1385 * Problem: the above approach makes it unwieldy to catch signals while
1386 * we are in read builtin, of while we read commands from stdin:
1387 * masked signals are not visible!
1388 *
1389 * New implementation
1390 * ==================
1391 * We record each signal we are interested in by installing signal handler
1392 * for them - a bit like emulating kernel pending signal mask in userspace.
1393 * We are interested in: signals which need to have special handling
1394 * as described above, and all signals which have traps set.
1395 * Signals are rocorded in pending_set.
1396 * After each pipe execution, we extract any pending signals
1397 * and act on them.
1398 *
1399 * unsigned special_sig_mask: a mask of shell-special signals.
1400 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1401 * char *traps[sig] if trap for sig is set (even if it's '').
1402 * sigset_t pending_set: set of sigs we received.
1403 *
1404 * "trap - SIGxxx":
1405 * if sig is in special_sig_mask, set handler back to:
1406 * record_pending_signo, or to IGN if it's a tty stop signal
1407 * if sig is in fatal_sig_mask, set handler back to sigexit.
1408 * else: set handler back to SIG_DFL
1409 * "trap 'cmd' SIGxxx":
1410 * set handler to record_pending_signo.
1411 * "trap '' SIGxxx":
1412 * set handler to SIG_IGN.
1413 * after [v]fork, if we plan to be a shell:
1414 * set signals with special interactive handling to SIG_DFL
1415 * (because child shell is not interactive),
1416 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1417 * after [v]fork, if we plan to exec:
1418 * POSIX says fork clears pending signal mask in child - no need to clear it.
1419 *
1420 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1421 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1422 *
1423 * Note (compat):
1424 * Standard says "When a subshell is entered, traps that are not being ignored
1425 * are set to the default actions". bash interprets it so that traps which
1426 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001427 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001428enum {
1429 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001430 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001431 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001432 | (1 << SIGHUP)
1433 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001434 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001435#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001436 | (1 << SIGTTIN)
1437 | (1 << SIGTTOU)
1438 | (1 << SIGTSTP)
1439#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001440 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001441};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001442
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001443static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001444{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001445 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001446#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001447 if (sig == SIGCHLD) {
1448 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001449//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 +02001450 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001451#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001452}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001453
Denys Vlasenko0806e402011-05-12 23:06:20 +02001454static sighandler_t install_sighandler(int sig, sighandler_t handler)
1455{
1456 struct sigaction old_sa;
1457
1458 /* We could use signal() to install handlers... almost:
1459 * except that we need to mask ALL signals while handlers run.
1460 * I saw signal nesting in strace, race window isn't small.
1461 * SA_RESTART is also needed, but in Linux, signal()
1462 * sets SA_RESTART too.
1463 */
1464 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1465 /* sigfillset(&G.sa.sa_mask); - already done */
1466 /* G.sa.sa_flags = SA_RESTART; - already done */
1467 G.sa.sa_handler = handler;
1468 sigaction(sig, &G.sa, &old_sa);
1469 return old_sa.sa_handler;
1470}
1471
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001472#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001473
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001474/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001475# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001476/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001477# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001478
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001479/* Restores tty foreground process group, and exits.
1480 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001481 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001482 * or called directly with -EXITCODE.
1483 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001484static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001485static void sigexit(int sig)
1486{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001487 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001488 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001489 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1490 /* Disable all signals: job control, SIGPIPE, etc.
1491 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1492 */
1493 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001494 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001495 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001496
1497 /* Not a signal, just exit */
1498 if (sig <= 0)
1499 _exit(- sig);
1500
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001501 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001502}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001503#else
1504
Denys Vlasenko8391c482010-05-22 17:50:43 +02001505# define disable_restore_tty_pgrp_on_exit() ((void)0)
1506# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001507
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001508#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001509
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001510static sighandler_t pick_sighandler(unsigned sig)
1511{
1512 sighandler_t handler = SIG_DFL;
1513 if (sig < sizeof(unsigned)*8) {
1514 unsigned sigmask = (1 << sig);
1515
1516#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001517 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001518 if (G_fatal_sig_mask & sigmask)
1519 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001520 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001521#endif
1522 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001523 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001524 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001525 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001526 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001527 * in an endless loop when we try to do some
1528 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001529 */
1530 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1531 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001532 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001533 }
1534 return handler;
1535}
1536
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001537/* Restores tty foreground process group, and exits. */
1538static void hush_exit(int exitcode) NORETURN;
1539static void hush_exit(int exitcode)
1540{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001541#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1542 save_history(G.line_input_state);
1543#endif
1544
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001545 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001546 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001547 char *argv[3];
1548 /* argv[0] is unused */
1549 argv[1] = G.traps[0];
1550 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001551 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001552 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001553 * "trap" will still show it, if executed
1554 * in the handler */
1555 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001556 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001557
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001558#if ENABLE_FEATURE_CLEAN_UP
1559 {
1560 struct variable *cur_var;
1561 if (G.cwd != bb_msg_unknown)
1562 free((char*)G.cwd);
1563 cur_var = G.top_var;
1564 while (cur_var) {
1565 struct variable *tmp = cur_var;
1566 if (!cur_var->max_len)
1567 free(cur_var->varstr);
1568 cur_var = cur_var->next;
1569 free(tmp);
1570 }
1571 }
1572#endif
1573
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001574#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001575 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001576 sigexit(- (exitcode & 0xff));
1577#else
1578 exit(exitcode);
1579#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001580}
1581
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001582
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001583//TODO: return a mask of ALL handled sigs?
1584static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001585{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001586 int last_sig = 0;
1587
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001588 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001589 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001590
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001591 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001592 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001593 sig = 0;
1594 do {
1595 sig++;
1596 if (sigismember(&G.pending_set, sig)) {
1597 sigdelset(&G.pending_set, sig);
1598 goto got_sig;
1599 }
1600 } while (sig < NSIG);
1601 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001602 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001603 if (G.traps && G.traps[sig]) {
1604 if (G.traps[sig][0]) {
1605 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001606 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001607 char *argv[3];
1608 /* argv[0] is unused */
1609 argv[1] = G.traps[sig];
1610 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001611 save_rcode = G.last_exitcode;
1612 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001613 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001614 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001615 } /* else: "" trap, ignoring signal */
1616 continue;
1617 }
1618 /* not a trap: special action */
1619 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001620 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001621 /* Builtin was ^C'ed, make it look prettier: */
1622 bb_putchar('\n');
1623 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001624 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001625 break;
1626#if ENABLE_HUSH_JOB
1627 case SIGHUP: {
1628 struct pipe *job;
1629 /* bash is observed to signal whole process groups,
1630 * not individual processes */
1631 for (job = G.job_list; job; job = job->next) {
1632 if (job->pgrp <= 0)
1633 continue;
1634 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1635 if (kill(- job->pgrp, SIGHUP) == 0)
1636 kill(- job->pgrp, SIGCONT);
1637 }
1638 sigexit(SIGHUP);
1639 }
1640#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001641#if ENABLE_HUSH_FAST
1642 case SIGCHLD:
1643 G.count_SIGCHLD++;
1644//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1645 /* Note:
1646 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1647 * This simplifies wait builtin a bit.
1648 */
1649 break;
1650#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001651 default: /* ignored: */
1652 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001653 /* Note:
1654 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1655 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001656 * in interactive shell, because TERM is ignored.
1657 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001658 break;
1659 }
1660 }
1661 return last_sig;
1662}
1663
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001664
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001665static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001666{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001667 if (force || G.cwd == NULL) {
1668 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1669 * we must not try to free(bb_msg_unknown) */
1670 if (G.cwd == bb_msg_unknown)
1671 G.cwd = NULL;
1672 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1673 if (!G.cwd)
1674 G.cwd = bb_msg_unknown;
1675 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001676 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001677}
1678
Denis Vlasenko83506862007-11-23 13:11:42 +00001679
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001680/*
1681 * Shell and environment variable support
1682 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001683static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001684{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001685 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001686 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001687
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001688 pp = &G.top_var;
1689 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001690 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001691 return pp;
1692 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001693 }
1694 return NULL;
1695}
1696
Denys Vlasenko03dad222010-01-12 23:29:57 +01001697static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001698{
Denys Vlasenko29082232010-07-16 13:52:32 +02001699 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001700 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001701
1702 if (G.expanded_assignments) {
1703 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001704 while (*cpp) {
1705 char *cp = *cpp;
1706 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1707 return cp + len + 1;
1708 cpp++;
1709 }
1710 }
1711
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001712 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001713 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001714 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001715
Denys Vlasenkodea47882009-10-09 15:40:49 +02001716 if (strcmp(name, "PPID") == 0)
1717 return utoa(G.root_ppid);
1718 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001719#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001720 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001721 return utoa(next_random(&G.random_gen));
1722#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001723 return NULL;
1724}
1725
1726/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001727 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001728 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001729 * 0: do not change export flag
1730 * (if creating new variable, flag will be 0)
1731 * 1: set export flag and putenv the variable
1732 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001733 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001734 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001735#if !BB_MMU && ENABLE_HUSH_LOCAL
1736/* all params are used */
1737#elif BB_MMU && ENABLE_HUSH_LOCAL
1738#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1739 set_local_var(str, flg_export, local_lvl)
1740#elif BB_MMU && !ENABLE_HUSH_LOCAL
1741#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001742 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001743#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, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001746#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001747static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001748{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001749 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001750 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001751 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001752 int name_len;
1753
Denis Vlasenko950bd722009-04-21 11:23:56 +00001754 eq_sign = strchr(str, '=');
1755 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001756 free(str);
1757 return -1;
1758 }
1759
Denis Vlasenko950bd722009-04-21 11:23:56 +00001760 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001761 var_pp = &G.top_var;
1762 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001763 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001764 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001765 continue;
1766 }
1767 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001768 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001769#if !BB_MMU
1770 if (!flg_read_only)
1771#endif
1772 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001773 free(str);
1774 return -1;
1775 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001776 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001777 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1778 *eq_sign = '\0';
1779 unsetenv(str);
1780 *eq_sign = '=';
1781 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001782#if ENABLE_HUSH_LOCAL
1783 if (cur->func_nest_level < local_lvl) {
1784 /* New variable is declared as local,
1785 * and existing one is global, or local
1786 * from enclosing function.
1787 * Remove and save old one: */
1788 *var_pp = cur->next;
1789 cur->next = *G.shadowed_vars_pp;
1790 *G.shadowed_vars_pp = cur;
1791 /* bash 3.2.33(1) and exported vars:
1792 * # export z=z
1793 * # f() { local z=a; env | grep ^z; }
1794 * # f
1795 * z=a
1796 * # env | grep ^z
1797 * z=z
1798 */
1799 if (cur->flg_export)
1800 flg_export = 1;
1801 break;
1802 }
1803#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001804 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001805 free_and_exp:
1806 free(str);
1807 goto exp;
1808 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001809 if (cur->max_len != 0) {
1810 if (cur->max_len >= strlen(str)) {
1811 /* This one is from startup env, reuse space */
1812 strcpy(cur->varstr, str);
1813 goto free_and_exp;
1814 }
1815 } else {
1816 /* max_len == 0 signifies "malloced" var, which we can
1817 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001818 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001819 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001820 cur->max_len = 0;
1821 goto set_str_and_exp;
1822 }
1823
Denys Vlasenko295fef82009-06-03 12:47:26 +02001824 /* Not found - create new variable struct */
1825 cur = xzalloc(sizeof(*cur));
1826#if ENABLE_HUSH_LOCAL
1827 cur->func_nest_level = local_lvl;
1828#endif
1829 cur->next = *var_pp;
1830 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001831
1832 set_str_and_exp:
1833 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001834#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001835 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001836#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001837 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001838 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001839 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001840 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1841 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001842 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001843 if (flg_export == -1) {
1844 cur->flg_export = 0;
1845 /* unsetenv was already done */
1846 } else {
1847 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1848 return putenv(cur->varstr);
1849 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001850 }
1851 return 0;
1852}
1853
Denys Vlasenko6db47842009-09-05 20:15:17 +02001854/* Used at startup and after each cd */
1855static void set_pwd_var(int exp)
1856{
1857 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1858 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1859}
1860
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001861static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001862{
1863 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001864 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001865
1866 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001867 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001868 var_pp = &G.top_var;
1869 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001870 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1871 if (cur->flg_read_only) {
1872 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001873 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001874 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001875 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001876 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1877 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001878 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1879 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001880 if (!cur->max_len)
1881 free(cur->varstr);
1882 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001883 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001884 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001885 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001886 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001887 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001888}
1889
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001890static int unset_local_var(const char *name)
1891{
1892 return unset_local_var_len(name, strlen(name));
1893}
1894
1895static void unset_vars(char **strings)
1896{
1897 char **v;
1898
1899 if (!strings)
1900 return;
1901 v = strings;
1902 while (*v) {
1903 const char *eq = strchrnul(*v, '=');
1904 unset_local_var_len(*v, (int)(eq - *v));
1905 v++;
1906 }
1907 free(strings);
1908}
1909
Denys Vlasenko03dad222010-01-12 23:29:57 +01001910static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001911{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001912 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001913 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001914}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001915
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001916
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001917/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001918 * Helpers for "var1=val1 var2=val2 cmd" feature
1919 */
1920static void add_vars(struct variable *var)
1921{
1922 struct variable *next;
1923
1924 while (var) {
1925 next = var->next;
1926 var->next = G.top_var;
1927 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001928 if (var->flg_export) {
1929 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001930 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001931 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001932 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001933 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001934 var = next;
1935 }
1936}
1937
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001938static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001939{
1940 char **s;
1941 struct variable *old = NULL;
1942
1943 if (!strings)
1944 return old;
1945 s = strings;
1946 while (*s) {
1947 struct variable *var_p;
1948 struct variable **var_pp;
1949 char *eq;
1950
1951 eq = strchr(*s, '=');
1952 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001953 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001954 if (var_pp) {
1955 /* Remove variable from global linked list */
1956 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001957 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001958 *var_pp = var_p->next;
1959 /* Add it to returned list */
1960 var_p->next = old;
1961 old = var_p;
1962 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001963 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001964 }
1965 s++;
1966 }
1967 return old;
1968}
1969
1970
1971/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001972 * in_str support
1973 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001974static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001975{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001976 int ch = *i->p;
1977 if (ch != '\0') {
1978 i->p++;
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001979 i->last_char = ch;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001980 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001981 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001982 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001983}
1984
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001985static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001986{
1987 return *i->p;
1988}
1989
1990#if ENABLE_HUSH_INTERACTIVE
1991
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001992static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001993{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001994 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001995 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001996 if (G.PS1 == NULL)
1997 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001998 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001999 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002000 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002001 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002002 if (G.PS2 == NULL)
2003 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002004}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002005
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002006static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002007{
2008 const char *prompt_str;
2009 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002010 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2011 /* Set up the prompt */
2012 if (promptmode == 0) { /* PS1 */
2013 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002014 /* bash uses $PWD value, even if it is set by user.
2015 * It uses current dir only if PWD is unset.
2016 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002017 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002018 prompt_str = G.PS1;
2019 } else
2020 prompt_str = G.PS2;
2021 } else
2022 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002023 debug_printf("result '%s'\n", prompt_str);
2024 return prompt_str;
2025}
2026
2027static void get_user_input(struct in_str *i)
2028{
2029 int r;
2030 const char *prompt_str;
2031
2032 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002033# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002034 /* Enable command line editing only while a command line
2035 * is actually being read */
2036 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01002037 /* Unicode support should be activated even if LANG is set
2038 * _during_ shell execution, not only if it was set when
2039 * shell was started. Therefore, re-check LANG every time:
2040 */
2041 reinit_unicode(get_local_var_value("LANG"));
2042
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002043 G.flag_SIGINT = 0;
2044 /* buglet: SIGINT will not make new prompt to appear _at once_,
2045 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002046 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 +00002047 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002048 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002049 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002050 i->eof_flag = (r < 0);
2051 if (i->eof_flag) { /* EOF/error detected */
2052 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2053 G.user_input_buf[1] = '\0';
2054 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02002055# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002056 do {
2057 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002058 if (i->last_char == '\0' || i->last_char == '\n') {
2059 /* Why check_and_run_traps here? Try this interactively:
2060 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2061 * $ <[enter], repeatedly...>
2062 * Without check_and_run_traps, handler never runs.
2063 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002064 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002065 fputs(prompt_str, stdout);
2066 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002067 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002068 G.user_input_buf[0] = r = fgetc(i->file);
2069 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002070 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002071 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002072# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002073 i->p = G.user_input_buf;
2074}
2075
2076#endif /* INTERACTIVE */
2077
2078/* This is the magic location that prints prompts
2079 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002080static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002081{
2082 int ch;
2083
2084 /* If there is data waiting, eat it up */
2085 if (i->p && *i->p) {
2086#if ENABLE_HUSH_INTERACTIVE
2087 take_cached:
2088#endif
2089 ch = *i->p++;
2090 if (i->eof_flag && !*i->p)
2091 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002092 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002093 } else {
2094 /* need to double check i->file because we might be doing something
2095 * more complicated by now, like sourcing or substituting. */
2096#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002097 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002098 do {
2099 get_user_input(i);
2100 } while (!*i->p); /* need non-empty line */
2101 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002102 goto take_cached;
2103 }
2104#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00002105 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002106 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002107 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002108 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002109 return ch;
2110}
2111
Denis Vlasenko913a2012009-04-05 22:17:04 +00002112/* All callers guarantee this routine will never
2113 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002114 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002115static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002116{
2117 int ch;
2118 if (i->p && *i->p) {
2119 if (i->eof_flag && !i->p[1])
2120 return EOF;
2121 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002122 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002123 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002124 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002125 i->eof_flag = (ch == EOF);
2126 i->peek_buf[0] = ch;
2127 i->peek_buf[1] = '\0';
2128 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002129 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002130 return ch;
2131}
2132
2133static void setup_file_in_str(struct in_str *i, FILE *f)
2134{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002135 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002136 i->peek = file_peek;
2137 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002138 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002139 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002140 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002141}
2142
2143static void setup_string_in_str(struct in_str *i, const char *s)
2144{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002145 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002146 i->peek = static_peek;
2147 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002148 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002149 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002150 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002151}
2152
2153
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002154/*
2155 * o_string support
2156 */
2157#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002158
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002159static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002160{
2161 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002162 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002163 if (o->data)
2164 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002165}
2166
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002167static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002168{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002169 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002170 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002171}
2172
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002173static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2174{
2175 free(o->data);
2176}
2177
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002178static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002179{
2180 if (o->length + len > o->maxlen) {
2181 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2182 o->data = xrealloc(o->data, 1 + o->maxlen);
2183 }
2184}
2185
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002186static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002187{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002188 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2189 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002190 o->data[o->length] = ch;
2191 o->length++;
2192 o->data[o->length] = '\0';
2193}
2194
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002195static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002196{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002197 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002198 memcpy(&o->data[o->length], str, len);
2199 o->length += len;
2200 o->data[o->length] = '\0';
2201}
2202
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002203static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002204{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002205 o_addblock(o, str, strlen(str));
2206}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002207
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002208#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002209static void nommu_addchr(o_string *o, int ch)
2210{
2211 if (o)
2212 o_addchr(o, ch);
2213}
2214#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002215# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002216#endif
2217
2218static void o_addstr_with_NUL(o_string *o, const char *str)
2219{
2220 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002221}
2222
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002223/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002224 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002225 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2226 * Apparently, on unquoted $v bash still does globbing
2227 * ("v='*.txt'; echo $v" prints all .txt files),
2228 * but NOT brace expansion! Thus, there should be TWO independent
2229 * quoting mechanisms on $v expansion side: one protects
2230 * $v from brace expansion, and other additionally protects "$v" against globbing.
2231 * We have only second one.
2232 */
2233
Denys Vlasenko9e800222010-10-03 14:28:04 +02002234#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002235# define MAYBE_BRACES "{}"
2236#else
2237# define MAYBE_BRACES ""
2238#endif
2239
Eric Andersen25f27032001-04-26 23:22:31 +00002240/* My analysis of quoting semantics tells me that state information
2241 * is associated with a destination, not a source.
2242 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002243static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002244{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002245 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002246 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002247 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002248 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002249 o_grow_by(o, sz);
2250 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002251 o->data[o->length] = '\\';
2252 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002253 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002254 o->data[o->length] = ch;
2255 o->length++;
2256 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002257}
2258
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002259static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002260{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002261 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002262 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2263 && strchr("*?[\\" MAYBE_BRACES, ch)
2264 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002265 sz++;
2266 o->data[o->length] = '\\';
2267 o->length++;
2268 }
2269 o_grow_by(o, sz);
2270 o->data[o->length] = ch;
2271 o->length++;
2272 o->data[o->length] = '\0';
2273}
2274
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002275static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002276{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002277 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002278 char ch;
2279 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002280 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002281 if (ordinary_cnt > len) /* paranoia */
2282 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002283 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002284 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002285 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002286 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002287 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002288
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002289 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002290 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002291 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002292 sz++;
2293 o->data[o->length] = '\\';
2294 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002295 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002296 o_grow_by(o, sz);
2297 o->data[o->length] = ch;
2298 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002299 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002300 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002301}
2302
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002303static void o_addQblock(o_string *o, const char *str, int len)
2304{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002305 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002306 o_addblock(o, str, len);
2307 return;
2308 }
2309 o_addqblock(o, str, len);
2310}
2311
Denys Vlasenko38292b62010-09-05 14:49:40 +02002312static void o_addQstr(o_string *o, const char *str)
2313{
2314 o_addQblock(o, str, strlen(str));
2315}
2316
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002317/* A special kind of o_string for $VAR and `cmd` expansion.
2318 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002319 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002320 * list[i] contains an INDEX (int!) into this string data.
2321 * It means that if list[] needs to grow, data needs to be moved higher up
2322 * but list[i]'s need not be modified.
2323 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002324 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002325 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2326 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002327#if DEBUG_EXPAND || DEBUG_GLOB
2328static void debug_print_list(const char *prefix, o_string *o, int n)
2329{
2330 char **list = (char**)o->data;
2331 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2332 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002333
2334 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002335 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 +02002336 prefix, list, n, string_start, o->length, o->maxlen,
2337 !!(o->o_expflags & EXP_FLAG_GLOB),
2338 o->has_quoted_part,
2339 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002340 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002341 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002342 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2343 o->data + (int)(uintptr_t)list[i] + string_start,
2344 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002345 i++;
2346 }
2347 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002348 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002349 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002350 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002351 }
2352}
2353#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002354# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002355#endif
2356
2357/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2358 * in list[n] so that it points past last stored byte so far.
2359 * It returns n+1. */
2360static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002361{
2362 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002363 int string_start;
2364 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002365
2366 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002367 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2368 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002369 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002370 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002371 /* list[n] points to string_start, make space for 16 more pointers */
2372 o->maxlen += 0x10 * sizeof(list[0]);
2373 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002374 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002375 memmove(list + n + 0x10, list + n, string_len);
2376 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002377 } else {
2378 debug_printf_list("list[%d]=%d string_start=%d\n",
2379 n, string_len, string_start);
2380 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002381 } else {
2382 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002383 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2384 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002385 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2386 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002387 o->has_empty_slot = 0;
2388 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002389 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002390 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002391 return n + 1;
2392}
2393
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002394/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002395static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002396{
2397 char **list = (char**)o->data;
2398 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2399
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002400 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002401}
2402
Denys Vlasenko9e800222010-10-03 14:28:04 +02002403#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002404/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2405 * first, it processes even {a} (no commas), second,
2406 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002407 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002408 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002409
2410/* Helper */
2411static int glob_needed(const char *s)
2412{
2413 while (*s) {
2414 if (*s == '\\') {
2415 if (!s[1])
2416 return 0;
2417 s += 2;
2418 continue;
2419 }
2420 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2421 return 1;
2422 s++;
2423 }
2424 return 0;
2425}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002426/* Return pointer to next closing brace or to comma */
2427static const char *next_brace_sub(const char *cp)
2428{
2429 unsigned depth = 0;
2430 cp++;
2431 while (*cp != '\0') {
2432 if (*cp == '\\') {
2433 if (*++cp == '\0')
2434 break;
2435 cp++;
2436 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002437 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002438 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002439 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002440 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002441 depth++;
2442 }
2443
2444 return *cp != '\0' ? cp : NULL;
2445}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002446/* Recursive brace globber. Note: may garble pattern[]. */
2447static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002448{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002449 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002450 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002451 const char *next;
2452 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002453 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002454 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002455
2456 debug_printf_glob("glob_brace('%s')\n", pattern);
2457
2458 begin = pattern;
2459 while (1) {
2460 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002461 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002462 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002463 /* Find the first sub-pattern and at the same time
2464 * find the rest after the closing brace */
2465 next = next_brace_sub(begin);
2466 if (next == NULL) {
2467 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002468 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002469 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002470 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002471 /* "{abc}" with no commas - illegal
2472 * brace expr, disregard and skip it */
2473 begin = next + 1;
2474 continue;
2475 }
2476 break;
2477 }
2478 if (*begin == '\\' && begin[1] != '\0')
2479 begin++;
2480 begin++;
2481 }
2482 debug_printf_glob("begin:%s\n", begin);
2483 debug_printf_glob("next:%s\n", next);
2484
2485 /* Now find the end of the whole brace expression */
2486 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002487 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002488 rest = next_brace_sub(rest);
2489 if (rest == NULL) {
2490 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002491 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002492 }
2493 debug_printf_glob("rest:%s\n", rest);
2494 }
2495 rest_len = strlen(++rest) + 1;
2496
2497 /* We are sure the brace expression is well-formed */
2498
2499 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002500 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002501
2502 /* We have a brace expression. BEGIN points to the opening {,
2503 * NEXT points past the terminator of the first element, and REST
2504 * points past the final }. We will accumulate result names from
2505 * recursive runs for each brace alternative in the buffer using
2506 * GLOB_APPEND. */
2507
2508 p = begin + 1;
2509 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002510 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002511 memcpy(
2512 mempcpy(
2513 mempcpy(new_pattern_buf,
2514 /* We know the prefix for all sub-patterns */
2515 pattern, begin - pattern),
2516 p, next - p),
2517 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002518
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002519 /* Note: glob_brace() may garble new_pattern_buf[].
2520 * That's why we re-copy prefix every time (1st memcpy above).
2521 */
2522 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002523 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002524 /* We saw the last entry */
2525 break;
2526 }
2527 p = next + 1;
2528 next = next_brace_sub(next);
2529 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002530 free(new_pattern_buf);
2531 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002532
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002533 simple_glob:
2534 {
2535 int gr;
2536 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002537
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002538 memset(&globdata, 0, sizeof(globdata));
2539 gr = glob(pattern, 0, NULL, &globdata);
2540 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2541 if (gr != 0) {
2542 if (gr == GLOB_NOMATCH) {
2543 globfree(&globdata);
2544 /* NB: garbles parameter */
2545 unbackslash(pattern);
2546 o_addstr_with_NUL(o, pattern);
2547 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2548 return o_save_ptr_helper(o, n);
2549 }
2550 if (gr == GLOB_NOSPACE)
2551 bb_error_msg_and_die(bb_msg_memory_exhausted);
2552 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2553 * but we didn't specify it. Paranoia again. */
2554 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2555 }
2556 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2557 char **argv = globdata.gl_pathv;
2558 while (1) {
2559 o_addstr_with_NUL(o, *argv);
2560 n = o_save_ptr_helper(o, n);
2561 argv++;
2562 if (!*argv)
2563 break;
2564 }
2565 }
2566 globfree(&globdata);
2567 }
2568 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002569}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002570/* Performs globbing on last list[],
2571 * saving each result as a new list[].
2572 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002573static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002574{
2575 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002576
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002577 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002578 if (!o->data)
2579 return o_save_ptr_helper(o, n);
2580 pattern = o->data + o_get_last_ptr(o, n);
2581 debug_printf_glob("glob pattern '%s'\n", pattern);
2582 if (!glob_needed(pattern)) {
2583 /* unbackslash last string in o in place, fix length */
2584 o->length = unbackslash(pattern) - o->data;
2585 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2586 return o_save_ptr_helper(o, n);
2587 }
2588
2589 copy = xstrdup(pattern);
2590 /* "forget" pattern in o */
2591 o->length = pattern - o->data;
2592 n = glob_brace(copy, o, n);
2593 free(copy);
2594 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002595 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002596 return n;
2597}
2598
Denys Vlasenko238081f2010-10-03 14:26:26 +02002599#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002600
2601/* Helper */
2602static int glob_needed(const char *s)
2603{
2604 while (*s) {
2605 if (*s == '\\') {
2606 if (!s[1])
2607 return 0;
2608 s += 2;
2609 continue;
2610 }
2611 if (*s == '*' || *s == '[' || *s == '?')
2612 return 1;
2613 s++;
2614 }
2615 return 0;
2616}
2617/* Performs globbing on last list[],
2618 * saving each result as a new list[].
2619 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002620static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002621{
2622 glob_t globdata;
2623 int gr;
2624 char *pattern;
2625
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002626 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002627 if (!o->data)
2628 return o_save_ptr_helper(o, n);
2629 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002630 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002631 if (!glob_needed(pattern)) {
2632 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002633 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002634 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002635 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002636 return o_save_ptr_helper(o, n);
2637 }
2638
2639 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002640 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2641 * If we glob "*.\*" and don't find anything, we need
2642 * to fall back to using literal "*.*", but GLOB_NOCHECK
2643 * will return "*.\*"!
2644 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002645 gr = glob(pattern, 0, NULL, &globdata);
2646 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002647 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002648 if (gr == GLOB_NOMATCH) {
2649 globfree(&globdata);
2650 goto literal;
2651 }
2652 if (gr == GLOB_NOSPACE)
2653 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002654 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2655 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002656 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002657 }
2658 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2659 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002660 /* "forget" pattern in o */
2661 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002662 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002663 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002664 n = o_save_ptr_helper(o, n);
2665 argv++;
2666 if (!*argv)
2667 break;
2668 }
2669 }
2670 globfree(&globdata);
2671 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002672 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002673 return n;
2674}
2675
Denys Vlasenko238081f2010-10-03 14:26:26 +02002676#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002677
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002678/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002679 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002680static int o_save_ptr(o_string *o, int n)
2681{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002682 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002683 /* If o->has_empty_slot, list[n] was already globbed
2684 * (if it was requested back then when it was filled)
2685 * so don't do that again! */
2686 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002687 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002688 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002689 return o_save_ptr_helper(o, n);
2690}
2691
2692/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002693static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002694{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002695 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002696 int string_start;
2697
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002698 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2699 if (DEBUG_EXPAND)
2700 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002701 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002702 list = (char**)o->data;
2703 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2704 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002705 while (n) {
2706 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002707 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002708 }
2709 return list;
2710}
2711
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002712static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002713
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002714/* Returns pi->next - next pipe in the list */
2715static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002716{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002717 struct pipe *next;
2718 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002719
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002720 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002721 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002722 struct command *command;
2723 struct redir_struct *r, *rnext;
2724
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002725 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002726 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002727 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002728 if (DEBUG_CLEAN) {
2729 int a;
2730 char **p;
2731 for (a = 0, p = command->argv; *p; a++, p++) {
2732 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2733 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002734 }
2735 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002736 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002737 }
2738 /* not "else if": on syntax error, we may have both! */
2739 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002740 debug_printf_clean(" begin group (cmd_type:%d)\n",
2741 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002742 free_pipe_list(command->group);
2743 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002744 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002745 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002746 /* else is crucial here.
2747 * If group != NULL, child_func is meaningless */
2748#if ENABLE_HUSH_FUNCTIONS
2749 else if (command->child_func) {
2750 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2751 command->child_func->parent_cmd = NULL;
2752 }
2753#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002754#if !BB_MMU
2755 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002756 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002757#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002758 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002759 debug_printf_clean(" redirect %d%s",
2760 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002761 /* guard against the case >$FOO, where foo is unset or blank */
2762 if (r->rd_filename) {
2763 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2764 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002765 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002766 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002767 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002768 rnext = r->next;
2769 free(r);
2770 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002771 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002772 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002773 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002774 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002775#if ENABLE_HUSH_JOB
2776 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002777 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002778#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002779
2780 next = pi->next;
2781 free(pi);
2782 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002783}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002784
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002785static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002786{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002787 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002788#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002789 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002790#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002791 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002792 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002793 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002794}
2795
2796
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002797/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002798
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002799#ifndef debug_print_tree
2800static void debug_print_tree(struct pipe *pi, int lvl)
2801{
2802 static const char *const PIPE[] = {
2803 [PIPE_SEQ] = "SEQ",
2804 [PIPE_AND] = "AND",
2805 [PIPE_OR ] = "OR" ,
2806 [PIPE_BG ] = "BG" ,
2807 };
2808 static const char *RES[] = {
2809 [RES_NONE ] = "NONE" ,
2810# if ENABLE_HUSH_IF
2811 [RES_IF ] = "IF" ,
2812 [RES_THEN ] = "THEN" ,
2813 [RES_ELIF ] = "ELIF" ,
2814 [RES_ELSE ] = "ELSE" ,
2815 [RES_FI ] = "FI" ,
2816# endif
2817# if ENABLE_HUSH_LOOPS
2818 [RES_FOR ] = "FOR" ,
2819 [RES_WHILE] = "WHILE",
2820 [RES_UNTIL] = "UNTIL",
2821 [RES_DO ] = "DO" ,
2822 [RES_DONE ] = "DONE" ,
2823# endif
2824# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2825 [RES_IN ] = "IN" ,
2826# endif
2827# if ENABLE_HUSH_CASE
2828 [RES_CASE ] = "CASE" ,
2829 [RES_CASE_IN ] = "CASE_IN" ,
2830 [RES_MATCH] = "MATCH",
2831 [RES_CASE_BODY] = "CASE_BODY",
2832 [RES_ESAC ] = "ESAC" ,
2833# endif
2834 [RES_XXXX ] = "XXXX" ,
2835 [RES_SNTX ] = "SNTX" ,
2836 };
2837 static const char *const CMDTYPE[] = {
2838 "{}",
2839 "()",
2840 "[noglob]",
2841# if ENABLE_HUSH_FUNCTIONS
2842 "func()",
2843# endif
2844 };
2845
2846 int pin, prn;
2847
2848 pin = 0;
2849 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002850 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002851 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2852 prn = 0;
2853 while (prn < pi->num_cmds) {
2854 struct command *command = &pi->cmds[prn];
2855 char **argv = command->argv;
2856
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002857 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002858 lvl*2, "", prn,
2859 command->assignment_cnt);
2860 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002861 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002862 CMDTYPE[command->cmd_type],
2863 argv
2864# if !BB_MMU
2865 , " group_as_string:", command->group_as_string
2866# else
2867 , "", ""
2868# endif
2869 );
2870 debug_print_tree(command->group, lvl+1);
2871 prn++;
2872 continue;
2873 }
2874 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002875 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002876 argv++;
2877 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002878 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002879 prn++;
2880 }
2881 pi = pi->next;
2882 pin++;
2883 }
2884}
2885#endif /* debug_print_tree */
2886
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002887static struct pipe *new_pipe(void)
2888{
Eric Andersen25f27032001-04-26 23:22:31 +00002889 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002890 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002891 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002892 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002893 return pi;
2894}
2895
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002896/* Command (member of a pipe) is complete, or we start a new pipe
2897 * if ctx->command is NULL.
2898 * No errors possible here.
2899 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002900static int done_command(struct parse_context *ctx)
2901{
2902 /* The command is really already in the pipe structure, so
2903 * advance the pipe counter and make a new, null command. */
2904 struct pipe *pi = ctx->pipe;
2905 struct command *command = ctx->command;
2906
2907 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002908 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002909 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002910 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002911 }
2912 pi->num_cmds++;
2913 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002914 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002915 } else {
2916 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2917 }
2918
2919 /* Only real trickiness here is that the uncommitted
2920 * command structure is not counted in pi->num_cmds. */
2921 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002922 ctx->command = command = &pi->cmds[pi->num_cmds];
2923 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002924 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002925 return pi->num_cmds; /* used only for 0/nonzero check */
2926}
2927
2928static void done_pipe(struct parse_context *ctx, pipe_style type)
2929{
2930 int not_null;
2931
2932 debug_printf_parse("done_pipe entered, followup %d\n", type);
2933 /* Close previous command */
2934 not_null = done_command(ctx);
2935 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002936#if HAS_KEYWORDS
2937 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2938 ctx->ctx_inverted = 0;
2939 ctx->pipe->res_word = ctx->ctx_res_w;
2940#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002941
2942 /* Without this check, even just <enter> on command line generates
2943 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002944 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002945 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002946#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002947 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002948#endif
2949#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002950 || ctx->ctx_res_w == RES_DONE
2951 || ctx->ctx_res_w == RES_FOR
2952 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002953#endif
2954#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002955 || ctx->ctx_res_w == RES_ESAC
2956#endif
2957 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002958 struct pipe *new_p;
2959 debug_printf_parse("done_pipe: adding new pipe: "
2960 "not_null:%d ctx->ctx_res_w:%d\n",
2961 not_null, ctx->ctx_res_w);
2962 new_p = new_pipe();
2963 ctx->pipe->next = new_p;
2964 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002965 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002966 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002967 * This is used to control execution.
2968 * RES_FOR and RES_IN are NOT sticky (needed to support
2969 * cases where variable or value happens to match a keyword):
2970 */
2971#if ENABLE_HUSH_LOOPS
2972 if (ctx->ctx_res_w == RES_FOR
2973 || ctx->ctx_res_w == RES_IN)
2974 ctx->ctx_res_w = RES_NONE;
2975#endif
2976#if ENABLE_HUSH_CASE
2977 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002978 ctx->ctx_res_w = RES_CASE_BODY;
2979 if (ctx->ctx_res_w == RES_CASE)
2980 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002981#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002982 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002983 /* Create the memory for command, roughly:
2984 * ctx->pipe->cmds = new struct command;
2985 * ctx->command = &ctx->pipe->cmds[0];
2986 */
2987 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002988 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002989 }
2990 debug_printf_parse("done_pipe return\n");
2991}
2992
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002993static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002994{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002995 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002996 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002997 /* Create the memory for command, roughly:
2998 * ctx->pipe->cmds = new struct command;
2999 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003000 */
3001 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003002}
3003
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003004/* If a reserved word is found and processed, parse context is modified
3005 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003006 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003007#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003008struct reserved_combo {
3009 char literal[6];
3010 unsigned char res;
3011 unsigned char assignment_flag;
3012 int flag;
3013};
3014enum {
3015 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003016# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003017 FLAG_IF = (1 << RES_IF ),
3018 FLAG_THEN = (1 << RES_THEN ),
3019 FLAG_ELIF = (1 << RES_ELIF ),
3020 FLAG_ELSE = (1 << RES_ELSE ),
3021 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003022# endif
3023# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003024 FLAG_FOR = (1 << RES_FOR ),
3025 FLAG_WHILE = (1 << RES_WHILE),
3026 FLAG_UNTIL = (1 << RES_UNTIL),
3027 FLAG_DO = (1 << RES_DO ),
3028 FLAG_DONE = (1 << RES_DONE ),
3029 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003030# endif
3031# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003032 FLAG_MATCH = (1 << RES_MATCH),
3033 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003034# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003035 FLAG_START = (1 << RES_XXXX ),
3036};
3037
3038static const struct reserved_combo* match_reserved_word(o_string *word)
3039{
Eric Andersen25f27032001-04-26 23:22:31 +00003040 /* Mostly a list of accepted follow-up reserved words.
3041 * FLAG_END means we are done with the sequence, and are ready
3042 * to turn the compound list into a command.
3043 * FLAG_START means the word must start a new compound list.
3044 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003045 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003046# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003047 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3048 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3049 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3050 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3051 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3052 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003053# endif
3054# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003055 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3056 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3057 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3058 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3059 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3060 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003061# endif
3062# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003063 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3064 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003065# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003066 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003067 const struct reserved_combo *r;
3068
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003069 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003070 if (strcmp(word->data, r->literal) == 0)
3071 return r;
3072 }
3073 return NULL;
3074}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003075/* Return 0: not a keyword, 1: keyword
3076 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003077static int reserved_word(o_string *word, struct parse_context *ctx)
3078{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003079# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003080 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003081 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003082 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003083# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003084 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003085
Denys Vlasenko38292b62010-09-05 14:49:40 +02003086 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003087 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003088 r = match_reserved_word(word);
3089 if (!r)
3090 return 0;
3091
3092 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003093# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003094 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3095 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003096 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003097 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003098# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003099 if (r->flag == 0) { /* '!' */
3100 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003101 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003102 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003103 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003104 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003105 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003106 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003107 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003108 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003109
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003110 old = xmalloc(sizeof(*old));
3111 debug_printf_parse("push stack %p\n", old);
3112 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003113 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003114 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003115 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003116 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003117 ctx->ctx_res_w = RES_SNTX;
3118 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003119 } else {
3120 /* "{...} fi" is ok. "{...} if" is not
3121 * Example:
3122 * if { echo foo; } then { echo bar; } fi */
3123 if (ctx->command->group)
3124 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003125 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003126
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003127 ctx->ctx_res_w = r->res;
3128 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003129 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003130 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003131
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003132 if (ctx->old_flag & FLAG_END) {
3133 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003134
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003135 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003136 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003137 old = ctx->stack;
3138 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003139 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003140# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003141 o_addstr(&old->as_string, ctx->as_string.data);
3142 o_free_unsafe(&ctx->as_string);
3143 old->command->group_as_string = xstrdup(old->as_string.data);
3144 debug_printf_parse("pop, remembering as:'%s'\n",
3145 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003146# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003147 *ctx = *old; /* physical copy */
3148 free(old);
3149 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003150 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003151}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003152#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003153
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003154/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003155 * Normal return is 0. Syntax errors return 1.
3156 * Note: on return, word is reset, but not o_free'd!
3157 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003158static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003159{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003160 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003161
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003162 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003163 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003164 debug_printf_parse("done_word return 0: true null, ignored\n");
3165 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003166 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003167
Eric Andersen25f27032001-04-26 23:22:31 +00003168 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003169 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3170 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003171 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3172 * "2.7 Redirection
3173 * ...the word that follows the redirection operator
3174 * shall be subjected to tilde expansion, parameter expansion,
3175 * command substitution, arithmetic expansion, and quote
3176 * removal. Pathname expansion shall not be performed
3177 * on the word by a non-interactive shell; an interactive
3178 * shell may perform it, but shall do so only when
3179 * the expansion would result in one word."
3180 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003181 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003182 /* Cater for >\file case:
3183 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3184 * Same with heredocs:
3185 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3186 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003187 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3188 unbackslash(ctx->pending_redirect->rd_filename);
3189 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003190 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003191 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3192 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003193 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003194 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003195 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003196 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003197#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003198# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003199 if (ctx->ctx_dsemicolon
3200 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3201 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003202 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003203 /* ctx->ctx_res_w = RES_MATCH; */
3204 ctx->ctx_dsemicolon = 0;
3205 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003206# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003207 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003208# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003209 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3210 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003211# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003212# if ENABLE_HUSH_CASE
3213 && ctx->ctx_res_w != RES_CASE
3214# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003215 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003216 int reserved = reserved_word(word, ctx);
3217 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3218 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003219 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003220 debug_printf_parse("done_word return %d\n",
3221 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003222 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003223 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003224# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003225 if (strcmp(word->data, "[[") == 0) {
3226 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3227 }
3228 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003229# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003230 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003231#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003232 if (command->group) {
3233 /* "{ echo foo; } echo bar" - bad */
3234 syntax_error_at(word->data);
3235 debug_printf_parse("done_word return 1: syntax error, "
3236 "groups and arglists don't mix\n");
3237 return 1;
3238 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003239
3240 /* If this word wasn't an assignment, next ones definitely
3241 * can't be assignments. Even if they look like ones. */
3242 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3243 && word->o_assignment != WORD_IS_KEYWORD
3244 ) {
3245 word->o_assignment = NOT_ASSIGNMENT;
3246 } else {
3247 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3248 command->assignment_cnt++;
3249 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3250 }
3251 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3252 word->o_assignment = MAYBE_ASSIGNMENT;
3253 }
3254 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3255
Denys Vlasenko38292b62010-09-05 14:49:40 +02003256 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003257 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3258 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003259 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003260 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003261 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003262 char *p = word->data;
3263 while (p[0] == SPECIAL_VAR_SYMBOL
3264 && (p[1] & 0x7f) == '@'
3265 && p[2] == SPECIAL_VAR_SYMBOL
3266 ) {
3267 p += 3;
3268 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003269 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003270 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003271 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003272 }
Eric Andersen25f27032001-04-26 23:22:31 +00003273
Denis Vlasenko06810332007-05-21 23:30:54 +00003274#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003275 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003276 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003277 || !is_well_formed_var_name(command->argv[0], '\0')
3278 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003279 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003280 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003281 return 1;
3282 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003283 /* Force FOR to have just one word (variable name) */
3284 /* NB: basically, this makes hush see "for v in ..."
3285 * syntax as if it is "for v; in ...". FOR and IN become
3286 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003287 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003288 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003289#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003290#if ENABLE_HUSH_CASE
3291 /* Force CASE to have just one word */
3292 if (ctx->ctx_res_w == RES_CASE) {
3293 done_pipe(ctx, PIPE_SEQ);
3294 }
3295#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003296
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003297 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003298
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003299 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003300 return 0;
3301}
3302
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003303
3304/* Peek ahead in the input to find out if we have a "&n" construct,
3305 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003306 * Return:
3307 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3308 * REDIRFD_SYNTAX_ERR if syntax error,
3309 * REDIRFD_TO_FILE if no & was seen,
3310 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003311 */
3312#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003313#define parse_redir_right_fd(as_string, input) \
3314 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003315#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003316static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003317{
3318 int ch, d, ok;
3319
3320 ch = i_peek(input);
3321 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003322 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003323
3324 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003325 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003326 ch = i_peek(input);
3327 if (ch == '-') {
3328 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003329 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003330 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003331 }
3332 d = 0;
3333 ok = 0;
3334 while (ch != EOF && isdigit(ch)) {
3335 d = d*10 + (ch-'0');
3336 ok = 1;
3337 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003338 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003339 ch = i_peek(input);
3340 }
3341 if (ok) return d;
3342
3343//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3344
3345 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003346 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003347}
3348
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003349/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003350 */
3351static int parse_redirect(struct parse_context *ctx,
3352 int fd,
3353 redir_type style,
3354 struct in_str *input)
3355{
3356 struct command *command = ctx->command;
3357 struct redir_struct *redir;
3358 struct redir_struct **redirp;
3359 int dup_num;
3360
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003361 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003362 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003363 /* Check for a '>&1' type redirect */
3364 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3365 if (dup_num == REDIRFD_SYNTAX_ERR)
3366 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003367 } else {
3368 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003369 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003370 if (dup_num) { /* <<-... */
3371 ch = i_getch(input);
3372 nommu_addchr(&ctx->as_string, ch);
3373 ch = i_peek(input);
3374 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003375 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003376
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003377 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003378 int ch = i_peek(input);
3379 if (ch == '|') {
3380 /* >|FILE redirect ("clobbering" >).
3381 * Since we do not support "set -o noclobber" yet,
3382 * >| and > are the same for now. Just eat |.
3383 */
3384 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003385 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003386 }
3387 }
3388
3389 /* Create a new redir_struct and append it to the linked list */
3390 redirp = &command->redirects;
3391 while ((redir = *redirp) != NULL) {
3392 redirp = &(redir->next);
3393 }
3394 *redirp = redir = xzalloc(sizeof(*redir));
3395 /* redir->next = NULL; */
3396 /* redir->rd_filename = NULL; */
3397 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003398 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003399
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003400 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3401 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003402
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003403 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003404 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003405 /* Erik had a check here that the file descriptor in question
3406 * is legit; I postpone that to "run time"
3407 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003408 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3409 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003410 } else {
3411 /* Set ctx->pending_redirect, so we know what to do at the
3412 * end of the next parsed word. */
3413 ctx->pending_redirect = redir;
3414 }
3415 return 0;
3416}
3417
Eric Andersen25f27032001-04-26 23:22:31 +00003418/* If a redirect is immediately preceded by a number, that number is
3419 * supposed to tell which file descriptor to redirect. This routine
3420 * looks for such preceding numbers. In an ideal world this routine
3421 * needs to handle all the following classes of redirects...
3422 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3423 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3424 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3425 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003426 *
3427 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3428 * "2.7 Redirection
3429 * ... If n is quoted, the number shall not be recognized as part of
3430 * the redirection expression. For example:
3431 * echo \2>a
3432 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003433 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003434 *
3435 * A -1 return means no valid number was found,
3436 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003437 */
3438static int redirect_opt_num(o_string *o)
3439{
3440 int num;
3441
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003442 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003443 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003444 num = bb_strtou(o->data, NULL, 10);
3445 if (errno || num < 0)
3446 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003447 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003448 return num;
3449}
3450
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003451#if BB_MMU
3452#define fetch_till_str(as_string, input, word, skip_tabs) \
3453 fetch_till_str(input, word, skip_tabs)
3454#endif
3455static char *fetch_till_str(o_string *as_string,
3456 struct in_str *input,
3457 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003458 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003459{
3460 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003461 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003462 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003463 int ch;
3464
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003465 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003466
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003467 while (1) {
3468 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003469 if (ch != EOF)
3470 nommu_addchr(as_string, ch);
3471 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003472 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3473 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003474 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3475 heredoc.data[past_EOL] = '\0';
3476 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3477 return heredoc.data;
3478 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003479 while (ch == '\n') {
3480 o_addchr(&heredoc, ch);
3481 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003482 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003483 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003484 do {
3485 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003486 if (ch != EOF)
3487 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003488 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003489 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003490 }
3491 if (ch == EOF) {
3492 o_free_unsafe(&heredoc);
3493 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003494 }
3495 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003496 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003497 if (prev == '\\' && ch == '\\')
3498 /* Correctly handle foo\\<eol> (not a line cont.) */
3499 prev = 0; /* not \ */
3500 else
3501 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003502 }
3503}
3504
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003505/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3506 * and load them all. There should be exactly heredoc_cnt of them.
3507 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003508static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3509{
3510 struct pipe *pi = ctx->list_head;
3511
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003512 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003513 int i;
3514 struct command *cmd = pi->cmds;
3515
3516 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3517 pi->num_cmds,
3518 cmd->argv ? cmd->argv[0] : "NONE");
3519 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003520 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003521
3522 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3523 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003524 while (redir) {
3525 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003526 char *p;
3527
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003528 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003529 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003530 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003531 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003532 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003533 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003534 return 1;
3535 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003536 free(redir->rd_filename);
3537 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003538 heredoc_cnt--;
3539 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003540 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003541 }
3542 cmd++;
3543 }
3544 pi = pi->next;
3545 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003546#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003547 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003548 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003549 bb_error_msg_and_die("heredoc BUG 2");
3550#endif
3551 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003552}
3553
3554
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003555static int run_list(struct pipe *pi);
3556#if BB_MMU
3557#define parse_stream(pstring, input, end_trigger) \
3558 parse_stream(input, end_trigger)
3559#endif
3560static struct pipe *parse_stream(char **pstring,
3561 struct in_str *input,
3562 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003563
Eric Andersen25f27032001-04-26 23:22:31 +00003564
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003565#if !ENABLE_HUSH_FUNCTIONS
3566#define parse_group(dest, ctx, input, ch) \
3567 parse_group(ctx, input, ch)
3568#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003569static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003570 struct in_str *input, int ch)
3571{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003572 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003573 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003574 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003575 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003576 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003577 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003578
3579 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003580#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003581 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003582 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003583 if (done_word(dest, ctx))
3584 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003585 if (!command->argv)
3586 goto skip; /* (... */
3587 if (command->argv[1]) { /* word word ... (... */
3588 syntax_error_unexpected_ch('(');
3589 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003590 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003591 /* it is "word(..." or "word (..." */
3592 do
3593 ch = i_getch(input);
3594 while (ch == ' ' || ch == '\t');
3595 if (ch != ')') {
3596 syntax_error_unexpected_ch(ch);
3597 return 1;
3598 }
3599 nommu_addchr(&ctx->as_string, ch);
3600 do
3601 ch = i_getch(input);
3602 while (ch == ' ' || ch == '\t' || ch == '\n');
3603 if (ch != '{') {
3604 syntax_error_unexpected_ch(ch);
3605 return 1;
3606 }
3607 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003608 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003609 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003610 }
3611#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003612
3613#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003614 if (command->argv /* word [word]{... */
3615 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003616 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003617 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003618 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003619 debug_printf_parse("parse_group return 1: "
3620 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003621 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003622 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003623#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003624
3625#if ENABLE_HUSH_FUNCTIONS
3626 skip:
3627#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003628 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003629 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003630 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003631 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003632 } else {
3633 /* bash does not allow "{echo...", requires whitespace */
3634 ch = i_getch(input);
3635 if (ch != ' ' && ch != '\t' && ch != '\n') {
3636 syntax_error_unexpected_ch(ch);
3637 return 1;
3638 }
3639 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003640 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003641
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003642 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003643#if BB_MMU
3644# define as_string NULL
3645#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003646 char *as_string = NULL;
3647#endif
3648 pipe_list = parse_stream(&as_string, input, endch);
3649#if !BB_MMU
3650 if (as_string)
3651 o_addstr(&ctx->as_string, as_string);
3652#endif
3653 /* empty ()/{} or parse error? */
3654 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003655 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003656 if (!BB_MMU)
3657 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003658 debug_printf_parse("parse_group return 1: "
3659 "parse_stream returned %p\n", pipe_list);
3660 return 1;
3661 }
3662 command->group = pipe_list;
3663#if !BB_MMU
3664 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3665 command->group_as_string = as_string;
3666 debug_printf_parse("end of group, remembering as:'%s'\n",
3667 command->group_as_string);
3668#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003669#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003670 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003671 debug_printf_parse("parse_group return 0\n");
3672 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003673 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003674}
3675
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003676#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003677/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003678static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003679/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003680static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003681{
3682 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003683 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003684 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003685 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003686 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003687 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003688 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003689 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003690 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003691 }
3692}
3693/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003694static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003695{
3696 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003697 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003698 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003699 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003700 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003701 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003702 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003703 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003704 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003705 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003706 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003707 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003708 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003709 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003710 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3711 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003712 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003713 continue;
3714 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003715 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003716 }
3717}
3718/* Process `cmd` - copy contents until "`" is seen. Complicated by
3719 * \` quoting.
3720 * "Within the backquoted style of command substitution, backslash
3721 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3722 * The search for the matching backquote shall be satisfied by the first
3723 * backquote found without a preceding backslash; during this search,
3724 * if a non-escaped backquote is encountered within a shell comment,
3725 * a here-document, an embedded command substitution of the $(command)
3726 * form, or a quoted string, undefined results occur. A single-quoted
3727 * or double-quoted string that begins, but does not end, within the
3728 * "`...`" sequence produces undefined results."
3729 * Example Output
3730 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3731 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003732static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003733{
3734 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003735 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003736 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003737 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003738 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003739 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3740 ch = i_getch(input);
3741 if (ch != '`'
3742 && ch != '$'
3743 && ch != '\\'
3744 && (!in_dquote || ch != '"')
3745 ) {
3746 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003747 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003748 }
3749 if (ch == EOF) {
3750 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003751 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003752 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003753 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003754 }
3755}
3756/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3757 * quoting and nested ()s.
3758 * "With the $(command) style of command substitution, all characters
3759 * following the open parenthesis to the matching closing parenthesis
3760 * constitute the command. Any valid shell script can be used for command,
3761 * except a script consisting solely of redirections which produces
3762 * unspecified results."
3763 * Example Output
3764 * echo $(echo '(TEST)' BEST) (TEST) BEST
3765 * echo $(echo 'TEST)' BEST) TEST) BEST
3766 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003767 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003768 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003769 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003770 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3771 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003772 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003773#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003774static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003775{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003776 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003777 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003778# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003779 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003780# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003781 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3782
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003783 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003784 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003785 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003786 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003787 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003788 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003789 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003790 if (!dbl)
3791 break;
3792 /* we look for closing )) of $((EXPR)) */
3793 if (i_peek(input) == end_ch) {
3794 i_getch(input); /* eat second ')' */
3795 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003796 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003797 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003798 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003799 if (ch == '(' || ch == '{') {
3800 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003801 if (!add_till_closing_bracket(dest, input, ch))
3802 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003803 o_addchr(dest, ch);
3804 continue;
3805 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003806 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003807 if (!add_till_single_quote(dest, input))
3808 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003809 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003810 continue;
3811 }
3812 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003813 if (!add_till_double_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 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003818 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003819 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3820 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003821 o_addchr(dest, ch);
3822 continue;
3823 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003824 if (ch == '\\') {
3825 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003826 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003827 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003828 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003829 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003830 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003831 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003832 continue;
3833 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003834 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003835 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003836}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003837#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003838
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003839/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003840#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003841#define parse_dollar(as_string, dest, input, quote_mask) \
3842 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003843#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003844#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003845static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003846 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003847 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003848{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003849 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003850
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003851 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003852 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003853 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003854 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003855 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003856 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003857 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003858 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003859 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003860 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003861 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003862 if (!isalnum(ch) && ch != '_')
3863 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003864 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003865 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003866 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003867 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003868 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003869 make_one_char_var:
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);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003872 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003873 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003874 o_addchr(dest, ch | quote_mask);
3875 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003876 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003877 case '$': /* pid */
3878 case '!': /* last bg pid */
3879 case '?': /* last exit code */
3880 case '#': /* number of args */
3881 case '*': /* args */
3882 case '@': /* args */
3883 goto make_one_char_var;
3884 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003885 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3886
Denys Vlasenko74369502010-05-21 19:52:01 +02003887 ch = i_getch(input); /* eat '{' */
3888 nommu_addchr(as_string, ch);
3889
3890 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003891 /* It should be ${?}, or ${#var},
3892 * or even ${?+subst} - operator acting on a special variable,
3893 * or the beginning of variable name.
3894 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003895 if (ch == EOF
3896 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3897 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003898 bad_dollar_syntax:
3899 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003900 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3901 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02003902 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003903 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003904 ch |= quote_mask;
3905
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003906 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003907 * However, this regresses some of our testsuite cases
3908 * which check invalid constructs like ${%}.
3909 * Oh well... let's check that the var name part is fine... */
3910
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003911 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003912 unsigned pos;
3913
Denys Vlasenko74369502010-05-21 19:52:01 +02003914 o_addchr(dest, ch);
3915 debug_printf_parse(": '%c'\n", ch);
3916
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003917 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003918 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003919 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003920 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003921
Denys Vlasenko74369502010-05-21 19:52:01 +02003922 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003923 unsigned end_ch;
3924 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003925 /* handle parameter expansions
3926 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3927 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003928 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003929 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003930
3931 /* Eat everything until closing '}' (or ':') */
3932 end_ch = '}';
3933 if (ENABLE_HUSH_BASH_COMPAT
3934 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003935 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003936 ) {
3937 /* It's ${var:N[:M]} thing */
3938 end_ch = '}' * 0x100 + ':';
3939 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003940 if (ENABLE_HUSH_BASH_COMPAT
3941 && ch == '/'
3942 ) {
3943 /* It's ${var/[/]pattern[/repl]} thing */
3944 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3945 i_getch(input);
3946 nommu_addchr(as_string, '/');
3947 ch = '\\';
3948 }
3949 end_ch = '}' * 0x100 + '/';
3950 }
3951 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003952 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003953 if (!BB_MMU)
3954 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003955#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003956 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003957 if (last_ch == 0) /* error? */
3958 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003959#else
3960#error Simple code to only allow ${var} is not implemented
3961#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003962 if (as_string) {
3963 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003964 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003965 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003966
3967 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3968 /* close the first block: */
3969 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003970 /* while parsing N from ${var:N[:M]}
3971 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003972 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003973 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003974 end_ch = '}';
3975 goto again;
3976 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003977 /* got '}' */
3978 if (end_ch == '}' * 0x100 + ':') {
3979 /* it's ${var:N} - emulate :999999999 */
3980 o_addstr(dest, "999999999");
3981 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003982 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003983 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003984 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003985 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003986 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3987 break;
3988 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003989#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003990 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003991 unsigned pos;
3992
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003993 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003994 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003995# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003996 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003997 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003998 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003999 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4000 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004001 if (!BB_MMU)
4002 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004003 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4004 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004005 if (as_string) {
4006 o_addstr(as_string, dest->data + pos);
4007 o_addchr(as_string, ')');
4008 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004009 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004010 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004011 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004012 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004013# endif
4014# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004015 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4016 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004017 if (!BB_MMU)
4018 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004019 if (!add_till_closing_bracket(dest, input, ')'))
4020 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004021 if (as_string) {
4022 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004023 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004024 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004025 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004026# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004027 break;
4028 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004029#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004030 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004031 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004032 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004033 ch = i_peek(input);
4034 if (isalnum(ch)) { /* it's $_name or $_123 */
4035 ch = '_';
4036 goto make_var;
4037 }
4038 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004039 /* TODO: $_ and $-: */
4040 /* $_ Shell or shell script name; or last argument of last command
4041 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4042 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004043 /* $- Option flags set by set builtin or shell options (-i etc) */
4044 default:
4045 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004046 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004047 debug_printf_parse("parse_dollar return 1 (ok)\n");
4048 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004049#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004050}
4051
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004052#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004053# if ENABLE_HUSH_BASH_COMPAT
4054#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4055 encode_string(dest, input, dquote_end, process_bkslash)
4056# else
4057/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4058#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4059 encode_string(dest, input, dquote_end)
4060# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004061#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004062
4063#else /* !MMU */
4064
4065# if ENABLE_HUSH_BASH_COMPAT
4066/* all parameters are needed, no macro tricks */
4067# else
4068#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4069 encode_string(as_string, dest, input, dquote_end)
4070# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004071#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004072static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004073 o_string *dest,
4074 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004075 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004076 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004077{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004078#if !ENABLE_HUSH_BASH_COMPAT
4079 const int process_bkslash = 1;
4080#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004081 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004082 int next;
4083
4084 again:
4085 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004086 if (ch != EOF)
4087 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004088 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004089 debug_printf_parse("encode_string return 1 (ok)\n");
4090 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004091 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004092 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004093 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004094 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004095 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004096 }
4097 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004098 if (ch != '\n') {
4099 next = i_peek(input);
4100 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004101 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004102 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004103 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004104 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004105 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004106 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004107 }
4108 /* bash:
4109 * "The backslash retains its special meaning [in "..."]
4110 * only when followed by one of the following characters:
4111 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004112 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004113 * NB: in (unquoted) heredoc, above does not apply to ",
4114 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004115 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004116 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004117 ch = i_getch(input); /* eat next */
4118 if (ch == '\n')
4119 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004120 } /* else: ch remains == '\\', and we double it below: */
4121 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004122 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004123 goto again;
4124 }
4125 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004126 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4127 debug_printf_parse("encode_string return 0: "
4128 "parse_dollar returned 0 (error)\n");
4129 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004130 }
4131 goto again;
4132 }
4133#if ENABLE_HUSH_TICK
4134 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004135 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004136 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4137 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004138 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4139 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004140 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4141 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004142 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004143 }
4144#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004145 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004146 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004147#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004148}
4149
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004150/*
4151 * Scan input until EOF or end_trigger char.
4152 * Return a list of pipes to execute, or NULL on EOF
4153 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004154 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004155 * reset parsing machinery and start parsing anew,
4156 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004157 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004158static struct pipe *parse_stream(char **pstring,
4159 struct in_str *input,
4160 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004161{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004162 struct parse_context ctx;
4163 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004164 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004165
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004166 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004167 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004168 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004169 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004170 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004171 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004172
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004173 /* If very first arg is "" or '', dest.data may end up NULL.
4174 * Preventing this: */
4175 o_addchr(&dest, '\0');
4176 dest.length = 0;
4177
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004178 /* We used to separate words on $IFS here. This was wrong.
4179 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004180 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004181 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004182
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004183 if (MAYBE_ASSIGNMENT != 0)
4184 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004185 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004186 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004187 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004188 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004189 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004190 int ch;
4191 int next;
4192 int redir_fd;
4193 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004194
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004195 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004196 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004197 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004198 if (ch == EOF) {
4199 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004200
4201 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004202 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004203 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004204 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004205 /* end_trigger == '}' case errors out earlier,
4206 * checking only ')' */
4207 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004208 syntax_error_unterm_ch('(');
4209 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004210 }
4211
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004212 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004213 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004214 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004215 o_free(&dest);
4216 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004217 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004218 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004219 /* (this makes bare "&" cmd a no-op.
4220 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004221 if (pi->num_cmds == 0
4222 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4223 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004224 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004225 pi = NULL;
4226 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004227#if !BB_MMU
4228 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4229 if (pstring)
4230 *pstring = ctx.as_string.data;
4231 else
4232 o_free_unsafe(&ctx.as_string);
4233#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004234 debug_leave();
4235 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004236 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004237 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004238 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004239
4240 next = '\0';
4241 if (ch != '\n')
4242 next = i_peek(input);
4243
4244 is_special = "{}<>;&|()#'" /* special outside of "str" */
4245 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4246 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004247 if (ctx.command->argv /* word [word]{... - non-special */
4248 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004249 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004250 || (next != ';' /* }; - special */
4251 && next != ')' /* }) - special */
4252 && next != '&' /* }& and }&& ... - special */
4253 && next != '|' /* }|| ... - special */
4254 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004255 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004256 ) {
4257 /* They are not special, skip "{}" */
4258 is_special += 2;
4259 }
4260 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004261 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004262
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004263 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004264 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004265 o_addQchr(&dest, ch);
4266 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4267 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004268 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004269 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004270 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004271 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004272 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004273 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004274 continue;
4275 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004276
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004277 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004278 if (done_word(&dest, &ctx)) {
4279 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004280 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004281 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004282 /* Is this a case when newline is simply ignored?
4283 * Some examples:
4284 * "cmd | <newline> cmd ..."
4285 * "case ... in <newline> word) ..."
4286 */
4287 if (IS_NULL_CMD(ctx.command)
4288 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004289 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004290 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004291 * Without check #1, interactive shell
4292 * ignores even bare <newline>,
4293 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004294 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004295 * ps2> _ <=== wrong, should be ps1
4296 * Without check #2, "cmd & <newline>"
4297 * is similarly mistreated.
4298 * (BTW, this makes "cmd & cmd"
4299 * and "cmd && cmd" non-orthogonal.
4300 * Really, ask yourself, why
4301 * "cmd && <newline>" doesn't start
4302 * cmd but waits for more input?
4303 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004304 */
4305 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004306 if (pi->num_cmds != 0 /* check #1 */
4307 && pi->followup != PIPE_BG /* check #2 */
4308 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004309 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004310 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004311 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004312 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004313 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004314 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4315 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004316 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004317 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004318 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004319 heredoc_cnt = 0;
4320 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004321 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004322 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004323 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004324 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004325 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004326 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004327 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004328
4329 /* "cmd}" or "cmd }..." without semicolon or &:
4330 * } is an ordinary char in this case, even inside { cmd; }
4331 * Pathological example: { ""}; } should exec "}" cmd
4332 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004333 if (ch == '}') {
4334 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4335 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004336 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004337 ) {
4338 goto ordinary_char;
4339 }
4340 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4341 goto skip_end_trigger;
4342 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004343 }
4344
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004345 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004346 && (ch != ';' || heredoc_cnt == 0)
4347#if ENABLE_HUSH_CASE
4348 && (ch != ')'
4349 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004350 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004351 )
4352#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004353 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004354 if (heredoc_cnt) {
4355 /* This is technically valid:
4356 * { cat <<HERE; }; echo Ok
4357 * heredoc
4358 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004359 * HERE
4360 * but we don't support this.
4361 * We require heredoc to be in enclosing {}/(),
4362 * if any.
4363 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004364 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004365 goto parse_error;
4366 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004367 if (done_word(&dest, &ctx)) {
4368 goto parse_error;
4369 }
4370 done_pipe(&ctx, PIPE_SEQ);
4371 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004372 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004373 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004374 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004375 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004376 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004377 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004378#if !BB_MMU
4379 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4380 if (pstring)
4381 *pstring = ctx.as_string.data;
4382 else
4383 o_free_unsafe(&ctx.as_string);
4384#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004385 debug_leave();
4386 debug_printf_parse("parse_stream return %p: "
4387 "end_trigger char found\n",
4388 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004389 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004390 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004391 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004392 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004393 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004394 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004395
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004396 /* Catch <, > before deciding whether this word is
4397 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4398 switch (ch) {
4399 case '>':
4400 redir_fd = redirect_opt_num(&dest);
4401 if (done_word(&dest, &ctx)) {
4402 goto parse_error;
4403 }
4404 redir_style = REDIRECT_OVERWRITE;
4405 if (next == '>') {
4406 redir_style = REDIRECT_APPEND;
4407 ch = i_getch(input);
4408 nommu_addchr(&ctx.as_string, ch);
4409 }
4410#if 0
4411 else if (next == '(') {
4412 syntax_error(">(process) not supported");
4413 goto parse_error;
4414 }
4415#endif
4416 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4417 goto parse_error;
4418 continue; /* back to top of while (1) */
4419 case '<':
4420 redir_fd = redirect_opt_num(&dest);
4421 if (done_word(&dest, &ctx)) {
4422 goto parse_error;
4423 }
4424 redir_style = REDIRECT_INPUT;
4425 if (next == '<') {
4426 redir_style = REDIRECT_HEREDOC;
4427 heredoc_cnt++;
4428 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4429 ch = i_getch(input);
4430 nommu_addchr(&ctx.as_string, ch);
4431 } else if (next == '>') {
4432 redir_style = REDIRECT_IO;
4433 ch = i_getch(input);
4434 nommu_addchr(&ctx.as_string, ch);
4435 }
4436#if 0
4437 else if (next == '(') {
4438 syntax_error("<(process) not supported");
4439 goto parse_error;
4440 }
4441#endif
4442 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4443 goto parse_error;
4444 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004445 case '#':
4446 if (dest.length == 0 && !dest.has_quoted_part) {
4447 /* skip "#comment" */
4448 while (1) {
4449 ch = i_peek(input);
4450 if (ch == EOF || ch == '\n')
4451 break;
4452 i_getch(input);
4453 /* note: we do not add it to &ctx.as_string */
4454 }
4455 nommu_addchr(&ctx.as_string, '\n');
4456 continue; /* back to top of while (1) */
4457 }
4458 break;
4459 case '\\':
4460 if (next == '\n') {
4461 /* It's "\<newline>" */
4462#if !BB_MMU
4463 /* Remove trailing '\' from ctx.as_string */
4464 ctx.as_string.data[--ctx.as_string.length] = '\0';
4465#endif
4466 ch = i_getch(input); /* eat it */
4467 continue; /* back to top of while (1) */
4468 }
4469 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004470 }
4471
4472 if (dest.o_assignment == MAYBE_ASSIGNMENT
4473 /* check that we are not in word in "a=1 2>word b=1": */
4474 && !ctx.pending_redirect
4475 ) {
4476 /* ch is a special char and thus this word
4477 * cannot be an assignment */
4478 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004479 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004480 }
4481
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004482 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4483
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004484 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004485 case '#': /* non-comment #: "echo a#b" etc */
4486 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004487 break;
4488 case '\\':
4489 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004490 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004491 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004492 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004493 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004494 /* note: ch != '\n' (that case does not reach this place) */
4495 o_addchr(&dest, '\\');
4496 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4497 o_addchr(&dest, ch);
4498 nommu_addchr(&ctx.as_string, ch);
4499 /* Example: echo Hello \2>file
4500 * we need to know that word 2 is quoted */
4501 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004502 break;
4503 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004504 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004505 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004506 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004507 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004508 }
Eric Andersen25f27032001-04-26 23:22:31 +00004509 break;
4510 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004511 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004512 if (next == '\'' && !ctx.pending_redirect) {
4513 insert_empty_quoted_str_marker:
4514 nommu_addchr(&ctx.as_string, next);
4515 i_getch(input); /* eat second ' */
4516 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4517 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4518 } else {
4519 while (1) {
4520 ch = i_getch(input);
4521 if (ch == EOF) {
4522 syntax_error_unterm_ch('\'');
4523 goto parse_error;
4524 }
4525 nommu_addchr(&ctx.as_string, ch);
4526 if (ch == '\'')
4527 break;
4528 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004529 }
Eric Andersen25f27032001-04-26 23:22:31 +00004530 }
Eric Andersen25f27032001-04-26 23:22:31 +00004531 break;
4532 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004533 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004534 if (next == '"' && !ctx.pending_redirect)
4535 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004536 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004537 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004538 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004539 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004540 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004541 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004542#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004543 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004544 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004545
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004546 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4547 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004548 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004549 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4550 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004551# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004552 o_addstr(&ctx.as_string, dest.data + pos);
4553 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004554# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004555 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4556 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004557 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004558 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004559#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004560 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004561#if ENABLE_HUSH_CASE
4562 case_semi:
4563#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004564 if (done_word(&dest, &ctx)) {
4565 goto parse_error;
4566 }
4567 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004568#if ENABLE_HUSH_CASE
4569 /* Eat multiple semicolons, detect
4570 * whether it means something special */
4571 while (1) {
4572 ch = i_peek(input);
4573 if (ch != ';')
4574 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004575 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004576 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004577 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004578 ctx.ctx_dsemicolon = 1;
4579 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004580 break;
4581 }
4582 }
4583#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004584 new_cmd:
4585 /* We just finished a cmd. New one may start
4586 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004587 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004588 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004589 break;
4590 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004591 if (done_word(&dest, &ctx)) {
4592 goto parse_error;
4593 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004594 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004595 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004596 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004597 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004598 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004599 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004600 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004601 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004602 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004603 if (done_word(&dest, &ctx)) {
4604 goto parse_error;
4605 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004606#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004607 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004608 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004609#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004610 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004611 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004612 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004613 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004614 } else {
4615 /* we could pick up a file descriptor choice here
4616 * with redirect_opt_num(), but bash doesn't do it.
4617 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004618 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004619#if !BB_MMU
4620 o_reset_to_empty_unquoted(&ctx.as_string);
4621#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004622 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004623 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004624 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004625#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004626 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004627 if (ctx.ctx_res_w == RES_MATCH
4628 && ctx.command->argv == NULL /* not (word|(... */
4629 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004630 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004631 ) {
4632 continue;
4633 }
4634#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004635 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004636 if (parse_group(&dest, &ctx, input, ch) != 0) {
4637 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004638 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004639 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004640 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004641#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004642 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004643 goto case_semi;
4644#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004645 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004646 /* proper use of this character is caught by end_trigger:
4647 * if we see {, we call parse_group(..., end_trigger='}')
4648 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004649 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004650 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004651 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004652 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004653 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004654 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004655 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004656
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004657 parse_error:
4658 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004659 struct parse_context *pctx;
4660 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004661
4662 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004663 * Sample for finding leaks on syntax error recovery path.
4664 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004665 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004666 * Samples to catch leaks at execution:
4667 * while if (true | {true;}); then echo ok; fi; do break; done
4668 * 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 +00004669 */
4670 pctx = &ctx;
4671 do {
4672 /* Update pipe/command counts,
4673 * otherwise freeing may miss some */
4674 done_pipe(pctx, PIPE_SEQ);
4675 debug_printf_clean("freeing list %p from ctx %p\n",
4676 pctx->list_head, pctx);
4677 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004678 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004679 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004680#if !BB_MMU
4681 o_free_unsafe(&pctx->as_string);
4682#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004683 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004684 if (pctx != &ctx) {
4685 free(pctx);
4686 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004687 IF_HAS_KEYWORDS(pctx = p2;)
4688 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004689
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004690 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004691 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004692#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004693 if (pstring)
4694 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004695#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004696 debug_leave();
4697 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004698 }
Eric Andersen25f27032001-04-26 23:22:31 +00004699}
4700
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004701
4702/*** Execution routines ***/
4703
4704/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004705#if !ENABLE_HUSH_BASH_COMPAT
4706/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4707#define expand_string_to_string(str, do_unbackslash) \
4708 expand_string_to_string(str)
4709#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004710static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004711#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004712static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004713#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004714
4715/* expand_strvec_to_strvec() takes a list of strings, expands
4716 * all variable references within and returns a pointer to
4717 * a list of expanded strings, possibly with larger number
4718 * of strings. (Think VAR="a b"; echo $VAR).
4719 * This new list is allocated as a single malloc block.
4720 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004721 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004722 * Caller can deallocate entire list by single free(list). */
4723
Denys Vlasenko238081f2010-10-03 14:26:26 +02004724/* A horde of its helpers come first: */
4725
4726static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4727{
4728 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004729 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004730
Denys Vlasenko9e800222010-10-03 14:28:04 +02004731#if ENABLE_HUSH_BRACE_EXPANSION
4732 if (c == '{' || c == '}') {
4733 /* { -> \{, } -> \} */
4734 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004735 /* And now we want to add { or } and continue:
4736 * o_addchr(o, c);
4737 * continue;
4738 * luckily, just falling throught achieves this.
4739 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004740 }
4741#endif
4742 o_addchr(o, c);
4743 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004744 /* \z -> \\\z; \<eol> -> \\<eol> */
4745 o_addchr(o, '\\');
4746 if (len) {
4747 len--;
4748 o_addchr(o, '\\');
4749 o_addchr(o, *str++);
4750 }
4751 }
4752 }
4753}
4754
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004755/* Store given string, finalizing the word and starting new one whenever
4756 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004757 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4758 * Return in *ended_with_ifs:
4759 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4760 */
4761static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004762{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004763 int last_is_ifs = 0;
4764
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004765 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004766 int word_len;
4767
4768 if (!*str) /* EOL - do not finalize word */
4769 break;
4770 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004771 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004772 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02004773 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004774 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004775 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004776 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004777 * Example: "v='\*'; echo b$v" prints "b\*"
4778 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004779 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004780 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004781 /*/ Why can't we do it easier? */
4782 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4783 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4784 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004785 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004786 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004787 if (!*str) /* EOL - do not finalize word */
4788 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004789 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004790
4791 /* We know str here points to at least one IFS char */
4792 last_is_ifs = 1;
4793 str += strspn(str, G.ifs); /* skip IFS chars */
4794 if (!*str) /* EOL - do not finalize word */
4795 break;
4796
4797 /* Start new word... but not always! */
4798 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004799 if (output->has_quoted_part
4800 /* Case "v=' a'; echo $v":
4801 * here nothing precedes the space in $v expansion,
4802 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004803 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004804 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004805 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004806 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004807 o_addchr(output, '\0');
4808 debug_print_list("expand_on_ifs", output, n);
4809 n = o_save_ptr(output, n);
4810 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004811 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004812
4813 if (ended_with_ifs)
4814 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004815 debug_print_list("expand_on_ifs[1]", output, n);
4816 return n;
4817}
4818
4819/* Helper to expand $((...)) and heredoc body. These act as if
4820 * they are in double quotes, with the exception that they are not :).
4821 * Just the rules are similar: "expand only $var and `cmd`"
4822 *
4823 * Returns malloced string.
4824 * As an optimization, we return NULL if expansion is not needed.
4825 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004826#if !ENABLE_HUSH_BASH_COMPAT
4827/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4828#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4829 encode_then_expand_string(str)
4830#endif
4831static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004832{
4833 char *exp_str;
4834 struct in_str input;
4835 o_string dest = NULL_O_STRING;
4836
4837 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004838 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004839#if ENABLE_HUSH_TICK
4840 && !strchr(str, '`')
4841#endif
4842 ) {
4843 return NULL;
4844 }
4845
4846 /* We need to expand. Example:
4847 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4848 */
4849 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004850 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004851//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004852 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004853 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004854 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4855 o_free_unsafe(&dest);
4856 return exp_str;
4857}
4858
4859#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004860static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004861{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004862 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004863 arith_t res;
4864 char *exp_str;
4865
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004866 math_state.lookupvar = get_local_var_value;
4867 math_state.setvar = set_local_var_from_halves;
4868 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004869 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004870 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004871 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004872 if (errmsg_p)
4873 *errmsg_p = math_state.errmsg;
4874 if (math_state.errmsg)
4875 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004876 return res;
4877}
4878#endif
4879
4880#if ENABLE_HUSH_BASH_COMPAT
4881/* ${var/[/]pattern[/repl]} helpers */
4882static char *strstr_pattern(char *val, const char *pattern, int *size)
4883{
4884 while (1) {
4885 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4886 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4887 if (end) {
4888 *size = end - val;
4889 return val;
4890 }
4891 if (*val == '\0')
4892 return NULL;
4893 /* Optimization: if "*pat" did not match the start of "string",
4894 * we know that "tring", "ring" etc will not match too:
4895 */
4896 if (pattern[0] == '*')
4897 return NULL;
4898 val++;
4899 }
4900}
4901static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4902{
4903 char *result = NULL;
4904 unsigned res_len = 0;
4905 unsigned repl_len = strlen(repl);
4906
4907 while (1) {
4908 int size;
4909 char *s = strstr_pattern(val, pattern, &size);
4910 if (!s)
4911 break;
4912
4913 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4914 memcpy(result + res_len, val, s - val);
4915 res_len += s - val;
4916 strcpy(result + res_len, repl);
4917 res_len += repl_len;
4918 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4919
4920 val = s + size;
4921 if (exp_op == '/')
4922 break;
4923 }
4924 if (val[0] && result) {
4925 result = xrealloc(result, res_len + strlen(val) + 1);
4926 strcpy(result + res_len, val);
4927 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4928 }
4929 debug_printf_varexp("result:'%s'\n", result);
4930 return result;
4931}
4932#endif
4933
4934/* Helper:
4935 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4936 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004937static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004938{
4939 const char *val = NULL;
4940 char *to_be_freed = NULL;
4941 char *p = *pp;
4942 char *var;
4943 char first_char;
4944 char exp_op;
4945 char exp_save = exp_save; /* for compiler */
4946 char *exp_saveptr; /* points to expansion operator */
4947 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004948 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004949
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004950 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004951 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004952 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004953 arg0 = arg[0];
4954 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004955 exp_op = 0;
4956
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004957 if (first_char == '#' /* ${#... */
4958 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4959 ) {
4960 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004961 var++;
4962 exp_op = 'L';
4963 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004964 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004965 if (exp_saveptr /* if 2nd char is one of expansion operators */
4966 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4967 ) {
4968 /* ${?:0}, ${#[:]%0} etc */
4969 exp_saveptr = var + 1;
4970 } else {
4971 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4972 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4973 }
4974 exp_op = exp_save = *exp_saveptr;
4975 if (exp_op) {
4976 exp_word = exp_saveptr + 1;
4977 if (exp_op == ':') {
4978 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004979//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004980 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004981 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004982 ) {
4983 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4984 exp_op = ':';
4985 exp_word--;
4986 }
4987 }
4988 *exp_saveptr = '\0';
4989 } /* else: it's not an expansion op, but bare ${var} */
4990 }
4991
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004992 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004993 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004994 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004995 int n = xatoi_positive(var);
4996 if (n < G.global_argc)
4997 val = G.global_argv[n];
4998 /* else val remains NULL: $N with too big N */
4999 } else {
5000 switch (var[0]) {
5001 case '$': /* pid */
5002 val = utoa(G.root_pid);
5003 break;
5004 case '!': /* bg pid */
5005 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5006 break;
5007 case '?': /* exitcode */
5008 val = utoa(G.last_exitcode);
5009 break;
5010 case '#': /* argc */
5011 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5012 break;
5013 default:
5014 val = get_local_var_value(var);
5015 }
5016 }
5017
5018 /* Handle any expansions */
5019 if (exp_op == 'L') {
5020 debug_printf_expand("expand: length(%s)=", val);
5021 val = utoa(val ? strlen(val) : 0);
5022 debug_printf_expand("%s\n", val);
5023 } else if (exp_op) {
5024 if (exp_op == '%' || exp_op == '#') {
5025 /* Standard-mandated substring removal ops:
5026 * ${parameter%word} - remove smallest suffix pattern
5027 * ${parameter%%word} - remove largest suffix pattern
5028 * ${parameter#word} - remove smallest prefix pattern
5029 * ${parameter##word} - remove largest prefix pattern
5030 *
5031 * Word is expanded to produce a glob pattern.
5032 * Then var's value is matched to it and matching part removed.
5033 */
5034 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005035 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005036 char *exp_exp_word;
5037 char *loc;
5038 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005039 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005040 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005041 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005042 if (exp_exp_word)
5043 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005044 /* HACK ALERT. We depend here on the fact that
5045 * G.global_argv and results of utoa and get_local_var_value
5046 * are actually in writable memory:
5047 * scan_and_match momentarily stores NULs there. */
5048 t = (char*)val;
5049 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005050 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005051 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005052 free(exp_exp_word);
5053 if (loc) { /* match was found */
5054 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005055 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005056 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005057 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005058 }
5059 }
5060 }
5061#if ENABLE_HUSH_BASH_COMPAT
5062 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005063 /* It's ${var/[/]pattern[/repl]} thing.
5064 * Note that in encoded form it has TWO parts:
5065 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005066 * and if // is used, it is encoded as \:
5067 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005068 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005069 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005070 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005071 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005072 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005073 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005074 * by the usual expansion rules:
5075 * >az; >bz;
5076 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5077 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5078 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5079 * v='a bz'; echo ${v/a*z/\z} prints "z"
5080 * (note that a*z _pattern_ is never globbed!)
5081 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005082 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005083 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005084 if (!pattern)
5085 pattern = xstrdup(exp_word);
5086 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5087 *p++ = SPECIAL_VAR_SYMBOL;
5088 exp_word = p;
5089 p = strchr(p, SPECIAL_VAR_SYMBOL);
5090 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005091 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005092 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5093 /* HACK ALERT. We depend here on the fact that
5094 * G.global_argv and results of utoa and get_local_var_value
5095 * are actually in writable memory:
5096 * replace_pattern momentarily stores NULs there. */
5097 t = (char*)val;
5098 to_be_freed = replace_pattern(t,
5099 pattern,
5100 (repl ? repl : exp_word),
5101 exp_op);
5102 if (to_be_freed) /* at least one replace happened */
5103 val = to_be_freed;
5104 free(pattern);
5105 free(repl);
5106 }
5107 }
5108#endif
5109 else if (exp_op == ':') {
5110#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5111 /* It's ${var:N[:M]} bashism.
5112 * Note that in encoded form it has TWO parts:
5113 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5114 */
5115 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005116 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005117
Denys Vlasenko063847d2010-09-15 13:33:02 +02005118 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5119 if (errmsg)
5120 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005121 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5122 *p++ = SPECIAL_VAR_SYMBOL;
5123 exp_word = p;
5124 p = strchr(p, SPECIAL_VAR_SYMBOL);
5125 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005126 len = expand_and_evaluate_arith(exp_word, &errmsg);
5127 if (errmsg)
5128 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005129 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005130 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005131 if (beg < 0) /* bash compat */
5132 beg = 0;
5133 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005134 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005135 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005136 val = NULL;
5137 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005138 /* Paranoia. What if user entered 9999999999999
5139 * which fits in arith_t but not int? */
5140 if (len >= INT_MAX)
5141 len = INT_MAX;
5142 val = to_be_freed = xstrndup(val + beg, len);
5143 }
5144 debug_printf_varexp("val:'%s'\n", val);
5145 } else
5146#endif
5147 {
5148 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005149 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005150 }
5151 } else { /* one of "-=+?" */
5152 /* Standard-mandated substitution ops:
5153 * ${var?word} - indicate error if unset
5154 * If var is unset, word (or a message indicating it is unset
5155 * if word is null) is written to standard error
5156 * and the shell exits with a non-zero exit status.
5157 * Otherwise, the value of var is substituted.
5158 * ${var-word} - use default value
5159 * If var is unset, word is substituted.
5160 * ${var=word} - assign and use default value
5161 * If var is unset, word is assigned to var.
5162 * In all cases, final value of var is substituted.
5163 * ${var+word} - use alternative value
5164 * If var is unset, null is substituted.
5165 * Otherwise, word is substituted.
5166 *
5167 * Word is subjected to tilde expansion, parameter expansion,
5168 * command substitution, and arithmetic expansion.
5169 * If word is not needed, it is not expanded.
5170 *
5171 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5172 * but also treat null var as if it is unset.
5173 */
5174 int use_word = (!val || ((exp_save == ':') && !val[0]));
5175 if (exp_op == '+')
5176 use_word = !use_word;
5177 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5178 (exp_save == ':') ? "true" : "false", use_word);
5179 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005180 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005181 if (to_be_freed)
5182 exp_word = to_be_freed;
5183 if (exp_op == '?') {
5184 /* mimic bash message */
5185 die_if_script("%s: %s",
5186 var,
5187 exp_word[0] ? exp_word : "parameter null or not set"
5188 );
5189//TODO: how interactive bash aborts expansion mid-command?
5190 } else {
5191 val = exp_word;
5192 }
5193
5194 if (exp_op == '=') {
5195 /* ${var=[word]} or ${var:=[word]} */
5196 if (isdigit(var[0]) || var[0] == '#') {
5197 /* mimic bash message */
5198 die_if_script("$%s: cannot assign in this way", var);
5199 val = NULL;
5200 } else {
5201 char *new_var = xasprintf("%s=%s", var, val);
5202 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5203 }
5204 }
5205 }
5206 } /* one of "-=+?" */
5207
5208 *exp_saveptr = exp_save;
5209 } /* if (exp_op) */
5210
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005211 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005212
5213 *pp = p;
5214 *to_be_freed_pp = to_be_freed;
5215 return val;
5216}
5217
5218/* Expand all variable references in given string, adding words to list[]
5219 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5220 * to be filled). This routine is extremely tricky: has to deal with
5221 * variables/parameters with whitespace, $* and $@, and constructs like
5222 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005223static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005224{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005225 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005226 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005227 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005228 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005229 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005230 char *p;
5231
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005232 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5233 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005234 debug_print_list("expand_vars_to_list", output, n);
5235 n = o_save_ptr(output, n);
5236 debug_print_list("expand_vars_to_list[0]", output, n);
5237
5238 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5239 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005240 char *to_be_freed = NULL;
5241 const char *val = NULL;
5242#if ENABLE_HUSH_TICK
5243 o_string subst_result = NULL_O_STRING;
5244#endif
5245#if ENABLE_SH_MATH_SUPPORT
5246 char arith_buf[sizeof(arith_t)*3 + 2];
5247#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005248
5249 if (ended_in_ifs) {
5250 o_addchr(output, '\0');
5251 n = o_save_ptr(output, n);
5252 ended_in_ifs = 0;
5253 }
5254
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005255 o_addblock(output, arg, p - arg);
5256 debug_print_list("expand_vars_to_list[1]", output, n);
5257 arg = ++p;
5258 p = strchr(p, SPECIAL_VAR_SYMBOL);
5259
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005260 /* Fetch special var name (if it is indeed one of them)
5261 * and quote bit, force the bit on if singleword expansion -
5262 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005263 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005264
5265 /* Is this variable quoted and thus expansion can't be null?
5266 * "$@" is special. Even if quoted, it can still
5267 * expand to nothing (not even an empty string),
5268 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005269 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005270 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005271
5272 switch (first_ch & 0x7f) {
5273 /* Highest bit in first_ch indicates that var is double-quoted */
5274 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005275 case '@': {
5276 int i;
5277 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005278 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005279 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005280 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005281 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005282 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005283 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005284 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5285 if (G.global_argv[i++][0] && G.global_argv[i]) {
5286 /* this argv[] is not empty and not last:
5287 * put terminating NUL, start new word */
5288 o_addchr(output, '\0');
5289 debug_print_list("expand_vars_to_list[2]", output, n);
5290 n = o_save_ptr(output, n);
5291 debug_print_list("expand_vars_to_list[3]", output, n);
5292 }
5293 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005294 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005295 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005296 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005297 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005298 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005299 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005300 while (1) {
5301 o_addQstr(output, G.global_argv[i]);
5302 if (++i >= G.global_argc)
5303 break;
5304 o_addchr(output, '\0');
5305 debug_print_list("expand_vars_to_list[4]", output, n);
5306 n = o_save_ptr(output, n);
5307 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005308 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005309 while (1) {
5310 o_addQstr(output, G.global_argv[i]);
5311 if (!G.global_argv[++i])
5312 break;
5313 if (G.ifs[0])
5314 o_addchr(output, G.ifs[0]);
5315 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005316 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005317 }
5318 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005319 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005320 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5321 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005322 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005323 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005324 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005325 break;
5326#if ENABLE_HUSH_TICK
5327 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005328 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005329 arg++;
5330 /* Can't just stuff it into output o_string,
5331 * expanded result may need to be globbed
5332 * and $IFS-splitted */
5333 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5334 G.last_exitcode = process_command_subs(&subst_result, arg);
5335 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5336 val = subst_result.data;
5337 goto store_val;
5338#endif
5339#if ENABLE_SH_MATH_SUPPORT
5340 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5341 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005342
5343 arg++; /* skip '+' */
5344 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5345 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005346 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005347 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5348 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005349 val = arith_buf;
5350 break;
5351 }
5352#endif
5353 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005354 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005355 IF_HUSH_TICK(store_val:)
5356 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005357 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5358 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005359 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005360 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005361 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005362 }
5363 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005364 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005365 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5366 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005367 }
5368 break;
5369
5370 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5371
5372 if (val && val[0]) {
5373 o_addQstr(output, val);
5374 }
5375 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005376
5377 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5378 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005379 if (*p != SPECIAL_VAR_SYMBOL)
5380 *p = SPECIAL_VAR_SYMBOL;
5381
5382#if ENABLE_HUSH_TICK
5383 o_free(&subst_result);
5384#endif
5385 arg = ++p;
5386 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5387
5388 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005389 if (ended_in_ifs) {
5390 o_addchr(output, '\0');
5391 n = o_save_ptr(output, n);
5392 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005393 debug_print_list("expand_vars_to_list[a]", output, n);
5394 /* this part is literal, and it was already pre-quoted
5395 * if needed (much earlier), do not use o_addQstr here! */
5396 o_addstr_with_NUL(output, arg);
5397 debug_print_list("expand_vars_to_list[b]", output, n);
5398 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005399 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005400 ) {
5401 n--;
5402 /* allow to reuse list[n] later without re-growth */
5403 output->has_empty_slot = 1;
5404 } else {
5405 o_addchr(output, '\0');
5406 }
5407
5408 return n;
5409}
5410
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005411static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005412{
5413 int n;
5414 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005415 o_string output = NULL_O_STRING;
5416
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005417 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005418
5419 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005420 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005421 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005422 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005423 }
5424 debug_print_list("expand_variables", &output, n);
5425
5426 /* output.data (malloced in one block) gets returned in "list" */
5427 list = o_finalize_list(&output, n);
5428 debug_print_strings("expand_variables[1]", list);
5429 return list;
5430}
5431
5432static char **expand_strvec_to_strvec(char **argv)
5433{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005434 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005435}
5436
5437#if ENABLE_HUSH_BASH_COMPAT
5438static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5439{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005440 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005441}
5442#endif
5443
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005444/* Used for expansion of right hand of assignments,
5445 * $((...)), heredocs, variable espansion parts.
5446 *
5447 * NB: should NOT do globbing!
5448 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5449 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005450static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005451{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005452#if !ENABLE_HUSH_BASH_COMPAT
5453 const int do_unbackslash = 1;
5454#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005455 char *argv[2], **list;
5456
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005457 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005458 /* This is generally an optimization, but it also
5459 * handles "", which otherwise trips over !list[0] check below.
5460 * (is this ever happens that we actually get str="" here?)
5461 */
5462 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5463 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005464 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005465 return xstrdup(str);
5466 }
5467
5468 argv[0] = (char*)str;
5469 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005470 list = expand_variables(argv, do_unbackslash
5471 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5472 : EXP_FLAG_SINGLEWORD
5473 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005474 if (HUSH_DEBUG)
5475 if (!list[0] || list[1])
5476 bb_error_msg_and_die("BUG in varexp2");
5477 /* actually, just move string 2*sizeof(char*) bytes back */
5478 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005479 if (do_unbackslash)
5480 unbackslash((char*)list);
5481 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005482 return (char*)list;
5483}
5484
5485/* Used for "eval" builtin */
5486static char* expand_strvec_to_string(char **argv)
5487{
5488 char **list;
5489
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005490 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005491 /* Convert all NULs to spaces */
5492 if (list[0]) {
5493 int n = 1;
5494 while (list[n]) {
5495 if (HUSH_DEBUG)
5496 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5497 bb_error_msg_and_die("BUG in varexp3");
5498 /* bash uses ' ' regardless of $IFS contents */
5499 list[n][-1] = ' ';
5500 n++;
5501 }
5502 }
5503 overlapping_strcpy((char*)list, list[0]);
5504 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5505 return (char*)list;
5506}
5507
5508static char **expand_assignments(char **argv, int count)
5509{
5510 int i;
5511 char **p;
5512
5513 G.expanded_assignments = p = NULL;
5514 /* Expand assignments into one string each */
5515 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005516 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005517 }
5518 G.expanded_assignments = NULL;
5519 return p;
5520}
5521
5522
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005523static void switch_off_special_sigs(unsigned mask)
5524{
5525 unsigned sig = 0;
5526 while ((mask >>= 1) != 0) {
5527 sig++;
5528 if (!(mask & 1))
5529 continue;
5530 if (G.traps) {
5531 if (G.traps[sig] && !G.traps[sig][0])
5532 /* trap is '', has to remain SIG_IGN */
5533 continue;
5534 free(G.traps[sig]);
5535 G.traps[sig] = NULL;
5536 }
5537 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005538 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005539 }
5540}
5541
Denys Vlasenkob347df92011-08-09 22:49:15 +02005542#if BB_MMU
5543/* never called */
5544void re_execute_shell(char ***to_free, const char *s,
5545 char *g_argv0, char **g_argv,
5546 char **builtin_argv) NORETURN;
5547
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005548static void reset_traps_to_defaults(void)
5549{
5550 /* This function is always called in a child shell
5551 * after fork (not vfork, NOMMU doesn't use this function).
5552 */
5553 unsigned sig;
5554 unsigned mask;
5555
5556 /* Child shells are not interactive.
5557 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5558 * Testcase: (while :; do :; done) + ^Z should background.
5559 * Same goes for SIGTERM, SIGHUP, SIGINT.
5560 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005561 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5562 if (!G.traps && !mask)
5563 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005564
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005565 /* Switch off special sigs */
5566 switch_off_special_sigs(mask);
5567#if ENABLE_HUSH_JOB
5568 G_fatal_sig_mask = 0;
5569#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005570 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005571 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5572 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005573
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005574 if (!G.traps)
5575 return;
5576
5577 /* Reset all sigs to default except ones with empty traps */
5578 for (sig = 0; sig < NSIG; sig++) {
5579 if (!G.traps[sig])
5580 continue; /* no trap: nothing to do */
5581 if (!G.traps[sig][0])
5582 continue; /* empty trap: has to remain SIG_IGN */
5583 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005584 free(G.traps[sig]);
5585 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005586 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005587 if (sig == 0)
5588 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005589 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005590 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005591}
5592
5593#else /* !BB_MMU */
5594
5595static void re_execute_shell(char ***to_free, const char *s,
5596 char *g_argv0, char **g_argv,
5597 char **builtin_argv) NORETURN;
5598static void re_execute_shell(char ***to_free, const char *s,
5599 char *g_argv0, char **g_argv,
5600 char **builtin_argv)
5601{
5602# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5603 /* delims + 2 * (number of bytes in printed hex numbers) */
5604 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5605 char *heredoc_argv[4];
5606 struct variable *cur;
5607# if ENABLE_HUSH_FUNCTIONS
5608 struct function *funcp;
5609# endif
5610 char **argv, **pp;
5611 unsigned cnt;
5612 unsigned long long empty_trap_mask;
5613
5614 if (!g_argv0) { /* heredoc */
5615 argv = heredoc_argv;
5616 argv[0] = (char *) G.argv0_for_re_execing;
5617 argv[1] = (char *) "-<";
5618 argv[2] = (char *) s;
5619 argv[3] = NULL;
5620 pp = &argv[3]; /* used as pointer to empty environment */
5621 goto do_exec;
5622 }
5623
5624 cnt = 0;
5625 pp = builtin_argv;
5626 if (pp) while (*pp++)
5627 cnt++;
5628
5629 empty_trap_mask = 0;
5630 if (G.traps) {
5631 int sig;
5632 for (sig = 1; sig < NSIG; sig++) {
5633 if (G.traps[sig] && !G.traps[sig][0])
5634 empty_trap_mask |= 1LL << sig;
5635 }
5636 }
5637
5638 sprintf(param_buf, NOMMU_HACK_FMT
5639 , (unsigned) G.root_pid
5640 , (unsigned) G.root_ppid
5641 , (unsigned) G.last_bg_pid
5642 , (unsigned) G.last_exitcode
5643 , cnt
5644 , empty_trap_mask
5645 IF_HUSH_LOOPS(, G.depth_of_loop)
5646 );
5647# undef NOMMU_HACK_FMT
5648 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5649 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5650 */
5651 cnt += 6;
5652 for (cur = G.top_var; cur; cur = cur->next) {
5653 if (!cur->flg_export || cur->flg_read_only)
5654 cnt += 2;
5655 }
5656# if ENABLE_HUSH_FUNCTIONS
5657 for (funcp = G.top_func; funcp; funcp = funcp->next)
5658 cnt += 3;
5659# endif
5660 pp = g_argv;
5661 while (*pp++)
5662 cnt++;
5663 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5664 *pp++ = (char *) G.argv0_for_re_execing;
5665 *pp++ = param_buf;
5666 for (cur = G.top_var; cur; cur = cur->next) {
5667 if (strcmp(cur->varstr, hush_version_str) == 0)
5668 continue;
5669 if (cur->flg_read_only) {
5670 *pp++ = (char *) "-R";
5671 *pp++ = cur->varstr;
5672 } else if (!cur->flg_export) {
5673 *pp++ = (char *) "-V";
5674 *pp++ = cur->varstr;
5675 }
5676 }
5677# if ENABLE_HUSH_FUNCTIONS
5678 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5679 *pp++ = (char *) "-F";
5680 *pp++ = funcp->name;
5681 *pp++ = funcp->body_as_string;
5682 }
5683# endif
5684 /* We can pass activated traps here. Say, -Tnn:trap_string
5685 *
5686 * However, POSIX says that subshells reset signals with traps
5687 * to SIG_DFL.
5688 * I tested bash-3.2 and it not only does that with true subshells
5689 * of the form ( list ), but with any forked children shells.
5690 * I set trap "echo W" WINCH; and then tried:
5691 *
5692 * { echo 1; sleep 20; echo 2; } &
5693 * while true; do echo 1; sleep 20; echo 2; break; done &
5694 * true | { echo 1; sleep 20; echo 2; } | cat
5695 *
5696 * In all these cases sending SIGWINCH to the child shell
5697 * did not run the trap. If I add trap "echo V" WINCH;
5698 * _inside_ group (just before echo 1), it works.
5699 *
5700 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005701 */
5702 *pp++ = (char *) "-c";
5703 *pp++ = (char *) s;
5704 if (builtin_argv) {
5705 while (*++builtin_argv)
5706 *pp++ = *builtin_argv;
5707 *pp++ = (char *) "";
5708 }
5709 *pp++ = g_argv0;
5710 while (*g_argv)
5711 *pp++ = *g_argv++;
5712 /* *pp = NULL; - is already there */
5713 pp = environ;
5714
5715 do_exec:
5716 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02005717 /* Don't propagate SIG_IGN to the child */
5718 if (SPECIAL_JOBSTOP_SIGS != 0)
5719 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005720 execve(bb_busybox_exec_path, argv, pp);
5721 /* Fallback. Useful for init=/bin/hush usage etc */
5722 if (argv[0][0] == '/')
5723 execve(argv[0], argv, pp);
5724 xfunc_error_retval = 127;
5725 bb_error_msg_and_die("can't re-execute the shell");
5726}
5727#endif /* !BB_MMU */
5728
5729
5730static int run_and_free_list(struct pipe *pi);
5731
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005732/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005733 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5734 * end_trigger controls how often we stop parsing
5735 * NUL: parse all, execute, return
5736 * ';': parse till ';' or newline, execute, repeat till EOF
5737 */
5738static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005739{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005740 /* Why we need empty flag?
5741 * An obscure corner case "false; ``; echo $?":
5742 * empty command in `` should still set $? to 0.
5743 * But we can't just set $? to 0 at the start,
5744 * this breaks "false; echo `echo $?`" case.
5745 */
5746 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005747 while (1) {
5748 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005749
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005750#if ENABLE_HUSH_INTERACTIVE
5751 if (end_trigger == ';')
5752 inp->promptmode = 0; /* PS1 */
5753#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005754 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005755 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5756 /* If we are in "big" script
5757 * (not in `cmd` or something similar)...
5758 */
5759 if (pipe_list == ERR_PTR && end_trigger == ';') {
5760 /* Discard cached input (rest of line) */
5761 int ch = inp->last_char;
5762 while (ch != EOF && ch != '\n') {
5763 //bb_error_msg("Discarded:'%c'", ch);
5764 ch = i_getch(inp);
5765 }
5766 /* Force prompt */
5767 inp->p = NULL;
5768 /* This stream isn't empty */
5769 empty = 0;
5770 continue;
5771 }
5772 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01005773 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005774 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005775 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005776 debug_print_tree(pipe_list, 0);
5777 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5778 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005779 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005780#if ENABLE_HUSH_FUNCTIONS
5781 if (G.flag_return_in_progress == 1)
5782 break;
5783#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005784 }
Eric Andersen25f27032001-04-26 23:22:31 +00005785}
5786
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005787static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005788{
5789 struct in_str input;
5790 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005791 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005792}
5793
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005794static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005795{
Eric Andersen25f27032001-04-26 23:22:31 +00005796 struct in_str input;
5797 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005798 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005799}
5800
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005801#if ENABLE_HUSH_TICK
5802static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5803{
5804 pid_t pid;
5805 int channel[2];
5806# if !BB_MMU
5807 char **to_free = NULL;
5808# endif
5809
5810 xpipe(channel);
5811 pid = BB_MMU ? xfork() : xvfork();
5812 if (pid == 0) { /* child */
5813 disable_restore_tty_pgrp_on_exit();
5814 /* Process substitution is not considered to be usual
5815 * 'command execution'.
5816 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5817 */
5818 bb_signals(0
5819 + (1 << SIGTSTP)
5820 + (1 << SIGTTIN)
5821 + (1 << SIGTTOU)
5822 , SIG_IGN);
5823 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5824 close(channel[0]); /* NB: close _first_, then move fd! */
5825 xmove_fd(channel[1], 1);
5826 /* Prevent it from trying to handle ctrl-z etc */
5827 IF_HUSH_JOB(G.run_list_level = 1;)
5828 /* Awful hack for `trap` or $(trap).
5829 *
5830 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5831 * contains an example where "trap" is executed in a subshell:
5832 *
5833 * save_traps=$(trap)
5834 * ...
5835 * eval "$save_traps"
5836 *
5837 * Standard does not say that "trap" in subshell shall print
5838 * parent shell's traps. It only says that its output
5839 * must have suitable form, but then, in the above example
5840 * (which is not supposed to be normative), it implies that.
5841 *
5842 * bash (and probably other shell) does implement it
5843 * (traps are reset to defaults, but "trap" still shows them),
5844 * but as a result, "trap" logic is hopelessly messed up:
5845 *
5846 * # trap
5847 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5848 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5849 * # true | trap <--- trap is in subshell - no output (ditto)
5850 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5851 * trap -- 'echo Ho' SIGWINCH
5852 * # echo `(trap)` <--- in subshell in subshell - output
5853 * trap -- 'echo Ho' SIGWINCH
5854 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5855 * trap -- 'echo Ho' SIGWINCH
5856 *
5857 * The rules when to forget and when to not forget traps
5858 * get really complex and nonsensical.
5859 *
5860 * Our solution: ONLY bare $(trap) or `trap` is special.
5861 */
5862 s = skip_whitespace(s);
5863 if (strncmp(s, "trap", 4) == 0
5864 && skip_whitespace(s + 4)[0] == '\0'
5865 ) {
5866 static const char *const argv[] = { NULL, NULL };
5867 builtin_trap((char**)argv);
5868 exit(0); /* not _exit() - we need to fflush */
5869 }
5870# if BB_MMU
5871 reset_traps_to_defaults();
5872 parse_and_run_string(s);
5873 _exit(G.last_exitcode);
5874# else
5875 /* We re-execute after vfork on NOMMU. This makes this script safe:
5876 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5877 * huge=`cat BIG` # was blocking here forever
5878 * echo OK
5879 */
5880 re_execute_shell(&to_free,
5881 s,
5882 G.global_argv[0],
5883 G.global_argv + 1,
5884 NULL);
5885# endif
5886 }
5887
5888 /* parent */
5889 *pid_p = pid;
5890# if ENABLE_HUSH_FAST
5891 G.count_SIGCHLD++;
5892//bb_error_msg("[%d] fork in generate_stream_from_string:"
5893// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5894// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5895# endif
5896 enable_restore_tty_pgrp_on_exit();
5897# if !BB_MMU
5898 free(to_free);
5899# endif
5900 close(channel[1]);
5901 close_on_exec_on(channel[0]);
5902 return xfdopen_for_read(channel[0]);
5903}
5904
5905/* Return code is exit status of the process that is run. */
5906static int process_command_subs(o_string *dest, const char *s)
5907{
5908 FILE *fp;
5909 struct in_str pipe_str;
5910 pid_t pid;
5911 int status, ch, eol_cnt;
5912
5913 fp = generate_stream_from_string(s, &pid);
5914
5915 /* Now send results of command back into original context */
5916 setup_file_in_str(&pipe_str, fp);
5917 eol_cnt = 0;
5918 while ((ch = i_getch(&pipe_str)) != EOF) {
5919 if (ch == '\n') {
5920 eol_cnt++;
5921 continue;
5922 }
5923 while (eol_cnt) {
5924 o_addchr(dest, '\n');
5925 eol_cnt--;
5926 }
5927 o_addQchr(dest, ch);
5928 }
5929
5930 debug_printf("done reading from `cmd` pipe, closing it\n");
5931 fclose(fp);
5932 /* We need to extract exitcode. Test case
5933 * "true; echo `sleep 1; false` $?"
5934 * should print 1 */
5935 safe_waitpid(pid, &status, 0);
5936 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5937 return WEXITSTATUS(status);
5938}
5939#endif /* ENABLE_HUSH_TICK */
5940
5941
5942static void setup_heredoc(struct redir_struct *redir)
5943{
5944 struct fd_pair pair;
5945 pid_t pid;
5946 int len, written;
5947 /* the _body_ of heredoc (misleading field name) */
5948 const char *heredoc = redir->rd_filename;
5949 char *expanded;
5950#if !BB_MMU
5951 char **to_free;
5952#endif
5953
5954 expanded = NULL;
5955 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005956 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005957 if (expanded)
5958 heredoc = expanded;
5959 }
5960 len = strlen(heredoc);
5961
5962 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5963 xpiped_pair(pair);
5964 xmove_fd(pair.rd, redir->rd_fd);
5965
5966 /* Try writing without forking. Newer kernels have
5967 * dynamically growing pipes. Must use non-blocking write! */
5968 ndelay_on(pair.wr);
5969 while (1) {
5970 written = write(pair.wr, heredoc, len);
5971 if (written <= 0)
5972 break;
5973 len -= written;
5974 if (len == 0) {
5975 close(pair.wr);
5976 free(expanded);
5977 return;
5978 }
5979 heredoc += written;
5980 }
5981 ndelay_off(pair.wr);
5982
5983 /* Okay, pipe buffer was not big enough */
5984 /* Note: we must not create a stray child (bastard? :)
5985 * for the unsuspecting parent process. Child creates a grandchild
5986 * and exits before parent execs the process which consumes heredoc
5987 * (that exec happens after we return from this function) */
5988#if !BB_MMU
5989 to_free = NULL;
5990#endif
5991 pid = xvfork();
5992 if (pid == 0) {
5993 /* child */
5994 disable_restore_tty_pgrp_on_exit();
5995 pid = BB_MMU ? xfork() : xvfork();
5996 if (pid != 0)
5997 _exit(0);
5998 /* grandchild */
5999 close(redir->rd_fd); /* read side of the pipe */
6000#if BB_MMU
6001 full_write(pair.wr, heredoc, len); /* may loop or block */
6002 _exit(0);
6003#else
6004 /* Delegate blocking writes to another process */
6005 xmove_fd(pair.wr, STDOUT_FILENO);
6006 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6007#endif
6008 }
6009 /* parent */
6010#if ENABLE_HUSH_FAST
6011 G.count_SIGCHLD++;
6012//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6013#endif
6014 enable_restore_tty_pgrp_on_exit();
6015#if !BB_MMU
6016 free(to_free);
6017#endif
6018 close(pair.wr);
6019 free(expanded);
6020 wait(NULL); /* wait till child has died */
6021}
6022
6023/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6024 * and stderr if they are redirected. */
6025static int setup_redirects(struct command *prog, int squirrel[])
6026{
6027 int openfd, mode;
6028 struct redir_struct *redir;
6029
6030 for (redir = prog->redirects; redir; redir = redir->next) {
6031 if (redir->rd_type == REDIRECT_HEREDOC2) {
6032 /* rd_fd<<HERE case */
6033 if (squirrel && redir->rd_fd < 3
6034 && squirrel[redir->rd_fd] < 0
6035 ) {
6036 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6037 }
6038 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6039 * of the heredoc */
6040 debug_printf_parse("set heredoc '%s'\n",
6041 redir->rd_filename);
6042 setup_heredoc(redir);
6043 continue;
6044 }
6045
6046 if (redir->rd_dup == REDIRFD_TO_FILE) {
6047 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6048 char *p;
6049 if (redir->rd_filename == NULL) {
6050 /* Something went wrong in the parse.
6051 * Pretend it didn't happen */
6052 bb_error_msg("bug in redirect parse");
6053 continue;
6054 }
6055 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006056 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006057 openfd = open_or_warn(p, mode);
6058 free(p);
6059 if (openfd < 0) {
6060 /* this could get lost if stderr has been redirected, but
6061 * bash and ash both lose it as well (though zsh doesn't!) */
6062//what the above comment tries to say?
6063 return 1;
6064 }
6065 } else {
6066 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6067 openfd = redir->rd_dup;
6068 }
6069
6070 if (openfd != redir->rd_fd) {
6071 if (squirrel && redir->rd_fd < 3
6072 && squirrel[redir->rd_fd] < 0
6073 ) {
6074 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6075 }
6076 if (openfd == REDIRFD_CLOSE) {
6077 /* "n>-" means "close me" */
6078 close(redir->rd_fd);
6079 } else {
6080 xdup2(openfd, redir->rd_fd);
6081 if (redir->rd_dup == REDIRFD_TO_FILE)
6082 close(openfd);
6083 }
6084 }
6085 }
6086 return 0;
6087}
6088
6089static void restore_redirects(int squirrel[])
6090{
6091 int i, fd;
6092 for (i = 0; i < 3; i++) {
6093 fd = squirrel[i];
6094 if (fd != -1) {
6095 /* We simply die on error */
6096 xmove_fd(fd, i);
6097 }
6098 }
6099}
6100
6101static char *find_in_path(const char *arg)
6102{
6103 char *ret = NULL;
6104 const char *PATH = get_local_var_value("PATH");
6105
6106 if (!PATH)
6107 return NULL;
6108
6109 while (1) {
6110 const char *end = strchrnul(PATH, ':');
6111 int sz = end - PATH; /* must be int! */
6112
6113 free(ret);
6114 if (sz != 0) {
6115 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6116 } else {
6117 /* We have xxx::yyyy in $PATH,
6118 * it means "use current dir" */
6119 ret = xstrdup(arg);
6120 }
6121 if (access(ret, F_OK) == 0)
6122 break;
6123
6124 if (*end == '\0') {
6125 free(ret);
6126 return NULL;
6127 }
6128 PATH = end + 1;
6129 }
6130
6131 return ret;
6132}
6133
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006134static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006135 const struct built_in_command *x,
6136 const struct built_in_command *end)
6137{
6138 while (x != end) {
6139 if (strcmp(name, x->b_cmd) != 0) {
6140 x++;
6141 continue;
6142 }
6143 debug_printf_exec("found builtin '%s'\n", name);
6144 return x;
6145 }
6146 return NULL;
6147}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006148static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006149{
6150 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6151}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006152static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006153{
6154 const struct built_in_command *x = find_builtin1(name);
6155 if (x)
6156 return x;
6157 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6158}
6159
6160#if ENABLE_HUSH_FUNCTIONS
6161static struct function **find_function_slot(const char *name)
6162{
6163 struct function **funcpp = &G.top_func;
6164 while (*funcpp) {
6165 if (strcmp(name, (*funcpp)->name) == 0) {
6166 break;
6167 }
6168 funcpp = &(*funcpp)->next;
6169 }
6170 return funcpp;
6171}
6172
6173static const struct function *find_function(const char *name)
6174{
6175 const struct function *funcp = *find_function_slot(name);
6176 if (funcp)
6177 debug_printf_exec("found function '%s'\n", name);
6178 return funcp;
6179}
6180
6181/* Note: takes ownership on name ptr */
6182static struct function *new_function(char *name)
6183{
6184 struct function **funcpp = find_function_slot(name);
6185 struct function *funcp = *funcpp;
6186
6187 if (funcp != NULL) {
6188 struct command *cmd = funcp->parent_cmd;
6189 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6190 if (!cmd) {
6191 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6192 free(funcp->name);
6193 /* Note: if !funcp->body, do not free body_as_string!
6194 * This is a special case of "-F name body" function:
6195 * body_as_string was not malloced! */
6196 if (funcp->body) {
6197 free_pipe_list(funcp->body);
6198# if !BB_MMU
6199 free(funcp->body_as_string);
6200# endif
6201 }
6202 } else {
6203 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6204 cmd->argv[0] = funcp->name;
6205 cmd->group = funcp->body;
6206# if !BB_MMU
6207 cmd->group_as_string = funcp->body_as_string;
6208# endif
6209 }
6210 } else {
6211 debug_printf_exec("remembering new function '%s'\n", name);
6212 funcp = *funcpp = xzalloc(sizeof(*funcp));
6213 /*funcp->next = NULL;*/
6214 }
6215
6216 funcp->name = name;
6217 return funcp;
6218}
6219
6220static void unset_func(const char *name)
6221{
6222 struct function **funcpp = find_function_slot(name);
6223 struct function *funcp = *funcpp;
6224
6225 if (funcp != NULL) {
6226 debug_printf_exec("freeing function '%s'\n", funcp->name);
6227 *funcpp = funcp->next;
6228 /* funcp is unlinked now, deleting it.
6229 * Note: if !funcp->body, the function was created by
6230 * "-F name body", do not free ->body_as_string
6231 * and ->name as they were not malloced. */
6232 if (funcp->body) {
6233 free_pipe_list(funcp->body);
6234 free(funcp->name);
6235# if !BB_MMU
6236 free(funcp->body_as_string);
6237# endif
6238 }
6239 free(funcp);
6240 }
6241}
6242
6243# if BB_MMU
6244#define exec_function(to_free, funcp, argv) \
6245 exec_function(funcp, argv)
6246# endif
6247static void exec_function(char ***to_free,
6248 const struct function *funcp,
6249 char **argv) NORETURN;
6250static void exec_function(char ***to_free,
6251 const struct function *funcp,
6252 char **argv)
6253{
6254# if BB_MMU
6255 int n = 1;
6256
6257 argv[0] = G.global_argv[0];
6258 G.global_argv = argv;
6259 while (*++argv)
6260 n++;
6261 G.global_argc = n;
6262 /* On MMU, funcp->body is always non-NULL */
6263 n = run_list(funcp->body);
6264 fflush_all();
6265 _exit(n);
6266# else
6267 re_execute_shell(to_free,
6268 funcp->body_as_string,
6269 G.global_argv[0],
6270 argv + 1,
6271 NULL);
6272# endif
6273}
6274
6275static int run_function(const struct function *funcp, char **argv)
6276{
6277 int rc;
6278 save_arg_t sv;
6279 smallint sv_flg;
6280
6281 save_and_replace_G_args(&sv, argv);
6282
6283 /* "we are in function, ok to use return" */
6284 sv_flg = G.flag_return_in_progress;
6285 G.flag_return_in_progress = -1;
6286# if ENABLE_HUSH_LOCAL
6287 G.func_nest_level++;
6288# endif
6289
6290 /* On MMU, funcp->body is always non-NULL */
6291# if !BB_MMU
6292 if (!funcp->body) {
6293 /* Function defined by -F */
6294 parse_and_run_string(funcp->body_as_string);
6295 rc = G.last_exitcode;
6296 } else
6297# endif
6298 {
6299 rc = run_list(funcp->body);
6300 }
6301
6302# if ENABLE_HUSH_LOCAL
6303 {
6304 struct variable *var;
6305 struct variable **var_pp;
6306
6307 var_pp = &G.top_var;
6308 while ((var = *var_pp) != NULL) {
6309 if (var->func_nest_level < G.func_nest_level) {
6310 var_pp = &var->next;
6311 continue;
6312 }
6313 /* Unexport */
6314 if (var->flg_export)
6315 bb_unsetenv(var->varstr);
6316 /* Remove from global list */
6317 *var_pp = var->next;
6318 /* Free */
6319 if (!var->max_len)
6320 free(var->varstr);
6321 free(var);
6322 }
6323 G.func_nest_level--;
6324 }
6325# endif
6326 G.flag_return_in_progress = sv_flg;
6327
6328 restore_G_args(&sv, argv);
6329
6330 return rc;
6331}
6332#endif /* ENABLE_HUSH_FUNCTIONS */
6333
6334
6335#if BB_MMU
6336#define exec_builtin(to_free, x, argv) \
6337 exec_builtin(x, argv)
6338#else
6339#define exec_builtin(to_free, x, argv) \
6340 exec_builtin(to_free, argv)
6341#endif
6342static void exec_builtin(char ***to_free,
6343 const struct built_in_command *x,
6344 char **argv) NORETURN;
6345static void exec_builtin(char ***to_free,
6346 const struct built_in_command *x,
6347 char **argv)
6348{
6349#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006350 int rcode;
6351 fflush_all();
6352 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006353 fflush_all();
6354 _exit(rcode);
6355#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006356 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006357 /* On NOMMU, we must never block!
6358 * Example: { sleep 99 | read line; } & echo Ok
6359 */
6360 re_execute_shell(to_free,
6361 argv[0],
6362 G.global_argv[0],
6363 G.global_argv + 1,
6364 argv);
6365#endif
6366}
6367
6368
6369static void execvp_or_die(char **argv) NORETURN;
6370static void execvp_or_die(char **argv)
6371{
6372 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006373 /* Don't propagate SIG_IGN to the child */
6374 if (SPECIAL_JOBSTOP_SIGS != 0)
6375 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006376 execvp(argv[0], argv);
6377 bb_perror_msg("can't execute '%s'", argv[0]);
6378 _exit(127); /* bash compat */
6379}
6380
6381#if ENABLE_HUSH_MODE_X
6382static void dump_cmd_in_x_mode(char **argv)
6383{
6384 if (G_x_mode && argv) {
6385 /* We want to output the line in one write op */
6386 char *buf, *p;
6387 int len;
6388 int n;
6389
6390 len = 3;
6391 n = 0;
6392 while (argv[n])
6393 len += strlen(argv[n++]) + 1;
6394 buf = xmalloc(len);
6395 buf[0] = '+';
6396 p = buf + 1;
6397 n = 0;
6398 while (argv[n])
6399 p += sprintf(p, " %s", argv[n++]);
6400 *p++ = '\n';
6401 *p = '\0';
6402 fputs(buf, stderr);
6403 free(buf);
6404 }
6405}
6406#else
6407# define dump_cmd_in_x_mode(argv) ((void)0)
6408#endif
6409
6410#if BB_MMU
6411#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6412 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6413#define pseudo_exec(nommu_save, command, argv_expanded) \
6414 pseudo_exec(command, argv_expanded)
6415#endif
6416
6417/* Called after [v]fork() in run_pipe, or from builtin_exec.
6418 * Never returns.
6419 * Don't exit() here. If you don't exec, use _exit instead.
6420 * The at_exit handlers apparently confuse the calling process,
6421 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6422static void pseudo_exec_argv(nommu_save_t *nommu_save,
6423 char **argv, int assignment_cnt,
6424 char **argv_expanded) NORETURN;
6425static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6426 char **argv, int assignment_cnt,
6427 char **argv_expanded)
6428{
6429 char **new_env;
6430
6431 new_env = expand_assignments(argv, assignment_cnt);
6432 dump_cmd_in_x_mode(new_env);
6433
6434 if (!argv[assignment_cnt]) {
6435 /* Case when we are here: ... | var=val | ...
6436 * (note that we do not exit early, i.e., do not optimize out
6437 * expand_assignments(): think about ... | var=`sleep 1` | ...
6438 */
6439 free_strings(new_env);
6440 _exit(EXIT_SUCCESS);
6441 }
6442
6443#if BB_MMU
6444 set_vars_and_save_old(new_env);
6445 free(new_env); /* optional */
6446 /* we can also destroy set_vars_and_save_old's return value,
6447 * to save memory */
6448#else
6449 nommu_save->new_env = new_env;
6450 nommu_save->old_vars = set_vars_and_save_old(new_env);
6451#endif
6452
6453 if (argv_expanded) {
6454 argv = argv_expanded;
6455 } else {
6456 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6457#if !BB_MMU
6458 nommu_save->argv = argv;
6459#endif
6460 }
6461 dump_cmd_in_x_mode(argv);
6462
6463#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6464 if (strchr(argv[0], '/') != NULL)
6465 goto skip;
6466#endif
6467
6468 /* Check if the command matches any of the builtins.
6469 * Depending on context, this might be redundant. But it's
6470 * easier to waste a few CPU cycles than it is to figure out
6471 * if this is one of those cases.
6472 */
6473 {
6474 /* On NOMMU, it is more expensive to re-execute shell
6475 * just in order to run echo or test builtin.
6476 * It's better to skip it here and run corresponding
6477 * non-builtin later. */
6478 const struct built_in_command *x;
6479 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6480 if (x) {
6481 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6482 }
6483 }
6484#if ENABLE_HUSH_FUNCTIONS
6485 /* Check if the command matches any functions */
6486 {
6487 const struct function *funcp = find_function(argv[0]);
6488 if (funcp) {
6489 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6490 }
6491 }
6492#endif
6493
6494#if ENABLE_FEATURE_SH_STANDALONE
6495 /* Check if the command matches any busybox applets */
6496 {
6497 int a = find_applet_by_name(argv[0]);
6498 if (a >= 0) {
6499# if BB_MMU /* see above why on NOMMU it is not allowed */
6500 if (APPLET_IS_NOEXEC(a)) {
6501 debug_printf_exec("running applet '%s'\n", argv[0]);
6502 run_applet_no_and_exit(a, argv);
6503 }
6504# endif
6505 /* Re-exec ourselves */
6506 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006507 /* Don't propagate SIG_IGN to the child */
6508 if (SPECIAL_JOBSTOP_SIGS != 0)
6509 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006510 execv(bb_busybox_exec_path, argv);
6511 /* If they called chroot or otherwise made the binary no longer
6512 * executable, fall through */
6513 }
6514 }
6515#endif
6516
6517#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6518 skip:
6519#endif
6520 execvp_or_die(argv);
6521}
6522
6523/* Called after [v]fork() in run_pipe
6524 */
6525static void pseudo_exec(nommu_save_t *nommu_save,
6526 struct command *command,
6527 char **argv_expanded) NORETURN;
6528static void pseudo_exec(nommu_save_t *nommu_save,
6529 struct command *command,
6530 char **argv_expanded)
6531{
6532 if (command->argv) {
6533 pseudo_exec_argv(nommu_save, command->argv,
6534 command->assignment_cnt, argv_expanded);
6535 }
6536
6537 if (command->group) {
6538 /* Cases when we are here:
6539 * ( list )
6540 * { list } &
6541 * ... | ( list ) | ...
6542 * ... | { list } | ...
6543 */
6544#if BB_MMU
6545 int rcode;
6546 debug_printf_exec("pseudo_exec: run_list\n");
6547 reset_traps_to_defaults();
6548 rcode = run_list(command->group);
6549 /* OK to leak memory by not calling free_pipe_list,
6550 * since this process is about to exit */
6551 _exit(rcode);
6552#else
6553 re_execute_shell(&nommu_save->argv_from_re_execing,
6554 command->group_as_string,
6555 G.global_argv[0],
6556 G.global_argv + 1,
6557 NULL);
6558#endif
6559 }
6560
6561 /* Case when we are here: ... | >file */
6562 debug_printf_exec("pseudo_exec'ed null command\n");
6563 _exit(EXIT_SUCCESS);
6564}
6565
6566#if ENABLE_HUSH_JOB
6567static const char *get_cmdtext(struct pipe *pi)
6568{
6569 char **argv;
6570 char *p;
6571 int len;
6572
6573 /* This is subtle. ->cmdtext is created only on first backgrounding.
6574 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6575 * On subsequent bg argv is trashed, but we won't use it */
6576 if (pi->cmdtext)
6577 return pi->cmdtext;
6578 argv = pi->cmds[0].argv;
6579 if (!argv || !argv[0]) {
6580 pi->cmdtext = xzalloc(1);
6581 return pi->cmdtext;
6582 }
6583
6584 len = 0;
6585 do {
6586 len += strlen(*argv) + 1;
6587 } while (*++argv);
6588 p = xmalloc(len);
6589 pi->cmdtext = p;
6590 argv = pi->cmds[0].argv;
6591 do {
6592 len = strlen(*argv);
6593 memcpy(p, *argv, len);
6594 p += len;
6595 *p++ = ' ';
6596 } while (*++argv);
6597 p[-1] = '\0';
6598 return pi->cmdtext;
6599}
6600
6601static void insert_bg_job(struct pipe *pi)
6602{
6603 struct pipe *job, **jobp;
6604 int i;
6605
6606 /* Linear search for the ID of the job to use */
6607 pi->jobid = 1;
6608 for (job = G.job_list; job; job = job->next)
6609 if (job->jobid >= pi->jobid)
6610 pi->jobid = job->jobid + 1;
6611
6612 /* Add job to the list of running jobs */
6613 jobp = &G.job_list;
6614 while ((job = *jobp) != NULL)
6615 jobp = &job->next;
6616 job = *jobp = xmalloc(sizeof(*job));
6617
6618 *job = *pi; /* physical copy */
6619 job->next = NULL;
6620 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6621 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6622 for (i = 0; i < pi->num_cmds; i++) {
6623 job->cmds[i].pid = pi->cmds[i].pid;
6624 /* all other fields are not used and stay zero */
6625 }
6626 job->cmdtext = xstrdup(get_cmdtext(pi));
6627
6628 if (G_interactive_fd)
6629 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6630 G.last_jobid = job->jobid;
6631}
6632
6633static void remove_bg_job(struct pipe *pi)
6634{
6635 struct pipe *prev_pipe;
6636
6637 if (pi == G.job_list) {
6638 G.job_list = pi->next;
6639 } else {
6640 prev_pipe = G.job_list;
6641 while (prev_pipe->next != pi)
6642 prev_pipe = prev_pipe->next;
6643 prev_pipe->next = pi->next;
6644 }
6645 if (G.job_list)
6646 G.last_jobid = G.job_list->jobid;
6647 else
6648 G.last_jobid = 0;
6649}
6650
6651/* Remove a backgrounded job */
6652static void delete_finished_bg_job(struct pipe *pi)
6653{
6654 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006655 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006656}
6657#endif /* JOB */
6658
6659/* Check to see if any processes have exited -- if they
6660 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006661static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006662{
6663 int attributes;
6664 int status;
6665#if ENABLE_HUSH_JOB
6666 struct pipe *pi;
6667#endif
6668 pid_t childpid;
6669 int rcode = 0;
6670
6671 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6672
6673 attributes = WUNTRACED;
6674 if (fg_pipe == NULL)
6675 attributes |= WNOHANG;
6676
6677 errno = 0;
6678#if ENABLE_HUSH_FAST
6679 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6680//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6681//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6682 /* There was neither fork nor SIGCHLD since last waitpid */
6683 /* Avoid doing waitpid syscall if possible */
6684 if (!G.we_have_children) {
6685 errno = ECHILD;
6686 return -1;
6687 }
6688 if (fg_pipe == NULL) { /* is WNOHANG set? */
6689 /* We have children, but they did not exit
6690 * or stop yet (we saw no SIGCHLD) */
6691 return 0;
6692 }
6693 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6694 }
6695#endif
6696
6697/* Do we do this right?
6698 * bash-3.00# sleep 20 | false
6699 * <ctrl-Z pressed>
6700 * [3]+ Stopped sleep 20 | false
6701 * bash-3.00# echo $?
6702 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6703 * [hush 1.14.0: yes we do it right]
6704 */
6705 wait_more:
6706 while (1) {
6707 int i;
6708 int dead;
6709
6710#if ENABLE_HUSH_FAST
6711 i = G.count_SIGCHLD;
6712#endif
6713 childpid = waitpid(-1, &status, attributes);
6714 if (childpid <= 0) {
6715 if (childpid && errno != ECHILD)
6716 bb_perror_msg("waitpid");
6717#if ENABLE_HUSH_FAST
6718 else { /* Until next SIGCHLD, waitpid's are useless */
6719 G.we_have_children = (childpid == 0);
6720 G.handled_SIGCHLD = i;
6721//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6722 }
6723#endif
6724 break;
6725 }
6726 dead = WIFEXITED(status) || WIFSIGNALED(status);
6727
6728#if DEBUG_JOBS
6729 if (WIFSTOPPED(status))
6730 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6731 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6732 if (WIFSIGNALED(status))
6733 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6734 childpid, WTERMSIG(status), WEXITSTATUS(status));
6735 if (WIFEXITED(status))
6736 debug_printf_jobs("pid %d exited, exitcode %d\n",
6737 childpid, WEXITSTATUS(status));
6738#endif
6739 /* Were we asked to wait for fg pipe? */
6740 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006741 i = fg_pipe->num_cmds;
6742 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006743 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6744 if (fg_pipe->cmds[i].pid != childpid)
6745 continue;
6746 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006747 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006748 fg_pipe->cmds[i].pid = 0;
6749 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006750 ex = WEXITSTATUS(status);
6751 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006752 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006753 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6754 */
6755 if (WIFSIGNALED(status)) {
6756 int sig = WTERMSIG(status);
6757 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006758 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6759 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6760 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006761 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6762 * Maybe we need to use sig | 128? */
6763 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006764 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006765 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006766 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006767 fg_pipe->stopped_cmds++;
6768 }
6769 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6770 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006771 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006772 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006773 i = fg_pipe->num_cmds;
6774 while (--i >= 0) {
6775 rcode = fg_pipe->cmds[i].cmd_exitcode;
6776 /* usually last process gives overall exitstatus,
6777 * but with "set -o pipefail", last *failed* process does */
6778 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6779 break;
6780 }
6781 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006782/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6783 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6784 * and "killall -STOP cat" */
6785 if (G_interactive_fd) {
6786#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006787 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006788 insert_bg_job(fg_pipe);
6789#endif
6790 return rcode;
6791 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006792 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006793 return rcode;
6794 }
6795 /* There are still running processes in the fg pipe */
6796 goto wait_more; /* do waitpid again */
6797 }
6798 /* it wasnt fg_pipe, look for process in bg pipes */
6799 }
6800
6801#if ENABLE_HUSH_JOB
6802 /* We asked to wait for bg or orphaned children */
6803 /* No need to remember exitcode in this case */
6804 for (pi = G.job_list; pi; pi = pi->next) {
6805 for (i = 0; i < pi->num_cmds; i++) {
6806 if (pi->cmds[i].pid == childpid)
6807 goto found_pi_and_prognum;
6808 }
6809 }
6810 /* Happens when shell is used as init process (init=/bin/sh) */
6811 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6812 continue; /* do waitpid again */
6813
6814 found_pi_and_prognum:
6815 if (dead) {
6816 /* child exited */
6817 pi->cmds[i].pid = 0;
6818 pi->alive_cmds--;
6819 if (!pi->alive_cmds) {
6820 if (G_interactive_fd)
6821 printf(JOB_STATUS_FORMAT, pi->jobid,
6822 "Done", pi->cmdtext);
6823 delete_finished_bg_job(pi);
6824 }
6825 } else {
6826 /* child stopped */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006827 pi->stopped_cmds++;
6828 }
6829#endif
6830 } /* while (waitpid succeeds)... */
6831
6832 return rcode;
6833}
6834
6835#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006836static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006837{
6838 pid_t p;
6839 int rcode = checkjobs(fg_pipe);
6840 if (G_saved_tty_pgrp) {
6841 /* Job finished, move the shell to the foreground */
6842 p = getpgrp(); /* our process group id */
6843 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6844 tcsetpgrp(G_interactive_fd, p);
6845 }
6846 return rcode;
6847}
6848#endif
6849
6850/* Start all the jobs, but don't wait for anything to finish.
6851 * See checkjobs().
6852 *
6853 * Return code is normally -1, when the caller has to wait for children
6854 * to finish to determine the exit status of the pipe. If the pipe
6855 * is a simple builtin command, however, the action is done by the
6856 * time run_pipe returns, and the exit code is provided as the
6857 * return value.
6858 *
6859 * Returns -1 only if started some children. IOW: we have to
6860 * mask out retvals of builtins etc with 0xff!
6861 *
6862 * The only case when we do not need to [v]fork is when the pipe
6863 * is single, non-backgrounded, non-subshell command. Examples:
6864 * cmd ; ... { list } ; ...
6865 * cmd && ... { list } && ...
6866 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006867 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006868 * or (if SH_STANDALONE) an applet, and we can run the { list }
6869 * with run_list. If it isn't one of these, we fork and exec cmd.
6870 *
6871 * Cases when we must fork:
6872 * non-single: cmd | cmd
6873 * backgrounded: cmd & { list } &
6874 * subshell: ( list ) [&]
6875 */
6876#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006877#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006878 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6879#endif
6880static int redirect_and_varexp_helper(char ***new_env_p,
6881 struct variable **old_vars_p,
6882 struct command *command,
6883 int squirrel[3],
6884 char **argv_expanded)
6885{
6886 /* setup_redirects acts on file descriptors, not FILEs.
6887 * This is perfect for work that comes after exec().
6888 * Is it really safe for inline use? Experimentally,
6889 * things seem to work. */
6890 int rcode = setup_redirects(command, squirrel);
6891 if (rcode == 0) {
6892 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6893 *new_env_p = new_env;
6894 dump_cmd_in_x_mode(new_env);
6895 dump_cmd_in_x_mode(argv_expanded);
6896 if (old_vars_p)
6897 *old_vars_p = set_vars_and_save_old(new_env);
6898 }
6899 return rcode;
6900}
6901static NOINLINE int run_pipe(struct pipe *pi)
6902{
6903 static const char *const null_ptr = NULL;
6904
6905 int cmd_no;
6906 int next_infd;
6907 struct command *command;
6908 char **argv_expanded;
6909 char **argv;
6910 /* it is not always needed, but we aim to smaller code */
6911 int squirrel[] = { -1, -1, -1 };
6912 int rcode;
6913
6914 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6915 debug_enter();
6916
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006917 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6918 * Result should be 3 lines: q w e, qwe, q w e
6919 */
6920 G.ifs = get_local_var_value("IFS");
6921 if (!G.ifs)
6922 G.ifs = defifs;
6923
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006924 IF_HUSH_JOB(pi->pgrp = -1;)
6925 pi->stopped_cmds = 0;
6926 command = &pi->cmds[0];
6927 argv_expanded = NULL;
6928
6929 if (pi->num_cmds != 1
6930 || pi->followup == PIPE_BG
6931 || command->cmd_type == CMD_SUBSHELL
6932 ) {
6933 goto must_fork;
6934 }
6935
6936 pi->alive_cmds = 1;
6937
6938 debug_printf_exec(": group:%p argv:'%s'\n",
6939 command->group, command->argv ? command->argv[0] : "NONE");
6940
6941 if (command->group) {
6942#if ENABLE_HUSH_FUNCTIONS
6943 if (command->cmd_type == CMD_FUNCDEF) {
6944 /* "executing" func () { list } */
6945 struct function *funcp;
6946
6947 funcp = new_function(command->argv[0]);
6948 /* funcp->name is already set to argv[0] */
6949 funcp->body = command->group;
6950# if !BB_MMU
6951 funcp->body_as_string = command->group_as_string;
6952 command->group_as_string = NULL;
6953# endif
6954 command->group = NULL;
6955 command->argv[0] = NULL;
6956 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6957 funcp->parent_cmd = command;
6958 command->child_func = funcp;
6959
6960 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6961 debug_leave();
6962 return EXIT_SUCCESS;
6963 }
6964#endif
6965 /* { list } */
6966 debug_printf("non-subshell group\n");
6967 rcode = 1; /* exitcode if redir failed */
6968 if (setup_redirects(command, squirrel) == 0) {
6969 debug_printf_exec(": run_list\n");
6970 rcode = run_list(command->group) & 0xff;
6971 }
6972 restore_redirects(squirrel);
6973 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6974 debug_leave();
6975 debug_printf_exec("run_pipe: return %d\n", rcode);
6976 return rcode;
6977 }
6978
6979 argv = command->argv ? command->argv : (char **) &null_ptr;
6980 {
6981 const struct built_in_command *x;
6982#if ENABLE_HUSH_FUNCTIONS
6983 const struct function *funcp;
6984#else
6985 enum { funcp = 0 };
6986#endif
6987 char **new_env = NULL;
6988 struct variable *old_vars = NULL;
6989
6990 if (argv[command->assignment_cnt] == NULL) {
6991 /* Assignments, but no command */
6992 /* Ensure redirects take effect (that is, create files).
6993 * Try "a=t >file" */
6994#if 0 /* A few cases in testsuite fail with this code. FIXME */
6995 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6996 /* Set shell variables */
6997 if (new_env) {
6998 argv = new_env;
6999 while (*argv) {
7000 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7001 /* Do we need to flag set_local_var() errors?
7002 * "assignment to readonly var" and "putenv error"
7003 */
7004 argv++;
7005 }
7006 }
7007 /* Redirect error sets $? to 1. Otherwise,
7008 * if evaluating assignment value set $?, retain it.
7009 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7010 if (rcode == 0)
7011 rcode = G.last_exitcode;
7012 /* Exit, _skipping_ variable restoring code: */
7013 goto clean_up_and_ret0;
7014
7015#else /* Older, bigger, but more correct code */
7016
7017 rcode = setup_redirects(command, squirrel);
7018 restore_redirects(squirrel);
7019 /* Set shell variables */
7020 if (G_x_mode)
7021 bb_putchar_stderr('+');
7022 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007023 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007024 if (G_x_mode)
7025 fprintf(stderr, " %s", p);
7026 debug_printf_exec("set shell var:'%s'->'%s'\n",
7027 *argv, p);
7028 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7029 /* Do we need to flag set_local_var() errors?
7030 * "assignment to readonly var" and "putenv error"
7031 */
7032 argv++;
7033 }
7034 if (G_x_mode)
7035 bb_putchar_stderr('\n');
7036 /* Redirect error sets $? to 1. Otherwise,
7037 * if evaluating assignment value set $?, retain it.
7038 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7039 if (rcode == 0)
7040 rcode = G.last_exitcode;
7041 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7042 debug_leave();
7043 debug_printf_exec("run_pipe: return %d\n", rcode);
7044 return rcode;
7045#endif
7046 }
7047
7048 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007049#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007050 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007051 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007052 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007053#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007054 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007055 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7056 }
7057
7058 /* if someone gives us an empty string: `cmd with empty output` */
7059 if (!argv_expanded[0]) {
7060 free(argv_expanded);
7061 debug_leave();
7062 return G.last_exitcode;
7063 }
7064
7065 x = find_builtin(argv_expanded[0]);
7066#if ENABLE_HUSH_FUNCTIONS
7067 funcp = NULL;
7068 if (!x)
7069 funcp = find_function(argv_expanded[0]);
7070#endif
7071 if (x || funcp) {
7072 if (!funcp) {
7073 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7074 debug_printf("exec with redirects only\n");
7075 rcode = setup_redirects(command, NULL);
7076 goto clean_up_and_ret1;
7077 }
7078 }
7079 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7080 if (rcode == 0) {
7081 if (!funcp) {
7082 debug_printf_exec(": builtin '%s' '%s'...\n",
7083 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007084 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007085 rcode = x->b_function(argv_expanded) & 0xff;
7086 fflush_all();
7087 }
7088#if ENABLE_HUSH_FUNCTIONS
7089 else {
7090# if ENABLE_HUSH_LOCAL
7091 struct variable **sv;
7092 sv = G.shadowed_vars_pp;
7093 G.shadowed_vars_pp = &old_vars;
7094# endif
7095 debug_printf_exec(": function '%s' '%s'...\n",
7096 funcp->name, argv_expanded[1]);
7097 rcode = run_function(funcp, argv_expanded) & 0xff;
7098# if ENABLE_HUSH_LOCAL
7099 G.shadowed_vars_pp = sv;
7100# endif
7101 }
7102#endif
7103 }
7104 clean_up_and_ret:
7105 unset_vars(new_env);
7106 add_vars(old_vars);
7107/* clean_up_and_ret0: */
7108 restore_redirects(squirrel);
7109 clean_up_and_ret1:
7110 free(argv_expanded);
7111 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7112 debug_leave();
7113 debug_printf_exec("run_pipe return %d\n", rcode);
7114 return rcode;
7115 }
7116
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007117 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007118 int n = find_applet_by_name(argv_expanded[0]);
7119 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7120 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7121 if (rcode == 0) {
7122 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7123 argv_expanded[0], argv_expanded[1]);
7124 rcode = run_nofork_applet(n, argv_expanded);
7125 }
7126 goto clean_up_and_ret;
7127 }
7128 }
7129 /* It is neither builtin nor applet. We must fork. */
7130 }
7131
7132 must_fork:
7133 /* NB: argv_expanded may already be created, and that
7134 * might include `cmd` runs! Do not rerun it! We *must*
7135 * use argv_expanded if it's non-NULL */
7136
7137 /* Going to fork a child per each pipe member */
7138 pi->alive_cmds = 0;
7139 next_infd = 0;
7140
7141 cmd_no = 0;
7142 while (cmd_no < pi->num_cmds) {
7143 struct fd_pair pipefds;
7144#if !BB_MMU
7145 volatile nommu_save_t nommu_save;
7146 nommu_save.new_env = NULL;
7147 nommu_save.old_vars = NULL;
7148 nommu_save.argv = NULL;
7149 nommu_save.argv_from_re_execing = NULL;
7150#endif
7151 command = &pi->cmds[cmd_no];
7152 cmd_no++;
7153 if (command->argv) {
7154 debug_printf_exec(": pipe member '%s' '%s'...\n",
7155 command->argv[0], command->argv[1]);
7156 } else {
7157 debug_printf_exec(": pipe member with no argv\n");
7158 }
7159
7160 /* pipes are inserted between pairs of commands */
7161 pipefds.rd = 0;
7162 pipefds.wr = 1;
7163 if (cmd_no < pi->num_cmds)
7164 xpiped_pair(pipefds);
7165
7166 command->pid = BB_MMU ? fork() : vfork();
7167 if (!command->pid) { /* child */
7168#if ENABLE_HUSH_JOB
7169 disable_restore_tty_pgrp_on_exit();
7170 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7171
7172 /* Every child adds itself to new process group
7173 * with pgid == pid_of_first_child_in_pipe */
7174 if (G.run_list_level == 1 && G_interactive_fd) {
7175 pid_t pgrp;
7176 pgrp = pi->pgrp;
7177 if (pgrp < 0) /* true for 1st process only */
7178 pgrp = getpid();
7179 if (setpgid(0, pgrp) == 0
7180 && pi->followup != PIPE_BG
7181 && G_saved_tty_pgrp /* we have ctty */
7182 ) {
7183 /* We do it in *every* child, not just first,
7184 * to avoid races */
7185 tcsetpgrp(G_interactive_fd, pgrp);
7186 }
7187 }
7188#endif
7189 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7190 /* 1st cmd in backgrounded pipe
7191 * should have its stdin /dev/null'ed */
7192 close(0);
7193 if (open(bb_dev_null, O_RDONLY))
7194 xopen("/", O_RDONLY);
7195 } else {
7196 xmove_fd(next_infd, 0);
7197 }
7198 xmove_fd(pipefds.wr, 1);
7199 if (pipefds.rd > 1)
7200 close(pipefds.rd);
7201 /* Like bash, explicit redirects override pipes,
7202 * and the pipe fd is available for dup'ing. */
7203 if (setup_redirects(command, NULL))
7204 _exit(1);
7205
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007206 /* Stores to nommu_save list of env vars putenv'ed
7207 * (NOMMU, on MMU we don't need that) */
7208 /* cast away volatility... */
7209 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7210 /* pseudo_exec() does not return */
7211 }
7212
7213 /* parent or error */
7214#if ENABLE_HUSH_FAST
7215 G.count_SIGCHLD++;
7216//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7217#endif
7218 enable_restore_tty_pgrp_on_exit();
7219#if !BB_MMU
7220 /* Clean up after vforked child */
7221 free(nommu_save.argv);
7222 free(nommu_save.argv_from_re_execing);
7223 unset_vars(nommu_save.new_env);
7224 add_vars(nommu_save.old_vars);
7225#endif
7226 free(argv_expanded);
7227 argv_expanded = NULL;
7228 if (command->pid < 0) { /* [v]fork failed */
7229 /* Clearly indicate, was it fork or vfork */
7230 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7231 } else {
7232 pi->alive_cmds++;
7233#if ENABLE_HUSH_JOB
7234 /* Second and next children need to know pid of first one */
7235 if (pi->pgrp < 0)
7236 pi->pgrp = command->pid;
7237#endif
7238 }
7239
7240 if (cmd_no > 1)
7241 close(next_infd);
7242 if (cmd_no < pi->num_cmds)
7243 close(pipefds.wr);
7244 /* Pass read (output) pipe end to next iteration */
7245 next_infd = pipefds.rd;
7246 }
7247
7248 if (!pi->alive_cmds) {
7249 debug_leave();
7250 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7251 return 1;
7252 }
7253
7254 debug_leave();
7255 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7256 return -1;
7257}
7258
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007259/* NB: called by pseudo_exec, and therefore must not modify any
7260 * global data until exec/_exit (we can be a child after vfork!) */
7261static int run_list(struct pipe *pi)
7262{
7263#if ENABLE_HUSH_CASE
7264 char *case_word = NULL;
7265#endif
7266#if ENABLE_HUSH_LOOPS
7267 struct pipe *loop_top = NULL;
7268 char **for_lcur = NULL;
7269 char **for_list = NULL;
7270#endif
7271 smallint last_followup;
7272 smalluint rcode;
7273#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7274 smalluint cond_code = 0;
7275#else
7276 enum { cond_code = 0 };
7277#endif
7278#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007279 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007280 smallint last_rword; /* ditto */
7281#endif
7282
7283 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7284 debug_enter();
7285
7286#if ENABLE_HUSH_LOOPS
7287 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007288 {
7289 struct pipe *cpipe;
7290 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7291 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7292 continue;
7293 /* current word is FOR or IN (BOLD in comments below) */
7294 if (cpipe->next == NULL) {
7295 syntax_error("malformed for");
7296 debug_leave();
7297 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7298 return 1;
7299 }
7300 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7301 if (cpipe->next->res_word == RES_DO)
7302 continue;
7303 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7304 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7305 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7306 ) {
7307 syntax_error("malformed for");
7308 debug_leave();
7309 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7310 return 1;
7311 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007312 }
7313 }
7314#endif
7315
7316 /* Past this point, all code paths should jump to ret: label
7317 * in order to return, no direct "return" statements please.
7318 * This helps to ensure that no memory is leaked. */
7319
7320#if ENABLE_HUSH_JOB
7321 G.run_list_level++;
7322#endif
7323
7324#if HAS_KEYWORDS
7325 rword = RES_NONE;
7326 last_rword = RES_XXXX;
7327#endif
7328 last_followup = PIPE_SEQ;
7329 rcode = G.last_exitcode;
7330
7331 /* Go through list of pipes, (maybe) executing them. */
7332 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7333 if (G.flag_SIGINT)
7334 break;
7335
7336 IF_HAS_KEYWORDS(rword = pi->res_word;)
7337 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7338 rword, cond_code, last_rword);
7339#if ENABLE_HUSH_LOOPS
7340 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7341 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7342 ) {
7343 /* start of a loop: remember where loop starts */
7344 loop_top = pi;
7345 G.depth_of_loop++;
7346 }
7347#endif
7348 /* Still in the same "if...", "then..." or "do..." branch? */
7349 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7350 if ((rcode == 0 && last_followup == PIPE_OR)
7351 || (rcode != 0 && last_followup == PIPE_AND)
7352 ) {
7353 /* It is "<true> || CMD" or "<false> && CMD"
7354 * and we should not execute CMD */
7355 debug_printf_exec("skipped cmd because of || or &&\n");
7356 last_followup = pi->followup;
7357 continue;
7358 }
7359 }
7360 last_followup = pi->followup;
7361 IF_HAS_KEYWORDS(last_rword = rword;)
7362#if ENABLE_HUSH_IF
7363 if (cond_code) {
7364 if (rword == RES_THEN) {
7365 /* if false; then ... fi has exitcode 0! */
7366 G.last_exitcode = rcode = EXIT_SUCCESS;
7367 /* "if <false> THEN cmd": skip cmd */
7368 continue;
7369 }
7370 } else {
7371 if (rword == RES_ELSE || rword == RES_ELIF) {
7372 /* "if <true> then ... ELSE/ELIF cmd":
7373 * skip cmd and all following ones */
7374 break;
7375 }
7376 }
7377#endif
7378#if ENABLE_HUSH_LOOPS
7379 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7380 if (!for_lcur) {
7381 /* first loop through for */
7382
7383 static const char encoded_dollar_at[] ALIGN1 = {
7384 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7385 }; /* encoded representation of "$@" */
7386 static const char *const encoded_dollar_at_argv[] = {
7387 encoded_dollar_at, NULL
7388 }; /* argv list with one element: "$@" */
7389 char **vals;
7390
7391 vals = (char**)encoded_dollar_at_argv;
7392 if (pi->next->res_word == RES_IN) {
7393 /* if no variable values after "in" we skip "for" */
7394 if (!pi->next->cmds[0].argv) {
7395 G.last_exitcode = rcode = EXIT_SUCCESS;
7396 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7397 break;
7398 }
7399 vals = pi->next->cmds[0].argv;
7400 } /* else: "for var; do..." -> assume "$@" list */
7401 /* create list of variable values */
7402 debug_print_strings("for_list made from", vals);
7403 for_list = expand_strvec_to_strvec(vals);
7404 for_lcur = for_list;
7405 debug_print_strings("for_list", for_list);
7406 }
7407 if (!*for_lcur) {
7408 /* "for" loop is over, clean up */
7409 free(for_list);
7410 for_list = NULL;
7411 for_lcur = NULL;
7412 break;
7413 }
7414 /* Insert next value from for_lcur */
7415 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7416 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7417 continue;
7418 }
7419 if (rword == RES_IN) {
7420 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7421 }
7422 if (rword == RES_DONE) {
7423 continue; /* "done" has no cmds too */
7424 }
7425#endif
7426#if ENABLE_HUSH_CASE
7427 if (rword == RES_CASE) {
7428 case_word = expand_strvec_to_string(pi->cmds->argv);
7429 continue;
7430 }
7431 if (rword == RES_MATCH) {
7432 char **argv;
7433
7434 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7435 break;
7436 /* all prev words didn't match, does this one match? */
7437 argv = pi->cmds->argv;
7438 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007439 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007440 /* TODO: which FNM_xxx flags to use? */
7441 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7442 free(pattern);
7443 if (cond_code == 0) { /* match! we will execute this branch */
7444 free(case_word); /* make future "word)" stop */
7445 case_word = NULL;
7446 break;
7447 }
7448 argv++;
7449 }
7450 continue;
7451 }
7452 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7453 if (cond_code != 0)
7454 continue; /* not matched yet, skip this pipe */
7455 }
7456#endif
7457 /* Just pressing <enter> in shell should check for jobs.
7458 * OTOH, in non-interactive shell this is useless
7459 * and only leads to extra job checks */
7460 if (pi->num_cmds == 0) {
7461 if (G_interactive_fd)
7462 goto check_jobs_and_continue;
7463 continue;
7464 }
7465
7466 /* After analyzing all keywords and conditions, we decided
7467 * to execute this pipe. NB: have to do checkjobs(NULL)
7468 * after run_pipe to collect any background children,
7469 * even if list execution is to be stopped. */
7470 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7471 {
7472 int r;
7473#if ENABLE_HUSH_LOOPS
7474 G.flag_break_continue = 0;
7475#endif
7476 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7477 if (r != -1) {
7478 /* We ran a builtin, function, or group.
7479 * rcode is already known
7480 * and we don't need to wait for anything. */
7481 G.last_exitcode = rcode;
7482 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007483 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007484#if ENABLE_HUSH_LOOPS
7485 /* Was it "break" or "continue"? */
7486 if (G.flag_break_continue) {
7487 smallint fbc = G.flag_break_continue;
7488 /* We might fall into outer *loop*,
7489 * don't want to break it too */
7490 if (loop_top) {
7491 G.depth_break_continue--;
7492 if (G.depth_break_continue == 0)
7493 G.flag_break_continue = 0;
7494 /* else: e.g. "continue 2" should *break* once, *then* continue */
7495 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7496 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7497 goto check_jobs_and_break;
7498 /* "continue": simulate end of loop */
7499 rword = RES_DONE;
7500 continue;
7501 }
7502#endif
7503#if ENABLE_HUSH_FUNCTIONS
7504 if (G.flag_return_in_progress == 1) {
7505 /* same as "goto check_jobs_and_break" */
7506 checkjobs(NULL);
7507 break;
7508 }
7509#endif
7510 } else if (pi->followup == PIPE_BG) {
7511 /* What does bash do with attempts to background builtins? */
7512 /* even bash 3.2 doesn't do that well with nested bg:
7513 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7514 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007515 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007516#if ENABLE_HUSH_JOB
7517 if (G.run_list_level == 1)
7518 insert_bg_job(pi);
7519#endif
7520 /* Last command's pid goes to $! */
7521 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7522 G.last_exitcode = rcode = EXIT_SUCCESS;
7523 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7524 } else {
7525#if ENABLE_HUSH_JOB
7526 if (G.run_list_level == 1 && G_interactive_fd) {
7527 /* Waits for completion, then fg's main shell */
7528 rcode = checkjobs_and_fg_shell(pi);
7529 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007530 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007531 } else
7532#endif
7533 { /* This one just waits for completion */
7534 rcode = checkjobs(pi);
7535 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007536 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007537 }
7538 G.last_exitcode = rcode;
7539 }
7540 }
7541
7542 /* Analyze how result affects subsequent commands */
7543#if ENABLE_HUSH_IF
7544 if (rword == RES_IF || rword == RES_ELIF)
7545 cond_code = rcode;
7546#endif
7547#if ENABLE_HUSH_LOOPS
7548 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007549 if (pi->next
7550 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02007551 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007552 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007553 if (rword == RES_WHILE) {
7554 if (rcode) {
7555 /* "while false; do...done" - exitcode 0 */
7556 G.last_exitcode = rcode = EXIT_SUCCESS;
7557 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7558 goto check_jobs_and_break;
7559 }
7560 }
7561 if (rword == RES_UNTIL) {
7562 if (!rcode) {
7563 debug_printf_exec(": until expr is true: breaking\n");
7564 check_jobs_and_break:
7565 checkjobs(NULL);
7566 break;
7567 }
7568 }
7569 }
7570#endif
7571
7572 check_jobs_and_continue:
7573 checkjobs(NULL);
7574 } /* for (pi) */
7575
7576#if ENABLE_HUSH_JOB
7577 G.run_list_level--;
7578#endif
7579#if ENABLE_HUSH_LOOPS
7580 if (loop_top)
7581 G.depth_of_loop--;
7582 free(for_list);
7583#endif
7584#if ENABLE_HUSH_CASE
7585 free(case_word);
7586#endif
7587 debug_leave();
7588 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7589 return rcode;
7590}
7591
7592/* Select which version we will use */
7593static int run_and_free_list(struct pipe *pi)
7594{
7595 int rcode = 0;
7596 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007597 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007598 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7599 rcode = run_list(pi);
7600 }
7601 /* free_pipe_list has the side effect of clearing memory.
7602 * In the long run that function can be merged with run_list,
7603 * but doing that now would hobble the debugging effort. */
7604 free_pipe_list(pi);
7605 debug_printf_exec("run_and_free_list return %d\n", rcode);
7606 return rcode;
7607}
7608
7609
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007610static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007611{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007612 sighandler_t old_handler;
7613 unsigned sig = 0;
7614 while ((mask >>= 1) != 0) {
7615 sig++;
7616 if (!(mask & 1))
7617 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007618 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007619 /* POSIX allows shell to re-enable SIGCHLD
7620 * even if it was SIG_IGN on entry.
7621 * Therefore we skip IGN check for it:
7622 */
7623 if (sig == SIGCHLD)
7624 continue;
7625 if (old_handler == SIG_IGN) {
7626 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007627 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007628 if (!G.traps)
7629 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7630 free(G.traps[sig]);
7631 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7632 }
7633 }
7634}
7635
7636/* Called a few times only (or even once if "sh -c") */
7637static void install_special_sighandlers(void)
7638{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007639 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007640
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007641 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007642 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007643 if (G_interactive_fd) {
7644 mask |= SPECIAL_INTERACTIVE_SIGS;
7645 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007646 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007647 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007648 /* Careful, do not re-install handlers we already installed */
7649 if (G.special_sig_mask != mask) {
7650 unsigned diff = mask & ~G.special_sig_mask;
7651 G.special_sig_mask = mask;
7652 install_sighandlers(diff);
7653 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007654}
7655
7656#if ENABLE_HUSH_JOB
7657/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007658/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007659static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007660{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007661 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007662
7663 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007664 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007665 + (1 << SIGILL ) * HUSH_DEBUG
7666 + (1 << SIGFPE ) * HUSH_DEBUG
7667 + (1 << SIGBUS ) * HUSH_DEBUG
7668 + (1 << SIGSEGV) * HUSH_DEBUG
7669 + (1 << SIGTRAP) * HUSH_DEBUG
7670 + (1 << SIGABRT)
7671 /* bash 3.2 seems to handle these just like 'fatal' ones */
7672 + (1 << SIGPIPE)
7673 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007674 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007675 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007676 * we never want to restore pgrp on exit, and this fn is not called
7677 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007678 /*+ (1 << SIGHUP )*/
7679 /*+ (1 << SIGTERM)*/
7680 /*+ (1 << SIGINT )*/
7681 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007682 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007683
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007684 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007685}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007686#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007687
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007688static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007689{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007690 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007691 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007692 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007693 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007694 break;
7695 case 'x':
7696 IF_HUSH_MODE_X(G_x_mode = state;)
7697 break;
7698 case 'o':
7699 if (!o_opt) {
7700 /* "set -+o" without parameter.
7701 * in bash, set -o produces this output:
7702 * pipefail off
7703 * and set +o:
7704 * set +o pipefail
7705 * We always use the second form.
7706 */
7707 const char *p = o_opt_strings;
7708 idx = 0;
7709 while (*p) {
7710 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7711 idx++;
7712 p += strlen(p) + 1;
7713 }
7714 break;
7715 }
7716 idx = index_in_strings(o_opt_strings, o_opt);
7717 if (idx >= 0) {
7718 G.o_opt[idx] = state;
7719 break;
7720 }
7721 default:
7722 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007723 }
7724 return EXIT_SUCCESS;
7725}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007726
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007727int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007728int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007729{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007730 enum {
7731 OPT_login = (1 << 0),
7732 };
7733 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00007734 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007735 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007736 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007737 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007738 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007739
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007740 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02007741 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007742 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenko10c01312011-05-11 11:49:21 +02007743#if ENABLE_HUSH_FAST
7744 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7745#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007746#if !BB_MMU
7747 G.argv0_for_re_execing = argv[0];
7748#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007749 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007750 shell_ver = xzalloc(sizeof(*shell_ver));
7751 shell_ver->flg_export = 1;
7752 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007753 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007754 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007755 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007756 /* Create shell local variables from the values
7757 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007758 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007759 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007760 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007761 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007762 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007763 if (e) while (*e) {
7764 char *value = strchr(*e, '=');
7765 if (value) { /* paranoia */
7766 cur_var->next = xzalloc(sizeof(*cur_var));
7767 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007768 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007769 cur_var->max_len = strlen(*e);
7770 cur_var->flg_export = 1;
7771 }
7772 e++;
7773 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007774 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007775 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7776 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007777
7778 /* Export PWD */
7779 set_pwd_var(/*exp:*/ 1);
7780 /* bash also exports SHLVL and _,
7781 * and sets (but doesn't export) the following variables:
7782 * BASH=/bin/bash
7783 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7784 * BASH_VERSION='3.2.0(1)-release'
7785 * HOSTTYPE=i386
7786 * MACHTYPE=i386-pc-linux-gnu
7787 * OSTYPE=linux-gnu
7788 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007789 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007790 * EUID=<NNNNN>
7791 * UID=<NNNNN>
7792 * GROUPS=()
7793 * LINES=<NNN>
7794 * COLUMNS=<NNN>
7795 * BASH_ARGC=()
7796 * BASH_ARGV=()
7797 * BASH_LINENO=()
7798 * BASH_SOURCE=()
7799 * DIRSTACK=()
7800 * PIPESTATUS=([0]="0")
7801 * HISTFILE=/<xxx>/.bash_history
7802 * HISTFILESIZE=500
7803 * HISTSIZE=500
7804 * MAILCHECK=60
7805 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7806 * SHELL=/bin/bash
7807 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7808 * TERM=dumb
7809 * OPTERR=1
7810 * OPTIND=1
7811 * IFS=$' \t\n'
7812 * PS1='\s-\v\$ '
7813 * PS2='> '
7814 * PS4='+ '
7815 */
7816
Denis Vlasenko38f63192007-01-22 09:03:07 +00007817#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02007818 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007819#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007820
Eric Andersen94ac2442001-05-22 19:05:18 +00007821 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007822 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007823
Denis Vlasenkoed782372009-04-10 00:45:02 +00007824 if (setjmp(die_jmp)) {
7825 /* xfunc has failed! die die die */
7826 /* no EXIT traps, this is an escape hatch! */
7827 G.exiting = 1;
7828 hush_exit(xfunc_error_retval);
7829 }
7830
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007831 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007832 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007833 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007834 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007835 * in order to intercept (more) signals.
7836 */
7837
7838 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007839 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007840 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007841 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007842 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007843 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007844#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007845 "<:$:R:V:"
7846# if ENABLE_HUSH_FUNCTIONS
7847 "F:"
7848# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007849#endif
7850 );
7851 if (opt <= 0)
7852 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007853 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007854 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007855 /* Possibilities:
7856 * sh ... -c 'script'
7857 * sh ... -c 'script' ARG0 [ARG1...]
7858 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007859 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007860 * "" needs to be replaced with NULL
7861 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007862 * Note: the form without ARG0 never happens:
7863 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007864 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007865 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007866 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007867 G.root_ppid = getppid();
7868 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007869 G.global_argv = argv + optind;
7870 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007871 if (builtin_argc) {
7872 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7873 const struct built_in_command *x;
7874
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007875 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007876 x = find_builtin(optarg);
7877 if (x) { /* paranoia */
7878 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7879 G.global_argv += builtin_argc;
7880 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007881 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007882 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007883 }
7884 goto final_return;
7885 }
7886 if (!G.global_argv[0]) {
7887 /* -c 'script' (no params): prevent empty $0 */
7888 G.global_argv--; /* points to argv[i] of 'script' */
7889 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007890 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007891 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007892 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007893 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007894 goto final_return;
7895 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007896 /* Well, we cannot just declare interactiveness,
7897 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007898 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007899 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007900 case 's':
7901 /* "-s" means "read from stdin", but this is how we always
7902 * operate, so simply do nothing here. */
7903 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007904 case 'l':
7905 flags |= OPT_login;
7906 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007907#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007908 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007909 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007910 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007911 case '$': {
7912 unsigned long long empty_trap_mask;
7913
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007914 G.root_pid = bb_strtou(optarg, &optarg, 16);
7915 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007916 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7917 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007918 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7919 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007920 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007921 optarg++;
7922 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007923 optarg++;
7924 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7925 if (empty_trap_mask != 0) {
7926 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007927 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007928 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7929 for (sig = 1; sig < NSIG; sig++) {
7930 if (empty_trap_mask & (1LL << sig)) {
7931 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007932 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007933 }
7934 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007935 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007936# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007937 optarg++;
7938 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007939# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007940 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007941 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007942 case 'R':
7943 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007944 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007945 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007946# if ENABLE_HUSH_FUNCTIONS
7947 case 'F': {
7948 struct function *funcp = new_function(optarg);
7949 /* funcp->name is already set to optarg */
7950 /* funcp->body is set to NULL. It's a special case. */
7951 funcp->body_as_string = argv[optind];
7952 optind++;
7953 break;
7954 }
7955# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007956#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007957 case 'n':
7958 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007959 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007960 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007961 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007962#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007963 fprintf(stderr, "Usage: sh [FILE]...\n"
7964 " or: sh -c command [args]...\n\n");
7965 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007966#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007967 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007968#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007969 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007970 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007971
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007972 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7973 G.global_argc = argc - (optind - 1);
7974 G.global_argv = argv + (optind - 1);
7975 G.global_argv[0] = argv[0];
7976
Denys Vlasenkodea47882009-10-09 15:40:49 +02007977 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007978 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007979 G.root_ppid = getppid();
7980 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007981
7982 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007983 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007984 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007985 debug_printf("sourcing /etc/profile\n");
7986 input = fopen_for_read("/etc/profile");
7987 if (input != NULL) {
7988 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007989 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007990 parse_and_run_file(input);
7991 fclose(input);
7992 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007993 /* bash: after sourcing /etc/profile,
7994 * tries to source (in the given order):
7995 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007996 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007997 * bash also sources ~/.bash_logout on exit.
7998 * If called as sh, skips .bash_XXX files.
7999 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008000 }
8001
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008002 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008003 FILE *input;
8004 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008005 * "bash <script>" (which is never interactive (unless -i?))
8006 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008007 * If called as sh, does the same but with $ENV.
8008 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008009 G.global_argc--;
8010 G.global_argv++;
8011 debug_printf("running script '%s'\n", G.global_argv[0]);
8012 input = xfopen_for_read(G.global_argv[0]);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008013 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008014 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008015 parse_and_run_file(input);
8016#if ENABLE_FEATURE_CLEAN_UP
8017 fclose(input);
8018#endif
8019 goto final_return;
8020 }
8021
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008022 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008023 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008024 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008025
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008026 /* A shell is interactive if the '-i' flag was given,
8027 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008028 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008029 * no arguments remaining or the -s flag given
8030 * standard input is a terminal
8031 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008032 * Refer to Posix.2, the description of the 'sh' utility.
8033 */
8034#if ENABLE_HUSH_JOB
8035 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008036 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8037 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8038 if (G_saved_tty_pgrp < 0)
8039 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008040
8041 /* try to dup stdin to high fd#, >= 255 */
8042 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8043 if (G_interactive_fd < 0) {
8044 /* try to dup to any fd */
8045 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008046 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008047 /* give up */
8048 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008049 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008050 }
8051 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008052// TODO: track & disallow any attempts of user
8053// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008054 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008055 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008056 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008057 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008058
Mike Frysinger38478a62009-05-20 04:48:06 -04008059 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008060 /* If we were run as 'hush &', sleep until we are
8061 * in the foreground (tty pgrp == our pgrp).
8062 * If we get started under a job aware app (like bash),
8063 * make sure we are now in charge so we don't fight over
8064 * who gets the foreground */
8065 while (1) {
8066 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008067 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8068 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008069 break;
8070 /* send TTIN to ourself (should stop us) */
8071 kill(- shell_pgrp, SIGTTIN);
8072 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008073 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008074
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008075 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008076 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008077
Mike Frysinger38478a62009-05-20 04:48:06 -04008078 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008079 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008080 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008081 /* Put ourselves in our own process group
8082 * (bash, too, does this only if ctty is available) */
8083 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8084 /* Grab control of the terminal */
8085 tcsetpgrp(G_interactive_fd, getpid());
8086 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00008087 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00008088 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00008089 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008090
8091# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8092 {
8093 const char *hp = get_local_var_value("HISTFILE");
8094 if (!hp) {
8095 hp = get_local_var_value("HOME");
8096 if (hp)
8097 hp = concat_path_file(hp, ".hush_history");
8098 } else {
8099 hp = xstrdup(hp);
8100 }
8101 if (hp) {
8102 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008103 //set_local_var(xasprintf("HISTFILE=%s", ...));
8104 }
8105# if ENABLE_FEATURE_SH_HISTFILESIZE
8106 hp = get_local_var_value("HISTFILESIZE");
8107 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8108# endif
8109 }
8110# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008111 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008112 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008113 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008114#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008115 /* No job control compiled in, only prompt/line editing */
8116 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008117 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8118 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008119 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008120 G_interactive_fd = dup(STDIN_FILENO);
8121 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008122 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008123 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008124 }
8125 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008126 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008127 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008128 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008129 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008130#else
8131 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008132 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008133#endif
8134 /* bash:
8135 * if interactive but not a login shell, sources ~/.bashrc
8136 * (--norc turns this off, --rcfile <file> overrides)
8137 */
8138
8139 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008140 /* note: ash and hush share this string */
8141 printf("\n\n%s %s\n"
8142 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8143 "\n",
8144 bb_banner,
8145 "hush - the humble shell"
8146 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008147 }
8148
Denis Vlasenkof9375282009-04-05 19:13:39 +00008149 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008150
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008151 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008152 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008153}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008154
8155
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008156#if ENABLE_MSH
8157int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8158int msh_main(int argc, char **argv)
8159{
8160 //bb_error_msg("msh is deprecated, please use hush instead");
8161 return hush_main(argc, argv);
8162}
8163#endif
8164
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008165
8166/*
8167 * Built-ins
8168 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008169static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008170{
8171 return 0;
8172}
8173
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008174static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008175{
8176 int argc = 0;
8177 while (*argv) {
8178 argc++;
8179 argv++;
8180 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008181 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008182}
8183
8184static int FAST_FUNC builtin_test(char **argv)
8185{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008186 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008187}
8188
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008189static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008190{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008191 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008192}
8193
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008194#if ENABLE_PRINTF
8195static int FAST_FUNC builtin_printf(char **argv)
8196{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008197 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008198}
8199#endif
8200
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008201static char **skip_dash_dash(char **argv)
8202{
8203 argv++;
8204 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8205 argv++;
8206 return argv;
8207}
8208
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008209static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008210{
8211 int rcode = EXIT_SUCCESS;
8212
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008213 argv = skip_dash_dash(argv);
8214 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008215 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008216 /* bash:
8217 * eval "echo Hi; done" ("done" is syntax error):
8218 * "echo Hi" will not execute too.
8219 */
8220 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008221 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008222 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008223 }
8224 return rcode;
8225}
8226
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008227static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008228{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008229 const char *newdir;
8230
8231 argv = skip_dash_dash(argv);
8232 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008233 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008234 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008235 * bash says "bash: cd: HOME not set" and does nothing
8236 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008237 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008238 const char *home = get_local_var_value("HOME");
8239 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008240 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008241 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008242 /* Mimic bash message exactly */
8243 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008244 return EXIT_FAILURE;
8245 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008246 /* Read current dir (get_cwd(1) is inside) and set PWD.
8247 * Note: do not enforce exporting. If PWD was unset or unexported,
8248 * set it again, but do not export. bash does the same.
8249 */
8250 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008251 return EXIT_SUCCESS;
8252}
8253
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008254static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008255{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008256 argv = skip_dash_dash(argv);
8257 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008258 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008259
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008260 /* Careful: we can end up here after [v]fork. Do not restore
8261 * tty pgrp then, only top-level shell process does that */
8262 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8263 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8264
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008265 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008266 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008267 * and tcsetpgrp, and this is inherently racy.
8268 */
8269 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008270}
8271
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008272static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008273{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008274 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008275
8276 /* interactive bash:
8277 * # trap "echo EEE" EXIT
8278 * # exit
8279 * exit
8280 * There are stopped jobs.
8281 * (if there are _stopped_ jobs, running ones don't count)
8282 * # exit
8283 * exit
8284 # EEE (then bash exits)
8285 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008286 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008287 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008288
8289 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008290 argv = skip_dash_dash(argv);
8291 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008292 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008293 /* mimic bash: exit 123abc == exit 255 + error msg */
8294 xfunc_error_retval = 255;
8295 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008296 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008297}
8298
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008299static void print_escaped(const char *s)
8300{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008301 if (*s == '\'')
8302 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008303 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008304 const char *p = strchrnul(s, '\'');
8305 /* print 'xxxx', possibly just '' */
8306 printf("'%.*s'", (int)(p - s), s);
8307 if (*p == '\0')
8308 break;
8309 s = p;
8310 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008311 /* s points to '; print "'''...'''" */
8312 putchar('"');
8313 do putchar('\''); while (*++s == '\'');
8314 putchar('"');
8315 } while (*s);
8316}
8317
Denys Vlasenko295fef82009-06-03 12:47:26 +02008318#if !ENABLE_HUSH_LOCAL
8319#define helper_export_local(argv, exp, lvl) \
8320 helper_export_local(argv, exp)
8321#endif
8322static void helper_export_local(char **argv, int exp, int lvl)
8323{
8324 do {
8325 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008326 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008327
8328 /* So far we do not check that name is valid (TODO?) */
8329
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008330 if (*name_end == '\0') {
8331 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008332
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008333 vpp = get_ptr_to_local_var(name, name_end - name);
8334 var = vpp ? *vpp : NULL;
8335
Denys Vlasenko295fef82009-06-03 12:47:26 +02008336 if (exp == -1) { /* unexporting? */
8337 /* export -n NAME (without =VALUE) */
8338 if (var) {
8339 var->flg_export = 0;
8340 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8341 unsetenv(name);
8342 } /* else: export -n NOT_EXISTING_VAR: no-op */
8343 continue;
8344 }
8345 if (exp == 1) { /* exporting? */
8346 /* export NAME (without =VALUE) */
8347 if (var) {
8348 var->flg_export = 1;
8349 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8350 putenv(var->varstr);
8351 continue;
8352 }
8353 }
8354 /* Exporting non-existing variable.
8355 * bash does not put it in environment,
8356 * but remembers that it is exported,
8357 * and does put it in env when it is set later.
8358 * We just set it to "" and export. */
8359 /* Or, it's "local NAME" (without =VALUE).
8360 * bash sets the value to "". */
8361 name = xasprintf("%s=", name);
8362 } else {
8363 /* (Un)exporting/making local NAME=VALUE */
8364 name = xstrdup(name);
8365 }
8366 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8367 } while (*++argv);
8368}
8369
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008370static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008371{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008372 unsigned opt_unexport;
8373
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008374#if ENABLE_HUSH_EXPORT_N
8375 /* "!": do not abort on errors */
8376 opt_unexport = getopt32(argv, "!n");
8377 if (opt_unexport == (uint32_t)-1)
8378 return EXIT_FAILURE;
8379 argv += optind;
8380#else
8381 opt_unexport = 0;
8382 argv++;
8383#endif
8384
8385 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008386 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008387 if (e) {
8388 while (*e) {
8389#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008390 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008391#else
8392 /* ash emits: export VAR='VAL'
8393 * bash: declare -x VAR="VAL"
8394 * we follow ash example */
8395 const char *s = *e++;
8396 const char *p = strchr(s, '=');
8397
8398 if (!p) /* wtf? take next variable */
8399 continue;
8400 /* export var= */
8401 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008402 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008403 putchar('\n');
8404#endif
8405 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008406 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008407 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008408 return EXIT_SUCCESS;
8409 }
8410
Denys Vlasenko295fef82009-06-03 12:47:26 +02008411 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008412
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008413 return EXIT_SUCCESS;
8414}
8415
Denys Vlasenko295fef82009-06-03 12:47:26 +02008416#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008417static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008418{
8419 if (G.func_nest_level == 0) {
8420 bb_error_msg("%s: not in a function", argv[0]);
8421 return EXIT_FAILURE; /* bash compat */
8422 }
8423 helper_export_local(argv, 0, G.func_nest_level);
8424 return EXIT_SUCCESS;
8425}
8426#endif
8427
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008428static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008429{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008430 int sig;
8431 char *new_cmd;
8432
8433 if (!G.traps)
8434 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8435
8436 argv++;
8437 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008438 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008439 /* No args: print all trapped */
8440 for (i = 0; i < NSIG; ++i) {
8441 if (G.traps[i]) {
8442 printf("trap -- ");
8443 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008444 /* note: bash adds "SIG", but only if invoked
8445 * as "bash". If called as "sh", or if set -o posix,
8446 * then it prints short signal names.
8447 * We are printing short names: */
8448 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008449 }
8450 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008451 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008452 return EXIT_SUCCESS;
8453 }
8454
8455 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008456 /* If first arg is a number: reset all specified signals */
8457 sig = bb_strtou(*argv, NULL, 10);
8458 if (errno == 0) {
8459 int ret;
8460 process_sig_list:
8461 ret = EXIT_SUCCESS;
8462 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008463 sighandler_t handler;
8464
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008465 sig = get_signum(*argv++);
8466 if (sig < 0 || sig >= NSIG) {
8467 ret = EXIT_FAILURE;
8468 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008469 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008470 continue;
8471 }
8472
8473 free(G.traps[sig]);
8474 G.traps[sig] = xstrdup(new_cmd);
8475
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008476 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008477 get_signame(sig), sig, G.traps[sig]);
8478
8479 /* There is no signal for 0 (EXIT) */
8480 if (sig == 0)
8481 continue;
8482
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008483 if (new_cmd)
8484 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8485 else
8486 /* We are removing trap handler */
8487 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02008488 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008489 }
8490 return ret;
8491 }
8492
8493 if (!argv[1]) { /* no second arg */
8494 bb_error_msg("trap: invalid arguments");
8495 return EXIT_FAILURE;
8496 }
8497
8498 /* First arg is "-": reset all specified to default */
8499 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8500 /* Everything else: set arg as signal handler
8501 * (includes "" case, which ignores signal) */
8502 if (argv[0][0] == '-') {
8503 if (argv[0][1] == '\0') { /* "-" */
8504 /* new_cmd remains NULL: "reset these sigs" */
8505 goto reset_traps;
8506 }
8507 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8508 argv++;
8509 }
8510 /* else: "-something", no special meaning */
8511 }
8512 new_cmd = *argv;
8513 reset_traps:
8514 argv++;
8515 goto process_sig_list;
8516}
8517
Mike Frysinger93cadc22009-05-27 17:06:25 -04008518/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008519static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008520{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008521 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008522
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008523 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008524 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008525 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008526
8527 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008528 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008529 type = "an alias";*/
8530#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008531 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008532 type = "a function";
8533#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008534 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008535 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008536 else if ((path = find_in_path(*argv)) != NULL)
8537 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008538 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008539 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008540 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008541 continue;
8542 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008543
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008544 printf("%s is %s\n", *argv, type);
8545 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008546 }
8547
8548 return ret;
8549}
8550
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008551#if ENABLE_HUSH_JOB
8552/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008553static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008554{
8555 int i, jobnum;
8556 struct pipe *pi;
8557
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008558 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008559 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008560
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008561 /* If they gave us no args, assume they want the last backgrounded task */
8562 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008563 for (pi = G.job_list; pi; pi = pi->next) {
8564 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008565 goto found;
8566 }
8567 }
8568 bb_error_msg("%s: no current job", argv[0]);
8569 return EXIT_FAILURE;
8570 }
8571 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8572 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8573 return EXIT_FAILURE;
8574 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008575 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008576 if (pi->jobid == jobnum) {
8577 goto found;
8578 }
8579 }
8580 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8581 return EXIT_FAILURE;
8582 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008583 /* TODO: bash prints a string representation
8584 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008585 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008586 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008587 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008588 }
8589
8590 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008591 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8592 for (i = 0; i < pi->num_cmds; i++) {
8593 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008594 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008595 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008596
8597 i = kill(- pi->pgrp, SIGCONT);
8598 if (i < 0) {
8599 if (errno == ESRCH) {
8600 delete_finished_bg_job(pi);
8601 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008602 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008603 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008604 }
8605
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008606 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008607 remove_bg_job(pi);
8608 return checkjobs_and_fg_shell(pi);
8609 }
8610 return EXIT_SUCCESS;
8611}
8612#endif
8613
8614#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008615static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008616{
8617 const struct built_in_command *x;
8618
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008619 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008620 "Built-in commands:\n"
8621 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008622 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008623 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008624 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008625 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008626 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008627 return EXIT_SUCCESS;
8628}
8629#endif
8630
8631#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008632static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008633{
8634 struct pipe *job;
8635 const char *status_string;
8636
Denis Vlasenko87a86552008-07-29 19:43:10 +00008637 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008638 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008639 status_string = "Stopped";
8640 else
8641 status_string = "Running";
8642
8643 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8644 }
8645 return EXIT_SUCCESS;
8646}
8647#endif
8648
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008649#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008650static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008651{
8652 void *p;
8653 unsigned long l;
8654
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008655# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008656 /* Optional. Reduces probability of false positives */
8657 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008658# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008659 /* Crude attempt to find where "free memory" starts,
8660 * sans fragmentation. */
8661 p = malloc(240);
8662 l = (unsigned long)p;
8663 free(p);
8664 p = malloc(3400);
8665 if (l < (unsigned long)p) l = (unsigned long)p;
8666 free(p);
8667
8668 if (!G.memleak_value)
8669 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008670
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008671 l -= G.memleak_value;
8672 if ((long)l < 0)
8673 l = 0;
8674 l /= 1024;
8675 if (l > 127)
8676 l = 127;
8677
8678 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8679 return l;
8680}
8681#endif
8682
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008683static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008684{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008685 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008686 return EXIT_SUCCESS;
8687}
8688
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008689/* Interruptibility of read builtin in bash
8690 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8691 *
8692 * Empty trap makes read ignore corresponding signal, for any signal.
8693 *
8694 * SIGINT:
8695 * - terminates non-interactive shell;
8696 * - interrupts read in interactive shell;
8697 * if it has non-empty trap:
8698 * - executes trap and returns to command prompt in interactive shell;
8699 * - executes trap and returns to read in non-interactive shell;
8700 * SIGTERM:
8701 * - is ignored (does not interrupt) read in interactive shell;
8702 * - terminates non-interactive shell;
8703 * if it has non-empty trap:
8704 * - executes trap and returns to read;
8705 * SIGHUP:
8706 * - terminates shell (regardless of interactivity);
8707 * if it has non-empty trap:
8708 * - executes trap and returns to read;
8709 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008710static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008711{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008712 const char *r;
8713 char *opt_n = NULL;
8714 char *opt_p = NULL;
8715 char *opt_t = NULL;
8716 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008717 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01008718 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008719
Denys Vlasenko03dad222010-01-12 23:29:57 +01008720 /* "!": do not abort on errors.
8721 * Option string must start with "sr" to match BUILTIN_READ_xxx
8722 */
8723 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8724 if (read_flags == (uint32_t)-1)
8725 return EXIT_FAILURE;
8726 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008727 ifs = get_local_var_value("IFS"); /* can be NULL */
8728
8729 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01008730 r = shell_builtin_read(set_local_var_from_halves,
8731 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008732 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01008733 read_flags,
8734 opt_n,
8735 opt_p,
8736 opt_t,
8737 opt_u
8738 );
8739
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008740 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008741 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008742 if (sig && sig != SIGINT)
8743 goto again;
8744 }
8745
Denys Vlasenko03dad222010-01-12 23:29:57 +01008746 if ((uintptr_t)r > 1) {
8747 bb_error_msg("%s", r);
8748 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008749 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008750
Denys Vlasenko03dad222010-01-12 23:29:57 +01008751 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008752}
8753
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008754/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8755 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008756 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008757 * set [-abCefhmnuvx] [-o option] [argument...]
8758 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008759 * set -- [argument...]
8760 * set -o
8761 * set +o
8762 * Implementations shall support the options in both their hyphen and
8763 * plus-sign forms. These options can also be specified as options to sh.
8764 * Examples:
8765 * Write out all variables and their values: set
8766 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8767 * Turn on the -x and -v options: set -xv
8768 * Unset all positional parameters: set --
8769 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8770 * Set the positional parameters to the expansion of x, even if x expands
8771 * with a leading '-' or '+': set -- $x
8772 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008773 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008774 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008775static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008776{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008777 int n;
8778 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008779 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008780
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008781 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008782 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008783 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008784 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008785 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008786 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008787
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008788 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008789 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008790 ++argv;
8791 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008792 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008793 if (arg[0] != '+' && arg[0] != '-')
8794 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008795 for (n = 1; arg[n]; ++n) {
8796 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008797 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008798 if (arg[n] == 'o' && argv[1])
8799 argv++;
8800 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008801 } while ((arg = *++argv) != NULL);
8802 /* Now argv[0] is 1st argument */
8803
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008804 if (arg == NULL)
8805 return EXIT_SUCCESS;
8806 set_argv:
8807
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008808 /* NB: G.global_argv[0] ($0) is never freed/changed */
8809 g_argv = G.global_argv;
8810 if (G.global_args_malloced) {
8811 pp = g_argv;
8812 while (*++pp)
8813 free(*pp);
8814 g_argv[1] = NULL;
8815 } else {
8816 G.global_args_malloced = 1;
8817 pp = xzalloc(sizeof(pp[0]) * 2);
8818 pp[0] = g_argv[0]; /* retain $0 */
8819 g_argv = pp;
8820 }
8821 /* This realloc's G.global_argv */
8822 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8823
8824 n = 1;
8825 while (*++pp)
8826 n++;
8827 G.global_argc = n;
8828
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008829 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008830
8831 /* Nothing known, so abort */
8832 error:
8833 bb_error_msg("set: %s: invalid option", arg);
8834 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008835}
8836
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008837static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008838{
8839 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008840 argv = skip_dash_dash(argv);
8841 if (argv[0]) {
8842 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008843 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008844 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008845 if (G.global_args_malloced) {
8846 int m = 1;
8847 while (m <= n)
8848 free(G.global_argv[m++]);
8849 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008850 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008851 memmove(&G.global_argv[1], &G.global_argv[n+1],
8852 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008853 return EXIT_SUCCESS;
8854 }
8855 return EXIT_FAILURE;
8856}
8857
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008858static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008859{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008860 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008861 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008862 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008863#if ENABLE_HUSH_FUNCTIONS
8864 smallint sv_flg;
8865#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008866
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008867 argv = skip_dash_dash(argv);
8868 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008869 if (!filename) {
8870 /* bash says: "bash: .: filename argument required" */
8871 return 2; /* bash compat */
8872 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008873 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008874 if (!strchr(filename, '/')) {
8875 arg_path = find_in_path(filename);
8876 if (arg_path)
8877 filename = arg_path;
8878 }
8879 input = fopen_or_warn(filename, "r");
8880 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008881 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008882 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008883 return EXIT_FAILURE;
8884 }
8885 close_on_exec_on(fileno(input));
8886
Mike Frysinger885b6f22009-04-18 21:04:25 +00008887#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008888 sv_flg = G.flag_return_in_progress;
8889 /* "we are inside sourced file, ok to use return" */
8890 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008891#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008892 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008893
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008894 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008895 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008896
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008897 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008898#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008899 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008900#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008901
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008902 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008903}
8904
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008905static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008906{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008907 int rc;
8908 mode_t mask;
8909
8910 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008911 argv = skip_dash_dash(argv);
8912 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008913 mode_t old_mask = mask;
8914
8915 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008916 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008917 mask ^= 0777;
8918 if (rc == 0) {
8919 mask = old_mask;
8920 /* bash messages:
8921 * bash: umask: 'q': invalid symbolic mode operator
8922 * bash: umask: 999: octal number out of range
8923 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008924 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008925 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008926 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008927 rc = 1;
8928 /* Mimic bash */
8929 printf("%04o\n", (unsigned) mask);
8930 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008931 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008932 umask(mask);
8933
8934 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008935}
8936
Mike Frysingerd690f682009-03-30 06:50:54 +00008937/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008938static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008939{
Mike Frysingerd690f682009-03-30 06:50:54 +00008940 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008941 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008942
Denis Vlasenko28e67962009-04-26 23:22:40 +00008943 /* "!": do not abort on errors */
8944 /* "+": stop at 1st non-option */
8945 opts = getopt32(argv, "!+vf");
8946 if (opts == (unsigned)-1)
8947 return EXIT_FAILURE;
8948 if (opts == 3) {
8949 bb_error_msg("unset: -v and -f are exclusive");
8950 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008951 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008952 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008953
8954 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008955 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008956 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008957 if (unset_local_var(*argv)) {
8958 /* unset <nonexistent_var> doesn't fail.
8959 * Error is when one tries to unset RO var.
8960 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008961 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008962 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008963 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008964#if ENABLE_HUSH_FUNCTIONS
8965 else {
8966 unset_func(*argv);
8967 }
8968#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008969 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008970 }
8971 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008972}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008973
Mike Frysinger56bdea12009-03-28 20:01:58 +00008974/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008975static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008976{
8977 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008978 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008979
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008980 argv = skip_dash_dash(argv);
8981 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008982 /* Don't care about wait results */
8983 /* Note 1: must wait until there are no more children */
8984 /* Note 2: must be interruptible */
8985 /* Examples:
8986 * $ sleep 3 & sleep 6 & wait
8987 * [1] 30934 sleep 3
8988 * [2] 30935 sleep 6
8989 * [1] Done sleep 3
8990 * [2] Done sleep 6
8991 * $ sleep 3 & sleep 6 & wait
8992 * [1] 30936 sleep 3
8993 * [2] 30937 sleep 6
8994 * [1] Done sleep 3
8995 * ^C <-- after ~4 sec from keyboard
8996 * $
8997 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008998 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008999 int sig;
9000 sigset_t oldset, allsigs;
9001
9002 /* waitpid is not interruptible by SA_RESTARTed
9003 * signals which we use. Thus, this ugly dance:
9004 */
9005
9006 /* Make sure possible SIGCHLD is stored in kernel's
9007 * pending signal mask before we call waitpid.
9008 * Or else we may race with SIGCHLD, lose it,
9009 * and get stuck in sigwaitinfo...
9010 */
9011 sigfillset(&allsigs);
9012 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9013
9014 if (!sigisemptyset(&G.pending_set)) {
9015 /* Crap! we raced with some signal! */
9016 // sig = 0;
9017 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009018 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009019
9020 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9021 if (errno == ECHILD) {
9022 sigprocmask(SIG_SETMASK, &oldset, NULL);
9023 break;
9024 }
9025
9026 /* Wait for SIGCHLD or any other signal */
9027 //sig = sigwaitinfo(&allsigs, NULL);
9028 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9029 /* Note: sigsuspend invokes signal handler */
9030 sigsuspend(&oldset);
9031 restore:
9032 sigprocmask(SIG_SETMASK, &oldset, NULL);
9033
9034 /* So, did we get a signal? */
9035 //if (sig > 0)
9036 // raise(sig); /* run handler */
9037 sig = check_and_run_traps();
9038 if (sig /*&& sig != SIGCHLD - always true */) {
9039 /* see note 2 */
9040 ret = 128 + sig;
9041 break;
9042 }
9043 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009044 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009045 return ret;
9046 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009047
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009048 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009049 while (*argv) {
9050 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00009051 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009052 /* mimic bash message */
9053 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009054 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009055 }
9056 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00009057 if (WIFSIGNALED(status))
9058 ret = 128 + WTERMSIG(status);
9059 else if (WIFEXITED(status))
9060 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00009061 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00009062 ret = EXIT_FAILURE;
9063 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009064 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009065 ret = 127;
9066 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00009067 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009068 }
9069
9070 return ret;
9071}
9072
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009073#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9074static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9075{
9076 if (argv[1]) {
9077 def = bb_strtou(argv[1], NULL, 10);
9078 if (errno || def < def_min || argv[2]) {
9079 bb_error_msg("%s: bad arguments", argv[0]);
9080 def = UINT_MAX;
9081 }
9082 }
9083 return def;
9084}
9085#endif
9086
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009087#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009088static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009089{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009090 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009091 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009092 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009093 return EXIT_SUCCESS; /* bash compat */
9094 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009095 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009096
9097 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9098 if (depth == UINT_MAX)
9099 G.flag_break_continue = BC_BREAK;
9100 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009101 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009102
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009103 return EXIT_SUCCESS;
9104}
9105
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009106static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009107{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009108 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9109 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009110}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009111#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009112
9113#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009114static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009115{
9116 int rc;
9117
9118 if (G.flag_return_in_progress != -1) {
9119 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9120 return EXIT_FAILURE; /* bash compat */
9121 }
9122
9123 G.flag_return_in_progress = 1;
9124
9125 /* bash:
9126 * out of range: wraps around at 256, does not error out
9127 * non-numeric param:
9128 * f() { false; return qwe; }; f; echo $?
9129 * bash: return: qwe: numeric argument required <== we do this
9130 * 255 <== we also do this
9131 */
9132 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9133 return rc;
9134}
9135#endif