blob: 7b0ea8b0c1d4c1445637dbfc10e46644b8fe3b63 [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 Vlasenkoff463a82013-05-12 02:45:23 +0200853#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200854static int builtin_history(char **argv) FAST_FUNC;
855#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200856#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200857static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200858#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000859#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200860static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000861#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400862#if ENABLE_PRINTF
863static int builtin_printf(char **argv) FAST_FUNC;
864#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200865static int builtin_pwd(char **argv) FAST_FUNC;
866static int builtin_read(char **argv) FAST_FUNC;
867static int builtin_set(char **argv) FAST_FUNC;
868static int builtin_shift(char **argv) FAST_FUNC;
869static int builtin_source(char **argv) FAST_FUNC;
870static int builtin_test(char **argv) FAST_FUNC;
871static int builtin_trap(char **argv) FAST_FUNC;
872static int builtin_type(char **argv) FAST_FUNC;
873static int builtin_true(char **argv) FAST_FUNC;
874static int builtin_umask(char **argv) FAST_FUNC;
875static int builtin_unset(char **argv) FAST_FUNC;
876static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000877#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200878static int builtin_break(char **argv) FAST_FUNC;
879static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000880#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000881#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200882static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000883#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000884
885/* Table of built-in functions. They can be forked or not, depending on
886 * context: within pipes, they fork. As simple commands, they do not.
887 * When used in non-forking context, they can change global variables
888 * in the parent shell process. If forked, of course they cannot.
889 * For example, 'unset foo | whatever' will parse and run, but foo will
890 * still be set at the end. */
891struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100892 const char *b_cmd;
893 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000894#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100895 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200896# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000897#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200898# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000899#endif
900};
901
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200902static const struct built_in_command bltins1[] = {
903 BLTIN("." , builtin_source , "Run commands in a file"),
904 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000905#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200906 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000907#endif
908#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200909 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000910#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200911 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000912#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200913 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000914#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200915 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
916 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
917 BLTIN("exit" , builtin_exit , "Exit"),
918 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000919#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200920 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000921#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000922#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200923 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000924#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200925#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200926 BLTIN("history" , builtin_history , "Show command history"),
927#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000928#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200929 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000930#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200931#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200932 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200933#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000934#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200935 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000936#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200937 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000938#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200939 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000940#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200941 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
942 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200943#if ENABLE_HUSH_BASH_COMPAT
944 BLTIN("source" , builtin_source , "Run commands in a file"),
945#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200946 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko2bba5912014-03-14 12:43:57 +0100947 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100948 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100949 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200950 BLTIN("umask" , builtin_umask , "Set file creation mask"),
951 BLTIN("unset" , builtin_unset , "Unset variables"),
952 BLTIN("wait" , builtin_wait , "Wait for process"),
953};
954/* For now, echo and test are unconditionally enabled.
955 * Maybe make it configurable? */
956static const struct built_in_command bltins2[] = {
957 BLTIN("[" , builtin_test , NULL),
958 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400959#if ENABLE_PRINTF
960 BLTIN("printf" , builtin_printf , NULL),
961#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200962 BLTIN("pwd" , builtin_pwd , NULL),
963 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000964};
965
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000966
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000967/* Debug printouts.
968 */
969#if HUSH_DEBUG
970/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100971# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000972# define debug_enter() (G.debug_indent++)
973# define debug_leave() (G.debug_indent--)
974#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200975# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000976# define debug_enter() ((void)0)
977# define debug_leave() ((void)0)
978#endif
979
980#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100981# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000982#endif
983
984#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100985# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000986#endif
987
988#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100989#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000990#endif
991
992#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100993# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000994#endif
995
996#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100997# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000998# define DEBUG_JOBS 1
999#else
1000# define DEBUG_JOBS 0
1001#endif
1002
1003#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001004# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001005# define DEBUG_EXPAND 1
1006#else
1007# define DEBUG_EXPAND 0
1008#endif
1009
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001010#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001011# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001012#endif
1013
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001014#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001015# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001016# define DEBUG_GLOB 1
1017#else
1018# define DEBUG_GLOB 0
1019#endif
1020
1021#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001022# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001023#endif
1024
1025#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001026# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001027#endif
1028
1029#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001030# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001031# define DEBUG_CLEAN 1
1032#else
1033# define DEBUG_CLEAN 0
1034#endif
1035
1036#if DEBUG_EXPAND
1037static void debug_print_strings(const char *prefix, char **vv)
1038{
1039 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001040 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001041 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001042 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001043}
1044#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001045# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001046#endif
1047
1048
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001049/* Leak hunting. Use hush_leaktool.sh for post-processing.
1050 */
1051#if LEAK_HUNTING
1052static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001053{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001054 void *ptr = xmalloc((size + 0xff) & ~0xff);
1055 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1056 return ptr;
1057}
1058static void *xxrealloc(int lineno, void *ptr, size_t size)
1059{
1060 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1061 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1062 return ptr;
1063}
1064static char *xxstrdup(int lineno, const char *str)
1065{
1066 char *ptr = xstrdup(str);
1067 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1068 return ptr;
1069}
1070static void xxfree(void *ptr)
1071{
1072 fdprintf(2, "free %p\n", ptr);
1073 free(ptr);
1074}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001075# define xmalloc(s) xxmalloc(__LINE__, s)
1076# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1077# define xstrdup(s) xxstrdup(__LINE__, s)
1078# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001079#endif
1080
1081
1082/* Syntax and runtime errors. They always abort scripts.
1083 * In interactive use they usually discard unparsed and/or unexecuted commands
1084 * and return to the prompt.
1085 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1086 */
1087#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001088# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001089# define syntax_error(lineno, msg) syntax_error(msg)
1090# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1091# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1092# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1093# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001094#endif
1095
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001096static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001097{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001098 va_list p;
1099
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001100#if HUSH_DEBUG >= 2
1101 bb_error_msg("hush.c:%u", lineno);
1102#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001103 va_start(p, fmt);
1104 bb_verror_msg(fmt, p, NULL);
1105 va_end(p);
1106 if (!G_interactive_fd)
1107 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001108}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001109
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001110static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001111{
1112 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001113 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001114 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001115 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001116}
1117
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001118static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001119{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001120 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001121}
1122
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001123static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001124{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001125 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001126}
1127
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001128static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001129{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001130 char msg[2] = { ch, '\0' };
1131 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001132}
1133
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001134static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001135{
1136 char msg[2];
1137 msg[0] = ch;
1138 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001139 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001140}
1141
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001142#if HUSH_DEBUG < 2
1143# undef die_if_script
1144# undef syntax_error
1145# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001146# undef syntax_error_unterm_ch
1147# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001148# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001149#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001150# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001151# define syntax_error(msg) syntax_error(__LINE__, msg)
1152# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1153# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1154# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1155# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001156#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001157
Denis Vlasenko552433b2009-04-04 19:29:21 +00001158
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001159#if ENABLE_HUSH_INTERACTIVE
1160static void cmdedit_update_prompt(void);
1161#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001162# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001163#endif
1164
1165
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001166/* Utility functions
1167 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001168/* Replace each \x with x in place, return ptr past NUL. */
1169static char *unbackslash(char *src)
1170{
Denys Vlasenko71885402009-09-24 01:44:13 +02001171 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001172 while (1) {
1173 if (*src == '\\')
1174 src++;
1175 if ((*dst++ = *src++) == '\0')
1176 break;
1177 }
1178 return dst;
1179}
1180
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001181static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001182{
1183 int i;
1184 unsigned count1;
1185 unsigned count2;
1186 char **v;
1187
1188 v = strings;
1189 count1 = 0;
1190 if (v) {
1191 while (*v) {
1192 count1++;
1193 v++;
1194 }
1195 }
1196 count2 = 0;
1197 v = add;
1198 while (*v) {
1199 count2++;
1200 v++;
1201 }
1202 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1203 v[count1 + count2] = NULL;
1204 i = count2;
1205 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001206 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001207 return v;
1208}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001209#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001210static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1211{
1212 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1213 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1214 return ptr;
1215}
1216#define add_strings_to_strings(strings, add, need_to_dup) \
1217 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1218#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001219
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001220/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001221static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001222{
1223 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001224 v[0] = add;
1225 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001226 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001227}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001228#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001229static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1230{
1231 char **ptr = add_string_to_strings(strings, add);
1232 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1233 return ptr;
1234}
1235#define add_string_to_strings(strings, add) \
1236 xx_add_string_to_strings(__LINE__, strings, add)
1237#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001238
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001239static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001240{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001241 char **v;
1242
1243 if (!strings)
1244 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001245 v = strings;
1246 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001247 free(*v);
1248 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001249 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001250 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001251}
1252
Denis Vlasenko76d50412008-06-10 16:19:39 +00001253
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001254/* Helpers for setting new $n and restoring them back
1255 */
1256typedef struct save_arg_t {
1257 char *sv_argv0;
1258 char **sv_g_argv;
1259 int sv_g_argc;
1260 smallint sv_g_malloced;
1261} save_arg_t;
1262
1263static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1264{
1265 int n;
1266
1267 sv->sv_argv0 = argv[0];
1268 sv->sv_g_argv = G.global_argv;
1269 sv->sv_g_argc = G.global_argc;
1270 sv->sv_g_malloced = G.global_args_malloced;
1271
1272 argv[0] = G.global_argv[0]; /* retain $0 */
1273 G.global_argv = argv;
1274 G.global_args_malloced = 0;
1275
1276 n = 1;
1277 while (*++argv)
1278 n++;
1279 G.global_argc = n;
1280}
1281
1282static void restore_G_args(save_arg_t *sv, char **argv)
1283{
1284 char **pp;
1285
1286 if (G.global_args_malloced) {
1287 /* someone ran "set -- arg1 arg2 ...", undo */
1288 pp = G.global_argv;
1289 while (*++pp) /* note: does not free $0 */
1290 free(*pp);
1291 free(G.global_argv);
1292 }
1293 argv[0] = sv->sv_argv0;
1294 G.global_argv = sv->sv_g_argv;
1295 G.global_argc = sv->sv_g_argc;
1296 G.global_args_malloced = sv->sv_g_malloced;
1297}
1298
1299
Denis Vlasenkod5762932009-03-31 11:22:57 +00001300/* Basic theory of signal handling in shell
1301 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001302 * This does not describe what hush does, rather, it is current understanding
1303 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001304 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1305 *
1306 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1307 * is finished or backgrounded. It is the same in interactive and
1308 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001309 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001310 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001311 * backgrounds (i.e. stops) or kills all members of currently running
1312 * pipe.
1313 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001314 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001315 * or by SIGINT in interactive shell.
1316 *
1317 * Trap handlers will execute even within trap handlers. (right?)
1318 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001319 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1320 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001321 *
1322 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001323 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001324 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001325 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001326 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001327 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001328 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001329 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001330 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001331 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001332 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001333 *
1334 * SIGQUIT: ignore
1335 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001336 * SIGHUP (interactive):
1337 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001338 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001339 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1340 * that all pipe members are stopped. Try this in bash:
1341 * while :; do :; done - ^Z does not background it
1342 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001343 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001344 * of the command line, show prompt. NB: ^C does not send SIGINT
1345 * to interactive shell while shell is waiting for a pipe,
1346 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001347 * Example 1: this waits 5 sec, but does not execute ls:
1348 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1349 * Example 2: this does not wait and does not execute ls:
1350 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1351 * Example 3: this does not wait 5 sec, but executes ls:
1352 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001353 * Example 4: this does not wait and does not execute ls:
1354 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001355 *
1356 * (What happens to signals which are IGN on shell start?)
1357 * (What happens with signal mask on shell start?)
1358 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001359 * Old implementation
1360 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001361 * We use in-kernel pending signal mask to determine which signals were sent.
1362 * We block all signals which we don't want to take action immediately,
1363 * i.e. we block all signals which need to have special handling as described
1364 * above, and all signals which have traps set.
1365 * After each pipe execution, we extract any pending signals via sigtimedwait()
1366 * and act on them.
1367 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001368 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001369 * sigset_t blocked_set: current blocked signal set
1370 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001371 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001372 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001373 * "trap 'cmd' SIGxxx":
1374 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001375 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001376 * unblock signals with special interactive handling
1377 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001378 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001379 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001380 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001381 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001382 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001383 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001384 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001385 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001386 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001387 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001388 * Standard says "When a subshell is entered, traps that are not being ignored
1389 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001390 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001391 *
1392 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001393 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001394 * masked signals are not visible!
1395 *
1396 * New implementation
1397 * ==================
1398 * We record each signal we are interested in by installing signal handler
1399 * for them - a bit like emulating kernel pending signal mask in userspace.
1400 * We are interested in: signals which need to have special handling
1401 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001402 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001403 * After each pipe execution, we extract any pending signals
1404 * and act on them.
1405 *
1406 * unsigned special_sig_mask: a mask of shell-special signals.
1407 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1408 * char *traps[sig] if trap for sig is set (even if it's '').
1409 * sigset_t pending_set: set of sigs we received.
1410 *
1411 * "trap - SIGxxx":
1412 * if sig is in special_sig_mask, set handler back to:
1413 * record_pending_signo, or to IGN if it's a tty stop signal
1414 * if sig is in fatal_sig_mask, set handler back to sigexit.
1415 * else: set handler back to SIG_DFL
1416 * "trap 'cmd' SIGxxx":
1417 * set handler to record_pending_signo.
1418 * "trap '' SIGxxx":
1419 * set handler to SIG_IGN.
1420 * after [v]fork, if we plan to be a shell:
1421 * set signals with special interactive handling to SIG_DFL
1422 * (because child shell is not interactive),
1423 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1424 * after [v]fork, if we plan to exec:
1425 * POSIX says fork clears pending signal mask in child - no need to clear it.
1426 *
1427 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1428 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1429 *
1430 * Note (compat):
1431 * Standard says "When a subshell is entered, traps that are not being ignored
1432 * are set to the default actions". bash interprets it so that traps which
1433 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001434 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001435enum {
1436 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001437 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001438 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001439 | (1 << SIGHUP)
1440 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001441 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001442#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001443 | (1 << SIGTTIN)
1444 | (1 << SIGTTOU)
1445 | (1 << SIGTSTP)
1446#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001447 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001448};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001449
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001450static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001451{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001452 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001453#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001454 if (sig == SIGCHLD) {
1455 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001456//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 +02001457 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001458#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001459}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001460
Denys Vlasenko0806e402011-05-12 23:06:20 +02001461static sighandler_t install_sighandler(int sig, sighandler_t handler)
1462{
1463 struct sigaction old_sa;
1464
1465 /* We could use signal() to install handlers... almost:
1466 * except that we need to mask ALL signals while handlers run.
1467 * I saw signal nesting in strace, race window isn't small.
1468 * SA_RESTART is also needed, but in Linux, signal()
1469 * sets SA_RESTART too.
1470 */
1471 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1472 /* sigfillset(&G.sa.sa_mask); - already done */
1473 /* G.sa.sa_flags = SA_RESTART; - already done */
1474 G.sa.sa_handler = handler;
1475 sigaction(sig, &G.sa, &old_sa);
1476 return old_sa.sa_handler;
1477}
1478
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001479#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001480
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001481/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001482# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001483/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001484# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001485
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001486/* Restores tty foreground process group, and exits.
1487 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001488 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001489 * or called directly with -EXITCODE.
1490 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001491static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001492static void sigexit(int sig)
1493{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001494 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001495 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001496 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1497 /* Disable all signals: job control, SIGPIPE, etc.
1498 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1499 */
1500 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001501 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001502 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001503
1504 /* Not a signal, just exit */
1505 if (sig <= 0)
1506 _exit(- sig);
1507
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001508 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001509}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001510#else
1511
Denys Vlasenko8391c482010-05-22 17:50:43 +02001512# define disable_restore_tty_pgrp_on_exit() ((void)0)
1513# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001514
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001515#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001516
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001517static sighandler_t pick_sighandler(unsigned sig)
1518{
1519 sighandler_t handler = SIG_DFL;
1520 if (sig < sizeof(unsigned)*8) {
1521 unsigned sigmask = (1 << sig);
1522
1523#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001524 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001525 if (G_fatal_sig_mask & sigmask)
1526 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001527 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001528#endif
1529 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001530 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001531 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001532 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001533 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001534 * in an endless loop when we try to do some
1535 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001536 */
1537 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1538 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001539 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001540 }
1541 return handler;
1542}
1543
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001544/* Restores tty foreground process group, and exits. */
1545static void hush_exit(int exitcode) NORETURN;
1546static void hush_exit(int exitcode)
1547{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001548#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1549 save_history(G.line_input_state);
1550#endif
1551
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001552 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001553 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001554 char *argv[3];
1555 /* argv[0] is unused */
1556 argv[1] = G.traps[0];
1557 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001558 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001559 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001560 * "trap" will still show it, if executed
1561 * in the handler */
1562 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001563 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001564
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001565#if ENABLE_FEATURE_CLEAN_UP
1566 {
1567 struct variable *cur_var;
1568 if (G.cwd != bb_msg_unknown)
1569 free((char*)G.cwd);
1570 cur_var = G.top_var;
1571 while (cur_var) {
1572 struct variable *tmp = cur_var;
1573 if (!cur_var->max_len)
1574 free(cur_var->varstr);
1575 cur_var = cur_var->next;
1576 free(tmp);
1577 }
1578 }
1579#endif
1580
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001581#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001582 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001583 sigexit(- (exitcode & 0xff));
1584#else
1585 exit(exitcode);
1586#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001587}
1588
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001589
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001590//TODO: return a mask of ALL handled sigs?
1591static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001592{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001593 int last_sig = 0;
1594
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001595 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001596 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001597
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001598 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001599 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001600 sig = 0;
1601 do {
1602 sig++;
1603 if (sigismember(&G.pending_set, sig)) {
1604 sigdelset(&G.pending_set, sig);
1605 goto got_sig;
1606 }
1607 } while (sig < NSIG);
1608 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001609 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001610 if (G.traps && G.traps[sig]) {
1611 if (G.traps[sig][0]) {
1612 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001613 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001614 char *argv[3];
1615 /* argv[0] is unused */
1616 argv[1] = G.traps[sig];
1617 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001618 save_rcode = G.last_exitcode;
1619 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001620 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001621 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001622 } /* else: "" trap, ignoring signal */
1623 continue;
1624 }
1625 /* not a trap: special action */
1626 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001627 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001628 /* Builtin was ^C'ed, make it look prettier: */
1629 bb_putchar('\n');
1630 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001631 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001632 break;
1633#if ENABLE_HUSH_JOB
1634 case SIGHUP: {
1635 struct pipe *job;
1636 /* bash is observed to signal whole process groups,
1637 * not individual processes */
1638 for (job = G.job_list; job; job = job->next) {
1639 if (job->pgrp <= 0)
1640 continue;
1641 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1642 if (kill(- job->pgrp, SIGHUP) == 0)
1643 kill(- job->pgrp, SIGCONT);
1644 }
1645 sigexit(SIGHUP);
1646 }
1647#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001648#if ENABLE_HUSH_FAST
1649 case SIGCHLD:
1650 G.count_SIGCHLD++;
1651//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1652 /* Note:
1653 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1654 * This simplifies wait builtin a bit.
1655 */
1656 break;
1657#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001658 default: /* ignored: */
1659 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001660 /* Note:
1661 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1662 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001663 * in interactive shell, because TERM is ignored.
1664 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001665 break;
1666 }
1667 }
1668 return last_sig;
1669}
1670
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001671
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001672static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001673{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001674 if (force || G.cwd == NULL) {
1675 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1676 * we must not try to free(bb_msg_unknown) */
1677 if (G.cwd == bb_msg_unknown)
1678 G.cwd = NULL;
1679 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1680 if (!G.cwd)
1681 G.cwd = bb_msg_unknown;
1682 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001683 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001684}
1685
Denis Vlasenko83506862007-11-23 13:11:42 +00001686
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001687/*
1688 * Shell and environment variable support
1689 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001690static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001691{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001692 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001693 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001694
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001695 pp = &G.top_var;
1696 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001697 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001698 return pp;
1699 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001700 }
1701 return NULL;
1702}
1703
Denys Vlasenko03dad222010-01-12 23:29:57 +01001704static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001705{
Denys Vlasenko29082232010-07-16 13:52:32 +02001706 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001707 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001708
1709 if (G.expanded_assignments) {
1710 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001711 while (*cpp) {
1712 char *cp = *cpp;
1713 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1714 return cp + len + 1;
1715 cpp++;
1716 }
1717 }
1718
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001719 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001720 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001721 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001722
Denys Vlasenkodea47882009-10-09 15:40:49 +02001723 if (strcmp(name, "PPID") == 0)
1724 return utoa(G.root_ppid);
1725 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001726#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001727 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001728 return utoa(next_random(&G.random_gen));
1729#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001730 return NULL;
1731}
1732
1733/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001734 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001735 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001736 * 0: do not change export flag
1737 * (if creating new variable, flag will be 0)
1738 * 1: set export flag and putenv the variable
1739 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001740 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001741 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001742#if !BB_MMU && ENABLE_HUSH_LOCAL
1743/* all params are used */
1744#elif BB_MMU && ENABLE_HUSH_LOCAL
1745#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1746 set_local_var(str, flg_export, local_lvl)
1747#elif BB_MMU && !ENABLE_HUSH_LOCAL
1748#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001749 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001750#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1751#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1752 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001753#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001754static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001755{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001756 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001757 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001758 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001759 int name_len;
1760
Denis Vlasenko950bd722009-04-21 11:23:56 +00001761 eq_sign = strchr(str, '=');
1762 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001763 free(str);
1764 return -1;
1765 }
1766
Denis Vlasenko950bd722009-04-21 11:23:56 +00001767 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001768 var_pp = &G.top_var;
1769 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001770 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001771 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001772 continue;
1773 }
1774 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001775 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001776#if !BB_MMU
1777 if (!flg_read_only)
1778#endif
1779 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001780 free(str);
1781 return -1;
1782 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001783 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001784 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1785 *eq_sign = '\0';
1786 unsetenv(str);
1787 *eq_sign = '=';
1788 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001789#if ENABLE_HUSH_LOCAL
1790 if (cur->func_nest_level < local_lvl) {
1791 /* New variable is declared as local,
1792 * and existing one is global, or local
1793 * from enclosing function.
1794 * Remove and save old one: */
1795 *var_pp = cur->next;
1796 cur->next = *G.shadowed_vars_pp;
1797 *G.shadowed_vars_pp = cur;
1798 /* bash 3.2.33(1) and exported vars:
1799 * # export z=z
1800 * # f() { local z=a; env | grep ^z; }
1801 * # f
1802 * z=a
1803 * # env | grep ^z
1804 * z=z
1805 */
1806 if (cur->flg_export)
1807 flg_export = 1;
1808 break;
1809 }
1810#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001811 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001812 free_and_exp:
1813 free(str);
1814 goto exp;
1815 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001816 if (cur->max_len != 0) {
1817 if (cur->max_len >= strlen(str)) {
1818 /* This one is from startup env, reuse space */
1819 strcpy(cur->varstr, str);
1820 goto free_and_exp;
1821 }
1822 } else {
1823 /* max_len == 0 signifies "malloced" var, which we can
1824 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001825 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001826 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001827 cur->max_len = 0;
1828 goto set_str_and_exp;
1829 }
1830
Denys Vlasenko295fef82009-06-03 12:47:26 +02001831 /* Not found - create new variable struct */
1832 cur = xzalloc(sizeof(*cur));
1833#if ENABLE_HUSH_LOCAL
1834 cur->func_nest_level = local_lvl;
1835#endif
1836 cur->next = *var_pp;
1837 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001838
1839 set_str_and_exp:
1840 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001841#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001842 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001843#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001844 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001845 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001846 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001847 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1848 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001849 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001850 if (flg_export == -1) {
1851 cur->flg_export = 0;
1852 /* unsetenv was already done */
1853 } else {
1854 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1855 return putenv(cur->varstr);
1856 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001857 }
1858 return 0;
1859}
1860
Denys Vlasenko6db47842009-09-05 20:15:17 +02001861/* Used at startup and after each cd */
1862static void set_pwd_var(int exp)
1863{
1864 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1865 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1866}
1867
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001868static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001869{
1870 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001871 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001872
1873 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001874 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001875 var_pp = &G.top_var;
1876 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001877 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1878 if (cur->flg_read_only) {
1879 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001880 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001881 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001882 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001883 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1884 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001885 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1886 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001887 if (!cur->max_len)
1888 free(cur->varstr);
1889 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001890 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001891 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001892 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001893 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001894 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001895}
1896
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001897static int unset_local_var(const char *name)
1898{
1899 return unset_local_var_len(name, strlen(name));
1900}
1901
1902static void unset_vars(char **strings)
1903{
1904 char **v;
1905
1906 if (!strings)
1907 return;
1908 v = strings;
1909 while (*v) {
1910 const char *eq = strchrnul(*v, '=');
1911 unset_local_var_len(*v, (int)(eq - *v));
1912 v++;
1913 }
1914 free(strings);
1915}
1916
Denys Vlasenko03dad222010-01-12 23:29:57 +01001917static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001918{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001919 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001920 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001921}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001922
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001923
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001924/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001925 * Helpers for "var1=val1 var2=val2 cmd" feature
1926 */
1927static void add_vars(struct variable *var)
1928{
1929 struct variable *next;
1930
1931 while (var) {
1932 next = var->next;
1933 var->next = G.top_var;
1934 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001935 if (var->flg_export) {
1936 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001937 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001938 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001939 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001940 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001941 var = next;
1942 }
1943}
1944
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001945static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001946{
1947 char **s;
1948 struct variable *old = NULL;
1949
1950 if (!strings)
1951 return old;
1952 s = strings;
1953 while (*s) {
1954 struct variable *var_p;
1955 struct variable **var_pp;
1956 char *eq;
1957
1958 eq = strchr(*s, '=');
1959 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001960 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001961 if (var_pp) {
1962 /* Remove variable from global linked list */
1963 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001964 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001965 *var_pp = var_p->next;
1966 /* Add it to returned list */
1967 var_p->next = old;
1968 old = var_p;
1969 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001970 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001971 }
1972 s++;
1973 }
1974 return old;
1975}
1976
1977
1978/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001979 * in_str support
1980 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001981static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001982{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001983 int ch = *i->p;
1984 if (ch != '\0') {
1985 i->p++;
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001986 i->last_char = ch;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001987 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001988 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001989 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001990}
1991
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001992static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001993{
1994 return *i->p;
1995}
1996
1997#if ENABLE_HUSH_INTERACTIVE
1998
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001999static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002000{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002001 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002002 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002003 if (G.PS1 == NULL)
2004 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002005 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002006 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002007 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002008 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002009 if (G.PS2 == NULL)
2010 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002011}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002012
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002013static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002014{
2015 const char *prompt_str;
2016 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002017 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2018 /* Set up the prompt */
2019 if (promptmode == 0) { /* PS1 */
2020 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002021 /* bash uses $PWD value, even if it is set by user.
2022 * It uses current dir only if PWD is unset.
2023 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002024 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002025 prompt_str = G.PS1;
2026 } else
2027 prompt_str = G.PS2;
2028 } else
2029 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002030 debug_printf("result '%s'\n", prompt_str);
2031 return prompt_str;
2032}
2033
2034static void get_user_input(struct in_str *i)
2035{
2036 int r;
2037 const char *prompt_str;
2038
2039 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002040# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002041 /* Enable command line editing only while a command line
2042 * is actually being read */
2043 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01002044 /* Unicode support should be activated even if LANG is set
2045 * _during_ shell execution, not only if it was set when
2046 * shell was started. Therefore, re-check LANG every time:
2047 */
Denys Vlasenko3e7ecb12013-07-02 17:30:23 +02002048 const char *s = get_local_var_value("LC_ALL");
Denys Vlasenko2301d122013-07-05 22:00:57 +02002049 if (!s) s = get_local_var_value("LC_CTYPE");
Denys Vlasenko3e7ecb12013-07-02 17:30:23 +02002050 if (!s) s = get_local_var_value("LANG");
2051 reinit_unicode(s);
Denys Vlasenko20704f02011-03-23 17:59:27 +01002052
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002053 G.flag_SIGINT = 0;
2054 /* buglet: SIGINT will not make new prompt to appear _at once_,
2055 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002056 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 +00002057 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002058 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002059 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002060 i->eof_flag = (r < 0);
2061 if (i->eof_flag) { /* EOF/error detected */
2062 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2063 G.user_input_buf[1] = '\0';
2064 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02002065# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002066 do {
2067 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002068 if (i->last_char == '\0' || i->last_char == '\n') {
2069 /* Why check_and_run_traps here? Try this interactively:
2070 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2071 * $ <[enter], repeatedly...>
2072 * Without check_and_run_traps, handler never runs.
2073 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002074 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002075 fputs(prompt_str, stdout);
2076 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002077 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002078 G.user_input_buf[0] = r = fgetc(i->file);
2079 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002080 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002081 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002082# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002083 i->p = G.user_input_buf;
2084}
2085
2086#endif /* INTERACTIVE */
2087
2088/* This is the magic location that prints prompts
2089 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002090static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002091{
2092 int ch;
2093
2094 /* If there is data waiting, eat it up */
2095 if (i->p && *i->p) {
2096#if ENABLE_HUSH_INTERACTIVE
2097 take_cached:
2098#endif
2099 ch = *i->p++;
2100 if (i->eof_flag && !*i->p)
2101 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002102 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002103 } else {
2104 /* need to double check i->file because we might be doing something
2105 * more complicated by now, like sourcing or substituting. */
2106#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002107 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002108 do {
2109 get_user_input(i);
2110 } while (!*i->p); /* need non-empty line */
2111 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002112 goto take_cached;
2113 }
2114#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00002115 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002116 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002117 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002118 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002119 return ch;
2120}
2121
Denis Vlasenko913a2012009-04-05 22:17:04 +00002122/* All callers guarantee this routine will never
2123 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002124 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002125static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002126{
2127 int ch;
2128 if (i->p && *i->p) {
2129 if (i->eof_flag && !i->p[1])
2130 return EOF;
2131 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002132 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002133 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002134 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002135 i->eof_flag = (ch == EOF);
2136 i->peek_buf[0] = ch;
2137 i->peek_buf[1] = '\0';
2138 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002139 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002140 return ch;
2141}
2142
2143static void setup_file_in_str(struct in_str *i, FILE *f)
2144{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002145 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002146 i->peek = file_peek;
2147 i->get = file_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->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002150 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002151}
2152
2153static void setup_string_in_str(struct in_str *i, const char *s)
2154{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002155 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002156 i->peek = static_peek;
2157 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002158 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002159 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002160 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002161}
2162
2163
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002164/*
2165 * o_string support
2166 */
2167#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002168
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002169static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002170{
2171 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002172 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002173 if (o->data)
2174 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002175}
2176
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002177static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002178{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002179 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002180 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002181}
2182
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002183static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2184{
2185 free(o->data);
2186}
2187
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002188static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002189{
2190 if (o->length + len > o->maxlen) {
2191 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2192 o->data = xrealloc(o->data, 1 + o->maxlen);
2193 }
2194}
2195
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002196static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002197{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002198 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2199 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002200 o->data[o->length] = ch;
2201 o->length++;
2202 o->data[o->length] = '\0';
2203}
2204
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002205static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002206{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002207 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002208 memcpy(&o->data[o->length], str, len);
2209 o->length += len;
2210 o->data[o->length] = '\0';
2211}
2212
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002213static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002214{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002215 o_addblock(o, str, strlen(str));
2216}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002217
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002218#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002219static void nommu_addchr(o_string *o, int ch)
2220{
2221 if (o)
2222 o_addchr(o, ch);
2223}
2224#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002225# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002226#endif
2227
2228static void o_addstr_with_NUL(o_string *o, const char *str)
2229{
2230 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002231}
2232
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002233/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002234 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002235 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2236 * Apparently, on unquoted $v bash still does globbing
2237 * ("v='*.txt'; echo $v" prints all .txt files),
2238 * but NOT brace expansion! Thus, there should be TWO independent
2239 * quoting mechanisms on $v expansion side: one protects
2240 * $v from brace expansion, and other additionally protects "$v" against globbing.
2241 * We have only second one.
2242 */
2243
Denys Vlasenko9e800222010-10-03 14:28:04 +02002244#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002245# define MAYBE_BRACES "{}"
2246#else
2247# define MAYBE_BRACES ""
2248#endif
2249
Eric Andersen25f27032001-04-26 23:22:31 +00002250/* My analysis of quoting semantics tells me that state information
2251 * is associated with a destination, not a source.
2252 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002253static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002254{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002255 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002256 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002257 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002258 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002259 o_grow_by(o, sz);
2260 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002261 o->data[o->length] = '\\';
2262 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002263 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002264 o->data[o->length] = ch;
2265 o->length++;
2266 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002267}
2268
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002269static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002270{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002271 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002272 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2273 && strchr("*?[\\" MAYBE_BRACES, ch)
2274 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002275 sz++;
2276 o->data[o->length] = '\\';
2277 o->length++;
2278 }
2279 o_grow_by(o, sz);
2280 o->data[o->length] = ch;
2281 o->length++;
2282 o->data[o->length] = '\0';
2283}
2284
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002285static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002286{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002287 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002288 char ch;
2289 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002290 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002291 if (ordinary_cnt > len) /* paranoia */
2292 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002293 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002294 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002295 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002296 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002297 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002298
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002299 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002300 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002301 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002302 sz++;
2303 o->data[o->length] = '\\';
2304 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002305 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002306 o_grow_by(o, sz);
2307 o->data[o->length] = ch;
2308 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002309 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002310 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002311}
2312
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002313static void o_addQblock(o_string *o, const char *str, int len)
2314{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002315 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002316 o_addblock(o, str, len);
2317 return;
2318 }
2319 o_addqblock(o, str, len);
2320}
2321
Denys Vlasenko38292b62010-09-05 14:49:40 +02002322static void o_addQstr(o_string *o, const char *str)
2323{
2324 o_addQblock(o, str, strlen(str));
2325}
2326
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002327/* A special kind of o_string for $VAR and `cmd` expansion.
2328 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002329 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002330 * list[i] contains an INDEX (int!) into this string data.
2331 * It means that if list[] needs to grow, data needs to be moved higher up
2332 * but list[i]'s need not be modified.
2333 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002334 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002335 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2336 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002337#if DEBUG_EXPAND || DEBUG_GLOB
2338static void debug_print_list(const char *prefix, o_string *o, int n)
2339{
2340 char **list = (char**)o->data;
2341 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2342 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002343
2344 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002345 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 +02002346 prefix, list, n, string_start, o->length, o->maxlen,
2347 !!(o->o_expflags & EXP_FLAG_GLOB),
2348 o->has_quoted_part,
2349 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002350 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002351 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002352 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2353 o->data + (int)(uintptr_t)list[i] + string_start,
2354 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002355 i++;
2356 }
2357 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002358 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002359 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002360 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002361 }
2362}
2363#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002364# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002365#endif
2366
2367/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2368 * in list[n] so that it points past last stored byte so far.
2369 * It returns n+1. */
2370static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002371{
2372 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002373 int string_start;
2374 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002375
2376 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002377 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2378 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002379 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002380 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002381 /* list[n] points to string_start, make space for 16 more pointers */
2382 o->maxlen += 0x10 * sizeof(list[0]);
2383 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002384 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002385 memmove(list + n + 0x10, list + n, string_len);
2386 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002387 } else {
2388 debug_printf_list("list[%d]=%d string_start=%d\n",
2389 n, string_len, string_start);
2390 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002391 } else {
2392 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002393 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2394 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002395 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2396 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002397 o->has_empty_slot = 0;
2398 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002399 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002400 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002401 return n + 1;
2402}
2403
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002404/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002405static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002406{
2407 char **list = (char**)o->data;
2408 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2409
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002410 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002411}
2412
Denys Vlasenko9e800222010-10-03 14:28:04 +02002413#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002414/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2415 * first, it processes even {a} (no commas), second,
2416 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002417 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002418 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002419
2420/* Helper */
2421static int glob_needed(const char *s)
2422{
2423 while (*s) {
2424 if (*s == '\\') {
2425 if (!s[1])
2426 return 0;
2427 s += 2;
2428 continue;
2429 }
2430 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2431 return 1;
2432 s++;
2433 }
2434 return 0;
2435}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002436/* Return pointer to next closing brace or to comma */
2437static const char *next_brace_sub(const char *cp)
2438{
2439 unsigned depth = 0;
2440 cp++;
2441 while (*cp != '\0') {
2442 if (*cp == '\\') {
2443 if (*++cp == '\0')
2444 break;
2445 cp++;
2446 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002447 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002448 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002449 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002450 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002451 depth++;
2452 }
2453
2454 return *cp != '\0' ? cp : NULL;
2455}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002456/* Recursive brace globber. Note: may garble pattern[]. */
2457static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002458{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002459 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002460 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002461 const char *next;
2462 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002463 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002464 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002465
2466 debug_printf_glob("glob_brace('%s')\n", pattern);
2467
2468 begin = pattern;
2469 while (1) {
2470 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002471 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002472 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002473 /* Find the first sub-pattern and at the same time
2474 * find the rest after the closing brace */
2475 next = next_brace_sub(begin);
2476 if (next == NULL) {
2477 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002478 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002479 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002480 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002481 /* "{abc}" with no commas - illegal
2482 * brace expr, disregard and skip it */
2483 begin = next + 1;
2484 continue;
2485 }
2486 break;
2487 }
2488 if (*begin == '\\' && begin[1] != '\0')
2489 begin++;
2490 begin++;
2491 }
2492 debug_printf_glob("begin:%s\n", begin);
2493 debug_printf_glob("next:%s\n", next);
2494
2495 /* Now find the end of the whole brace expression */
2496 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002497 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002498 rest = next_brace_sub(rest);
2499 if (rest == NULL) {
2500 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002501 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002502 }
2503 debug_printf_glob("rest:%s\n", rest);
2504 }
2505 rest_len = strlen(++rest) + 1;
2506
2507 /* We are sure the brace expression is well-formed */
2508
2509 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002510 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002511
2512 /* We have a brace expression. BEGIN points to the opening {,
2513 * NEXT points past the terminator of the first element, and REST
2514 * points past the final }. We will accumulate result names from
2515 * recursive runs for each brace alternative in the buffer using
2516 * GLOB_APPEND. */
2517
2518 p = begin + 1;
2519 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002520 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002521 memcpy(
2522 mempcpy(
2523 mempcpy(new_pattern_buf,
2524 /* We know the prefix for all sub-patterns */
2525 pattern, begin - pattern),
2526 p, next - p),
2527 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002528
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002529 /* Note: glob_brace() may garble new_pattern_buf[].
2530 * That's why we re-copy prefix every time (1st memcpy above).
2531 */
2532 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002533 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002534 /* We saw the last entry */
2535 break;
2536 }
2537 p = next + 1;
2538 next = next_brace_sub(next);
2539 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002540 free(new_pattern_buf);
2541 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002542
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002543 simple_glob:
2544 {
2545 int gr;
2546 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002547
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002548 memset(&globdata, 0, sizeof(globdata));
2549 gr = glob(pattern, 0, NULL, &globdata);
2550 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2551 if (gr != 0) {
2552 if (gr == GLOB_NOMATCH) {
2553 globfree(&globdata);
2554 /* NB: garbles parameter */
2555 unbackslash(pattern);
2556 o_addstr_with_NUL(o, pattern);
2557 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2558 return o_save_ptr_helper(o, n);
2559 }
2560 if (gr == GLOB_NOSPACE)
2561 bb_error_msg_and_die(bb_msg_memory_exhausted);
2562 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2563 * but we didn't specify it. Paranoia again. */
2564 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2565 }
2566 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2567 char **argv = globdata.gl_pathv;
2568 while (1) {
2569 o_addstr_with_NUL(o, *argv);
2570 n = o_save_ptr_helper(o, n);
2571 argv++;
2572 if (!*argv)
2573 break;
2574 }
2575 }
2576 globfree(&globdata);
2577 }
2578 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002579}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002580/* Performs globbing on last list[],
2581 * saving each result as a new list[].
2582 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002583static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002584{
2585 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002586
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002587 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002588 if (!o->data)
2589 return o_save_ptr_helper(o, n);
2590 pattern = o->data + o_get_last_ptr(o, n);
2591 debug_printf_glob("glob pattern '%s'\n", pattern);
2592 if (!glob_needed(pattern)) {
2593 /* unbackslash last string in o in place, fix length */
2594 o->length = unbackslash(pattern) - o->data;
2595 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2596 return o_save_ptr_helper(o, n);
2597 }
2598
2599 copy = xstrdup(pattern);
2600 /* "forget" pattern in o */
2601 o->length = pattern - o->data;
2602 n = glob_brace(copy, o, n);
2603 free(copy);
2604 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002605 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002606 return n;
2607}
2608
Denys Vlasenko238081f2010-10-03 14:26:26 +02002609#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002610
2611/* Helper */
2612static int glob_needed(const char *s)
2613{
2614 while (*s) {
2615 if (*s == '\\') {
2616 if (!s[1])
2617 return 0;
2618 s += 2;
2619 continue;
2620 }
2621 if (*s == '*' || *s == '[' || *s == '?')
2622 return 1;
2623 s++;
2624 }
2625 return 0;
2626}
2627/* Performs globbing on last list[],
2628 * saving each result as a new list[].
2629 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002630static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002631{
2632 glob_t globdata;
2633 int gr;
2634 char *pattern;
2635
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002636 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002637 if (!o->data)
2638 return o_save_ptr_helper(o, n);
2639 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002640 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002641 if (!glob_needed(pattern)) {
2642 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002643 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002644 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002645 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002646 return o_save_ptr_helper(o, n);
2647 }
2648
2649 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002650 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2651 * If we glob "*.\*" and don't find anything, we need
2652 * to fall back to using literal "*.*", but GLOB_NOCHECK
2653 * will return "*.\*"!
2654 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002655 gr = glob(pattern, 0, NULL, &globdata);
2656 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002657 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002658 if (gr == GLOB_NOMATCH) {
2659 globfree(&globdata);
2660 goto literal;
2661 }
2662 if (gr == GLOB_NOSPACE)
2663 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002664 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2665 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002666 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002667 }
2668 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2669 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002670 /* "forget" pattern in o */
2671 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002672 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002673 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002674 n = o_save_ptr_helper(o, n);
2675 argv++;
2676 if (!*argv)
2677 break;
2678 }
2679 }
2680 globfree(&globdata);
2681 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002682 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002683 return n;
2684}
2685
Denys Vlasenko238081f2010-10-03 14:26:26 +02002686#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002687
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002688/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002689 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002690static int o_save_ptr(o_string *o, int n)
2691{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002692 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002693 /* If o->has_empty_slot, list[n] was already globbed
2694 * (if it was requested back then when it was filled)
2695 * so don't do that again! */
2696 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002697 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002698 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002699 return o_save_ptr_helper(o, n);
2700}
2701
2702/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002703static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002704{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002705 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002706 int string_start;
2707
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002708 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2709 if (DEBUG_EXPAND)
2710 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002711 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002712 list = (char**)o->data;
2713 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2714 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002715 while (n) {
2716 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002717 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002718 }
2719 return list;
2720}
2721
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002722static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002723
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002724/* Returns pi->next - next pipe in the list */
2725static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002726{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002727 struct pipe *next;
2728 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002729
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002730 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002731 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002732 struct command *command;
2733 struct redir_struct *r, *rnext;
2734
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002735 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002736 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002737 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002738 if (DEBUG_CLEAN) {
2739 int a;
2740 char **p;
2741 for (a = 0, p = command->argv; *p; a++, p++) {
2742 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2743 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002744 }
2745 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002746 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002747 }
2748 /* not "else if": on syntax error, we may have both! */
2749 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002750 debug_printf_clean(" begin group (cmd_type:%d)\n",
2751 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002752 free_pipe_list(command->group);
2753 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002754 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002755 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002756 /* else is crucial here.
2757 * If group != NULL, child_func is meaningless */
2758#if ENABLE_HUSH_FUNCTIONS
2759 else if (command->child_func) {
2760 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2761 command->child_func->parent_cmd = NULL;
2762 }
2763#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002764#if !BB_MMU
2765 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002766 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002767#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002768 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002769 debug_printf_clean(" redirect %d%s",
2770 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002771 /* guard against the case >$FOO, where foo is unset or blank */
2772 if (r->rd_filename) {
2773 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2774 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002775 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002776 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002777 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002778 rnext = r->next;
2779 free(r);
2780 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002781 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002782 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002783 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002784 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002785#if ENABLE_HUSH_JOB
2786 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002787 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002788#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002789
2790 next = pi->next;
2791 free(pi);
2792 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002793}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002794
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002795static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002796{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002797 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002798#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002799 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002800#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002801 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002802 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002803 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002804}
2805
2806
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002807/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002808
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002809#ifndef debug_print_tree
2810static void debug_print_tree(struct pipe *pi, int lvl)
2811{
2812 static const char *const PIPE[] = {
2813 [PIPE_SEQ] = "SEQ",
2814 [PIPE_AND] = "AND",
2815 [PIPE_OR ] = "OR" ,
2816 [PIPE_BG ] = "BG" ,
2817 };
2818 static const char *RES[] = {
2819 [RES_NONE ] = "NONE" ,
2820# if ENABLE_HUSH_IF
2821 [RES_IF ] = "IF" ,
2822 [RES_THEN ] = "THEN" ,
2823 [RES_ELIF ] = "ELIF" ,
2824 [RES_ELSE ] = "ELSE" ,
2825 [RES_FI ] = "FI" ,
2826# endif
2827# if ENABLE_HUSH_LOOPS
2828 [RES_FOR ] = "FOR" ,
2829 [RES_WHILE] = "WHILE",
2830 [RES_UNTIL] = "UNTIL",
2831 [RES_DO ] = "DO" ,
2832 [RES_DONE ] = "DONE" ,
2833# endif
2834# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2835 [RES_IN ] = "IN" ,
2836# endif
2837# if ENABLE_HUSH_CASE
2838 [RES_CASE ] = "CASE" ,
2839 [RES_CASE_IN ] = "CASE_IN" ,
2840 [RES_MATCH] = "MATCH",
2841 [RES_CASE_BODY] = "CASE_BODY",
2842 [RES_ESAC ] = "ESAC" ,
2843# endif
2844 [RES_XXXX ] = "XXXX" ,
2845 [RES_SNTX ] = "SNTX" ,
2846 };
2847 static const char *const CMDTYPE[] = {
2848 "{}",
2849 "()",
2850 "[noglob]",
2851# if ENABLE_HUSH_FUNCTIONS
2852 "func()",
2853# endif
2854 };
2855
2856 int pin, prn;
2857
2858 pin = 0;
2859 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002860 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002861 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2862 prn = 0;
2863 while (prn < pi->num_cmds) {
2864 struct command *command = &pi->cmds[prn];
2865 char **argv = command->argv;
2866
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002867 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002868 lvl*2, "", prn,
2869 command->assignment_cnt);
2870 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002871 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002872 CMDTYPE[command->cmd_type],
2873 argv
2874# if !BB_MMU
2875 , " group_as_string:", command->group_as_string
2876# else
2877 , "", ""
2878# endif
2879 );
2880 debug_print_tree(command->group, lvl+1);
2881 prn++;
2882 continue;
2883 }
2884 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002885 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002886 argv++;
2887 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002888 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002889 prn++;
2890 }
2891 pi = pi->next;
2892 pin++;
2893 }
2894}
2895#endif /* debug_print_tree */
2896
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002897static struct pipe *new_pipe(void)
2898{
Eric Andersen25f27032001-04-26 23:22:31 +00002899 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002900 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002901 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002902 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002903 return pi;
2904}
2905
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002906/* Command (member of a pipe) is complete, or we start a new pipe
2907 * if ctx->command is NULL.
2908 * No errors possible here.
2909 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002910static int done_command(struct parse_context *ctx)
2911{
2912 /* The command is really already in the pipe structure, so
2913 * advance the pipe counter and make a new, null command. */
2914 struct pipe *pi = ctx->pipe;
2915 struct command *command = ctx->command;
2916
2917 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002918 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002919 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002920 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002921 }
2922 pi->num_cmds++;
2923 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002924 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002925 } else {
2926 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2927 }
2928
2929 /* Only real trickiness here is that the uncommitted
2930 * command structure is not counted in pi->num_cmds. */
2931 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002932 ctx->command = command = &pi->cmds[pi->num_cmds];
2933 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002934 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002935 return pi->num_cmds; /* used only for 0/nonzero check */
2936}
2937
2938static void done_pipe(struct parse_context *ctx, pipe_style type)
2939{
2940 int not_null;
2941
2942 debug_printf_parse("done_pipe entered, followup %d\n", type);
2943 /* Close previous command */
2944 not_null = done_command(ctx);
2945 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002946#if HAS_KEYWORDS
2947 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2948 ctx->ctx_inverted = 0;
2949 ctx->pipe->res_word = ctx->ctx_res_w;
2950#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002951
2952 /* Without this check, even just <enter> on command line generates
2953 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002954 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002955 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002956#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002957 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002958#endif
2959#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002960 || ctx->ctx_res_w == RES_DONE
2961 || ctx->ctx_res_w == RES_FOR
2962 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002963#endif
2964#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002965 || ctx->ctx_res_w == RES_ESAC
2966#endif
2967 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002968 struct pipe *new_p;
2969 debug_printf_parse("done_pipe: adding new pipe: "
2970 "not_null:%d ctx->ctx_res_w:%d\n",
2971 not_null, ctx->ctx_res_w);
2972 new_p = new_pipe();
2973 ctx->pipe->next = new_p;
2974 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002975 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002976 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002977 * This is used to control execution.
2978 * RES_FOR and RES_IN are NOT sticky (needed to support
2979 * cases where variable or value happens to match a keyword):
2980 */
2981#if ENABLE_HUSH_LOOPS
2982 if (ctx->ctx_res_w == RES_FOR
2983 || ctx->ctx_res_w == RES_IN)
2984 ctx->ctx_res_w = RES_NONE;
2985#endif
2986#if ENABLE_HUSH_CASE
2987 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002988 ctx->ctx_res_w = RES_CASE_BODY;
2989 if (ctx->ctx_res_w == RES_CASE)
2990 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002991#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002992 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002993 /* Create the memory for command, roughly:
2994 * ctx->pipe->cmds = new struct command;
2995 * ctx->command = &ctx->pipe->cmds[0];
2996 */
2997 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002998 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002999 }
3000 debug_printf_parse("done_pipe return\n");
3001}
3002
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003003static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003004{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003005 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003006 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003007 /* Create the memory for command, roughly:
3008 * ctx->pipe->cmds = new struct command;
3009 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003010 */
3011 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003012}
3013
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003014/* If a reserved word is found and processed, parse context is modified
3015 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003016 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003017#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003018struct reserved_combo {
3019 char literal[6];
3020 unsigned char res;
3021 unsigned char assignment_flag;
3022 int flag;
3023};
3024enum {
3025 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003026# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003027 FLAG_IF = (1 << RES_IF ),
3028 FLAG_THEN = (1 << RES_THEN ),
3029 FLAG_ELIF = (1 << RES_ELIF ),
3030 FLAG_ELSE = (1 << RES_ELSE ),
3031 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003032# endif
3033# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003034 FLAG_FOR = (1 << RES_FOR ),
3035 FLAG_WHILE = (1 << RES_WHILE),
3036 FLAG_UNTIL = (1 << RES_UNTIL),
3037 FLAG_DO = (1 << RES_DO ),
3038 FLAG_DONE = (1 << RES_DONE ),
3039 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003040# endif
3041# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003042 FLAG_MATCH = (1 << RES_MATCH),
3043 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003044# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003045 FLAG_START = (1 << RES_XXXX ),
3046};
3047
3048static const struct reserved_combo* match_reserved_word(o_string *word)
3049{
Eric Andersen25f27032001-04-26 23:22:31 +00003050 /* Mostly a list of accepted follow-up reserved words.
3051 * FLAG_END means we are done with the sequence, and are ready
3052 * to turn the compound list into a command.
3053 * FLAG_START means the word must start a new compound list.
3054 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003055 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003056# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003057 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3058 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3059 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3060 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3061 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3062 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003063# endif
3064# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003065 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3066 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3067 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3068 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3069 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3070 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003071# endif
3072# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003073 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3074 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003075# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003076 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003077 const struct reserved_combo *r;
3078
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003079 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003080 if (strcmp(word->data, r->literal) == 0)
3081 return r;
3082 }
3083 return NULL;
3084}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003085/* Return 0: not a keyword, 1: keyword
3086 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003087static int reserved_word(o_string *word, struct parse_context *ctx)
3088{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003089# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003090 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003091 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003092 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003093# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003094 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003095
Denys Vlasenko38292b62010-09-05 14:49:40 +02003096 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003097 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003098 r = match_reserved_word(word);
3099 if (!r)
3100 return 0;
3101
3102 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003103# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003104 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3105 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003106 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003107 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003108# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003109 if (r->flag == 0) { /* '!' */
3110 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003111 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003112 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003113 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003114 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003115 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003116 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003117 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003118 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003119
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003120 old = xmalloc(sizeof(*old));
3121 debug_printf_parse("push stack %p\n", old);
3122 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003123 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003124 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003125 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003126 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003127 ctx->ctx_res_w = RES_SNTX;
3128 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003129 } else {
3130 /* "{...} fi" is ok. "{...} if" is not
3131 * Example:
3132 * if { echo foo; } then { echo bar; } fi */
3133 if (ctx->command->group)
3134 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003135 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003136
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003137 ctx->ctx_res_w = r->res;
3138 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003139 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003140 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003141
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003142 if (ctx->old_flag & FLAG_END) {
3143 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003144
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003145 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003146 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003147 old = ctx->stack;
3148 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003149 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003150# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003151 o_addstr(&old->as_string, ctx->as_string.data);
3152 o_free_unsafe(&ctx->as_string);
3153 old->command->group_as_string = xstrdup(old->as_string.data);
3154 debug_printf_parse("pop, remembering as:'%s'\n",
3155 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003156# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003157 *ctx = *old; /* physical copy */
3158 free(old);
3159 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003160 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003161}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003162#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003163
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003164/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003165 * Normal return is 0. Syntax errors return 1.
3166 * Note: on return, word is reset, but not o_free'd!
3167 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003168static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003169{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003170 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003171
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003172 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003173 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003174 debug_printf_parse("done_word return 0: true null, ignored\n");
3175 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003176 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003177
Eric Andersen25f27032001-04-26 23:22:31 +00003178 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003179 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3180 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003181 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3182 * "2.7 Redirection
3183 * ...the word that follows the redirection operator
3184 * shall be subjected to tilde expansion, parameter expansion,
3185 * command substitution, arithmetic expansion, and quote
3186 * removal. Pathname expansion shall not be performed
3187 * on the word by a non-interactive shell; an interactive
3188 * shell may perform it, but shall do so only when
3189 * the expansion would result in one word."
3190 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003191 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003192 /* Cater for >\file case:
3193 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3194 * Same with heredocs:
3195 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3196 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003197 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3198 unbackslash(ctx->pending_redirect->rd_filename);
3199 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003200 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003201 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3202 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003203 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003204 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003205 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003206 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003207#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003208# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003209 if (ctx->ctx_dsemicolon
3210 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3211 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003212 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003213 /* ctx->ctx_res_w = RES_MATCH; */
3214 ctx->ctx_dsemicolon = 0;
3215 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003216# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003217 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003218# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003219 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3220 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003221# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003222# if ENABLE_HUSH_CASE
3223 && ctx->ctx_res_w != RES_CASE
3224# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003225 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003226 int reserved = reserved_word(word, ctx);
3227 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3228 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003229 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003230 debug_printf_parse("done_word return %d\n",
3231 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003232 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003233 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003234# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003235 if (strcmp(word->data, "[[") == 0) {
3236 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3237 }
3238 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003239# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003240 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003241#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003242 if (command->group) {
3243 /* "{ echo foo; } echo bar" - bad */
3244 syntax_error_at(word->data);
3245 debug_printf_parse("done_word return 1: syntax error, "
3246 "groups and arglists don't mix\n");
3247 return 1;
3248 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003249
3250 /* If this word wasn't an assignment, next ones definitely
3251 * can't be assignments. Even if they look like ones. */
3252 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3253 && word->o_assignment != WORD_IS_KEYWORD
3254 ) {
3255 word->o_assignment = NOT_ASSIGNMENT;
3256 } else {
3257 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3258 command->assignment_cnt++;
3259 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3260 }
3261 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3262 word->o_assignment = MAYBE_ASSIGNMENT;
3263 }
3264 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3265
Denys Vlasenko38292b62010-09-05 14:49:40 +02003266 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003267 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3268 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003269 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003270 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003271 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003272 char *p = word->data;
3273 while (p[0] == SPECIAL_VAR_SYMBOL
3274 && (p[1] & 0x7f) == '@'
3275 && p[2] == SPECIAL_VAR_SYMBOL
3276 ) {
3277 p += 3;
3278 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003279 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003280 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003281 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003282 }
Eric Andersen25f27032001-04-26 23:22:31 +00003283
Denis Vlasenko06810332007-05-21 23:30:54 +00003284#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003285 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003286 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003287 || !is_well_formed_var_name(command->argv[0], '\0')
3288 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003289 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003290 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003291 return 1;
3292 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003293 /* Force FOR to have just one word (variable name) */
3294 /* NB: basically, this makes hush see "for v in ..."
3295 * syntax as if it is "for v; in ...". FOR and IN become
3296 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003297 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003298 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003299#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003300#if ENABLE_HUSH_CASE
3301 /* Force CASE to have just one word */
3302 if (ctx->ctx_res_w == RES_CASE) {
3303 done_pipe(ctx, PIPE_SEQ);
3304 }
3305#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003306
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003307 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003308
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003309 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003310 return 0;
3311}
3312
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003313
3314/* Peek ahead in the input to find out if we have a "&n" construct,
3315 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003316 * Return:
3317 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3318 * REDIRFD_SYNTAX_ERR if syntax error,
3319 * REDIRFD_TO_FILE if no & was seen,
3320 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003321 */
3322#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003323#define parse_redir_right_fd(as_string, input) \
3324 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003325#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003326static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003327{
3328 int ch, d, ok;
3329
3330 ch = i_peek(input);
3331 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003332 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003333
3334 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003335 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003336 ch = i_peek(input);
3337 if (ch == '-') {
3338 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003339 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003340 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003341 }
3342 d = 0;
3343 ok = 0;
3344 while (ch != EOF && isdigit(ch)) {
3345 d = d*10 + (ch-'0');
3346 ok = 1;
3347 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003348 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003349 ch = i_peek(input);
3350 }
3351 if (ok) return d;
3352
3353//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3354
3355 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003356 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003357}
3358
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003359/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003360 */
3361static int parse_redirect(struct parse_context *ctx,
3362 int fd,
3363 redir_type style,
3364 struct in_str *input)
3365{
3366 struct command *command = ctx->command;
3367 struct redir_struct *redir;
3368 struct redir_struct **redirp;
3369 int dup_num;
3370
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003371 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003372 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003373 /* Check for a '>&1' type redirect */
3374 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3375 if (dup_num == REDIRFD_SYNTAX_ERR)
3376 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003377 } else {
3378 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003379 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003380 if (dup_num) { /* <<-... */
3381 ch = i_getch(input);
3382 nommu_addchr(&ctx->as_string, ch);
3383 ch = i_peek(input);
3384 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003385 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003386
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003387 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003388 int ch = i_peek(input);
3389 if (ch == '|') {
3390 /* >|FILE redirect ("clobbering" >).
3391 * Since we do not support "set -o noclobber" yet,
3392 * >| and > are the same for now. Just eat |.
3393 */
3394 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003395 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003396 }
3397 }
3398
3399 /* Create a new redir_struct and append it to the linked list */
3400 redirp = &command->redirects;
3401 while ((redir = *redirp) != NULL) {
3402 redirp = &(redir->next);
3403 }
3404 *redirp = redir = xzalloc(sizeof(*redir));
3405 /* redir->next = NULL; */
3406 /* redir->rd_filename = NULL; */
3407 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003408 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003409
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003410 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3411 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003412
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003413 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003414 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003415 /* Erik had a check here that the file descriptor in question
3416 * is legit; I postpone that to "run time"
3417 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003418 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3419 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003420 } else {
3421 /* Set ctx->pending_redirect, so we know what to do at the
3422 * end of the next parsed word. */
3423 ctx->pending_redirect = redir;
3424 }
3425 return 0;
3426}
3427
Eric Andersen25f27032001-04-26 23:22:31 +00003428/* If a redirect is immediately preceded by a number, that number is
3429 * supposed to tell which file descriptor to redirect. This routine
3430 * looks for such preceding numbers. In an ideal world this routine
3431 * needs to handle all the following classes of redirects...
3432 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3433 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3434 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3435 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003436 *
3437 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3438 * "2.7 Redirection
3439 * ... If n is quoted, the number shall not be recognized as part of
3440 * the redirection expression. For example:
3441 * echo \2>a
3442 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003443 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003444 *
3445 * A -1 return means no valid number was found,
3446 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003447 */
3448static int redirect_opt_num(o_string *o)
3449{
3450 int num;
3451
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003452 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003453 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003454 num = bb_strtou(o->data, NULL, 10);
3455 if (errno || num < 0)
3456 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003457 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003458 return num;
3459}
3460
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003461#if BB_MMU
3462#define fetch_till_str(as_string, input, word, skip_tabs) \
3463 fetch_till_str(input, word, skip_tabs)
3464#endif
3465static char *fetch_till_str(o_string *as_string,
3466 struct in_str *input,
3467 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003468 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003469{
3470 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003471 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003472 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003473 int ch;
3474
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003475 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003476
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003477 while (1) {
3478 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003479 if (ch != EOF)
3480 nommu_addchr(as_string, ch);
3481 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003482 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3483 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003484 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3485 heredoc.data[past_EOL] = '\0';
3486 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3487 return heredoc.data;
3488 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003489 while (ch == '\n') {
3490 o_addchr(&heredoc, ch);
3491 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003492 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003493 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003494 do {
3495 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003496 if (ch != EOF)
3497 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003498 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003499 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003500 }
3501 if (ch == EOF) {
3502 o_free_unsafe(&heredoc);
3503 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003504 }
3505 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003506 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003507 if (prev == '\\' && ch == '\\')
3508 /* Correctly handle foo\\<eol> (not a line cont.) */
3509 prev = 0; /* not \ */
3510 else
3511 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003512 }
3513}
3514
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003515/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3516 * and load them all. There should be exactly heredoc_cnt of them.
3517 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003518static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3519{
3520 struct pipe *pi = ctx->list_head;
3521
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003522 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003523 int i;
3524 struct command *cmd = pi->cmds;
3525
3526 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3527 pi->num_cmds,
3528 cmd->argv ? cmd->argv[0] : "NONE");
3529 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003530 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003531
3532 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3533 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003534 while (redir) {
3535 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003536 char *p;
3537
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003538 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003539 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003540 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003541 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003542 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003543 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003544 return 1;
3545 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003546 free(redir->rd_filename);
3547 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003548 heredoc_cnt--;
3549 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003550 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003551 }
3552 cmd++;
3553 }
3554 pi = pi->next;
3555 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003556#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003557 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003558 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003559 bb_error_msg_and_die("heredoc BUG 2");
3560#endif
3561 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003562}
3563
3564
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003565static int run_list(struct pipe *pi);
3566#if BB_MMU
3567#define parse_stream(pstring, input, end_trigger) \
3568 parse_stream(input, end_trigger)
3569#endif
3570static struct pipe *parse_stream(char **pstring,
3571 struct in_str *input,
3572 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003573
Eric Andersen25f27032001-04-26 23:22:31 +00003574
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003575#if !ENABLE_HUSH_FUNCTIONS
3576#define parse_group(dest, ctx, input, ch) \
3577 parse_group(ctx, input, ch)
3578#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003579static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003580 struct in_str *input, int ch)
3581{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003582 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003583 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003584 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003585 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003586 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003587 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003588
3589 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003590#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003591 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003592 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003593 if (done_word(dest, ctx))
3594 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003595 if (!command->argv)
3596 goto skip; /* (... */
3597 if (command->argv[1]) { /* word word ... (... */
3598 syntax_error_unexpected_ch('(');
3599 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003600 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003601 /* it is "word(..." or "word (..." */
3602 do
3603 ch = i_getch(input);
3604 while (ch == ' ' || ch == '\t');
3605 if (ch != ')') {
3606 syntax_error_unexpected_ch(ch);
3607 return 1;
3608 }
3609 nommu_addchr(&ctx->as_string, ch);
3610 do
3611 ch = i_getch(input);
3612 while (ch == ' ' || ch == '\t' || ch == '\n');
3613 if (ch != '{') {
3614 syntax_error_unexpected_ch(ch);
3615 return 1;
3616 }
3617 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003618 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003619 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003620 }
3621#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003622
3623#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003624 if (command->argv /* word [word]{... */
3625 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003626 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003627 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003628 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003629 debug_printf_parse("parse_group return 1: "
3630 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003631 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003632 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003633#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003634
3635#if ENABLE_HUSH_FUNCTIONS
3636 skip:
3637#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003638 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003639 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003640 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003641 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003642 } else {
3643 /* bash does not allow "{echo...", requires whitespace */
3644 ch = i_getch(input);
3645 if (ch != ' ' && ch != '\t' && ch != '\n') {
3646 syntax_error_unexpected_ch(ch);
3647 return 1;
3648 }
3649 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003650 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003651
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003652 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003653#if BB_MMU
3654# define as_string NULL
3655#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003656 char *as_string = NULL;
3657#endif
3658 pipe_list = parse_stream(&as_string, input, endch);
3659#if !BB_MMU
3660 if (as_string)
3661 o_addstr(&ctx->as_string, as_string);
3662#endif
3663 /* empty ()/{} or parse error? */
3664 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003665 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003666 if (!BB_MMU)
3667 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003668 debug_printf_parse("parse_group return 1: "
3669 "parse_stream returned %p\n", pipe_list);
3670 return 1;
3671 }
3672 command->group = pipe_list;
3673#if !BB_MMU
3674 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3675 command->group_as_string = as_string;
3676 debug_printf_parse("end of group, remembering as:'%s'\n",
3677 command->group_as_string);
3678#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003679#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003680 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003681 debug_printf_parse("parse_group return 0\n");
3682 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003683 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003684}
3685
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003686#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003687/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003688static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003689/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003690static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003691{
3692 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003693 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003694 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003695 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003696 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003697 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003698 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003699 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003700 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003701 }
3702}
3703/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003704static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003705{
3706 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003707 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003708 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003709 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003710 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003711 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003712 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003713 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003714 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003715 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003716 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003717 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003718 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003719 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003720 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3721 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003722 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003723 continue;
3724 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003725 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003726 }
3727}
3728/* Process `cmd` - copy contents until "`" is seen. Complicated by
3729 * \` quoting.
3730 * "Within the backquoted style of command substitution, backslash
3731 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3732 * The search for the matching backquote shall be satisfied by the first
3733 * backquote found without a preceding backslash; during this search,
3734 * if a non-escaped backquote is encountered within a shell comment,
3735 * a here-document, an embedded command substitution of the $(command)
3736 * form, or a quoted string, undefined results occur. A single-quoted
3737 * or double-quoted string that begins, but does not end, within the
3738 * "`...`" sequence produces undefined results."
3739 * Example Output
3740 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3741 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003742static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003743{
3744 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003745 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003746 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003747 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003748 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003749 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3750 ch = i_getch(input);
3751 if (ch != '`'
3752 && ch != '$'
3753 && ch != '\\'
3754 && (!in_dquote || ch != '"')
3755 ) {
3756 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003757 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003758 }
3759 if (ch == EOF) {
3760 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003761 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003762 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003763 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003764 }
3765}
3766/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3767 * quoting and nested ()s.
3768 * "With the $(command) style of command substitution, all characters
3769 * following the open parenthesis to the matching closing parenthesis
3770 * constitute the command. Any valid shell script can be used for command,
3771 * except a script consisting solely of redirections which produces
3772 * unspecified results."
3773 * Example Output
3774 * echo $(echo '(TEST)' BEST) (TEST) BEST
3775 * echo $(echo 'TEST)' BEST) TEST) BEST
3776 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003777 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003778 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003779 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003780 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3781 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003782 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003783#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003784static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003785{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003786 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003787 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003788# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003789 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003790# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003791 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3792
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003793 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003794 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003795 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003796 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003797 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003798 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003799 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003800 if (!dbl)
3801 break;
3802 /* we look for closing )) of $((EXPR)) */
3803 if (i_peek(input) == end_ch) {
3804 i_getch(input); /* eat second ')' */
3805 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003806 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003807 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003808 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003809 if (ch == '(' || ch == '{') {
3810 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003811 if (!add_till_closing_bracket(dest, input, ch))
3812 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003813 o_addchr(dest, ch);
3814 continue;
3815 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003816 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003817 if (!add_till_single_quote(dest, input))
3818 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003819 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003820 continue;
3821 }
3822 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003823 if (!add_till_double_quote(dest, input))
3824 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003825 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003826 continue;
3827 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003828 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003829 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3830 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003831 o_addchr(dest, ch);
3832 continue;
3833 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003834 if (ch == '\\') {
3835 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003836 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003837 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003838 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003839 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003840 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003841 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003842 continue;
3843 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003844 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003845 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003846}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003847#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003848
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003849/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003850#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003851#define parse_dollar(as_string, dest, input, quote_mask) \
3852 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003853#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003854#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003855static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003856 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003857 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003858{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003859 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003860
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003861 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003862 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003863 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003864 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003865 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003866 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003867 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003868 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003869 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003870 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003871 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003872 if (!isalnum(ch) && ch != '_')
3873 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003874 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003875 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003876 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003877 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003878 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003879 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003880 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003881 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003882 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003883 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003884 o_addchr(dest, ch | quote_mask);
3885 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003886 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003887 case '$': /* pid */
3888 case '!': /* last bg pid */
3889 case '?': /* last exit code */
3890 case '#': /* number of args */
3891 case '*': /* args */
3892 case '@': /* args */
3893 goto make_one_char_var;
3894 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003895 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3896
Denys Vlasenko74369502010-05-21 19:52:01 +02003897 ch = i_getch(input); /* eat '{' */
3898 nommu_addchr(as_string, ch);
3899
3900 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003901 /* It should be ${?}, or ${#var},
3902 * or even ${?+subst} - operator acting on a special variable,
3903 * or the beginning of variable name.
3904 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003905 if (ch == EOF
3906 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3907 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003908 bad_dollar_syntax:
3909 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003910 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3911 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02003912 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003913 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003914 ch |= quote_mask;
3915
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003916 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003917 * However, this regresses some of our testsuite cases
3918 * which check invalid constructs like ${%}.
3919 * Oh well... let's check that the var name part is fine... */
3920
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003921 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003922 unsigned pos;
3923
Denys Vlasenko74369502010-05-21 19:52:01 +02003924 o_addchr(dest, ch);
3925 debug_printf_parse(": '%c'\n", ch);
3926
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003927 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003928 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003929 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003930 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003931
Denys Vlasenko74369502010-05-21 19:52:01 +02003932 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003933 unsigned end_ch;
3934 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003935 /* handle parameter expansions
3936 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3937 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003938 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003939 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003940
3941 /* Eat everything until closing '}' (or ':') */
3942 end_ch = '}';
3943 if (ENABLE_HUSH_BASH_COMPAT
3944 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003945 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003946 ) {
3947 /* It's ${var:N[:M]} thing */
3948 end_ch = '}' * 0x100 + ':';
3949 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003950 if (ENABLE_HUSH_BASH_COMPAT
3951 && ch == '/'
3952 ) {
3953 /* It's ${var/[/]pattern[/repl]} thing */
3954 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3955 i_getch(input);
3956 nommu_addchr(as_string, '/');
3957 ch = '\\';
3958 }
3959 end_ch = '}' * 0x100 + '/';
3960 }
3961 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003962 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003963 if (!BB_MMU)
3964 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003965#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003966 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003967 if (last_ch == 0) /* error? */
3968 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003969#else
3970#error Simple code to only allow ${var} is not implemented
3971#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003972 if (as_string) {
3973 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003974 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003975 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003976
3977 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3978 /* close the first block: */
3979 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003980 /* while parsing N from ${var:N[:M]}
3981 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003982 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003983 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003984 end_ch = '}';
3985 goto again;
3986 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003987 /* got '}' */
3988 if (end_ch == '}' * 0x100 + ':') {
3989 /* it's ${var:N} - emulate :999999999 */
3990 o_addstr(dest, "999999999");
3991 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003992 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003993 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003994 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003995 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003996 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3997 break;
3998 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003999#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004000 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004001 unsigned pos;
4002
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004003 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004004 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004005# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004006 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004007 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004008 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004009 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4010 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004011 if (!BB_MMU)
4012 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004013 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4014 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004015 if (as_string) {
4016 o_addstr(as_string, dest->data + pos);
4017 o_addchr(as_string, ')');
4018 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004019 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004020 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004021 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004022 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004023# endif
4024# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004025 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4026 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004027 if (!BB_MMU)
4028 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004029 if (!add_till_closing_bracket(dest, input, ')'))
4030 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004031 if (as_string) {
4032 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004033 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004034 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004035 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004036# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004037 break;
4038 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004039#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004040 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004041 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004042 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004043 ch = i_peek(input);
4044 if (isalnum(ch)) { /* it's $_name or $_123 */
4045 ch = '_';
4046 goto make_var;
4047 }
4048 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004049 /* TODO: $_ and $-: */
4050 /* $_ Shell or shell script name; or last argument of last command
4051 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4052 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004053 /* $- Option flags set by set builtin or shell options (-i etc) */
4054 default:
4055 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004056 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004057 debug_printf_parse("parse_dollar return 1 (ok)\n");
4058 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004059#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004060}
4061
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004062#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004063# if ENABLE_HUSH_BASH_COMPAT
4064#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4065 encode_string(dest, input, dquote_end, process_bkslash)
4066# else
4067/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4068#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4069 encode_string(dest, input, dquote_end)
4070# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004071#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004072
4073#else /* !MMU */
4074
4075# if ENABLE_HUSH_BASH_COMPAT
4076/* all parameters are needed, no macro tricks */
4077# else
4078#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4079 encode_string(as_string, dest, input, dquote_end)
4080# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004081#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004082static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004083 o_string *dest,
4084 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004085 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004086 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004087{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004088#if !ENABLE_HUSH_BASH_COMPAT
4089 const int process_bkslash = 1;
4090#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004091 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004092 int next;
4093
4094 again:
4095 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004096 if (ch != EOF)
4097 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004098 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004099 debug_printf_parse("encode_string return 1 (ok)\n");
4100 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004101 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004102 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004103 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004104 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004105 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004106 }
4107 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004108 if (ch != '\n') {
4109 next = i_peek(input);
4110 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004111 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004112 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004113 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004114 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004115 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004116 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004117 }
4118 /* bash:
4119 * "The backslash retains its special meaning [in "..."]
4120 * only when followed by one of the following characters:
4121 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004122 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004123 * NB: in (unquoted) heredoc, above does not apply to ",
4124 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004125 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004126 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004127 ch = i_getch(input); /* eat next */
4128 if (ch == '\n')
4129 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004130 } /* else: ch remains == '\\', and we double it below: */
4131 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004132 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004133 goto again;
4134 }
4135 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004136 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4137 debug_printf_parse("encode_string return 0: "
4138 "parse_dollar returned 0 (error)\n");
4139 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004140 }
4141 goto again;
4142 }
4143#if ENABLE_HUSH_TICK
4144 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004145 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004146 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4147 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004148 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4149 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004150 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4151 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004152 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004153 }
4154#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004155 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004156 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004157#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004158}
4159
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004160/*
4161 * Scan input until EOF or end_trigger char.
4162 * Return a list of pipes to execute, or NULL on EOF
4163 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004164 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004165 * reset parsing machinery and start parsing anew,
4166 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004167 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004168static struct pipe *parse_stream(char **pstring,
4169 struct in_str *input,
4170 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004171{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004172 struct parse_context ctx;
4173 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004174 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004175
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004176 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004177 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004178 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004179 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004180 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004181 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004182
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004183 /* If very first arg is "" or '', dest.data may end up NULL.
4184 * Preventing this: */
4185 o_addchr(&dest, '\0');
4186 dest.length = 0;
4187
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004188 /* We used to separate words on $IFS here. This was wrong.
4189 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004190 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004191 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004192
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004193 if (MAYBE_ASSIGNMENT != 0)
4194 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004195 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004196 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004197 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004198 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004199 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004200 int ch;
4201 int next;
4202 int redir_fd;
4203 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004204
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004205 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004206 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004207 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004208 if (ch == EOF) {
4209 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004210
4211 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004212 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004213 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004214 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004215 /* end_trigger == '}' case errors out earlier,
4216 * checking only ')' */
4217 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004218 syntax_error_unterm_ch('(');
4219 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004220 }
4221
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004222 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004223 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004224 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004225 o_free(&dest);
4226 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004227 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004228 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004229 /* (this makes bare "&" cmd a no-op.
4230 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004231 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004232 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004233 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004234 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004235 pi = NULL;
4236 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004237#if !BB_MMU
4238 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4239 if (pstring)
4240 *pstring = ctx.as_string.data;
4241 else
4242 o_free_unsafe(&ctx.as_string);
4243#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004244 debug_leave();
4245 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004246 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004247 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004248 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004249
4250 next = '\0';
4251 if (ch != '\n')
4252 next = i_peek(input);
4253
4254 is_special = "{}<>;&|()#'" /* special outside of "str" */
4255 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4256 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004257 if (ctx.command->argv /* word [word]{... - non-special */
4258 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004259 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004260 || (next != ';' /* }; - special */
4261 && next != ')' /* }) - special */
4262 && next != '&' /* }& and }&& ... - special */
4263 && next != '|' /* }|| ... - special */
4264 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004265 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004266 ) {
4267 /* They are not special, skip "{}" */
4268 is_special += 2;
4269 }
4270 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004271 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004272
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004273 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004274 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004275 o_addQchr(&dest, ch);
4276 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4277 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004278 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004279 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004280 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004281 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004282 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004283 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004284 continue;
4285 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004286
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004287 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004288 if (done_word(&dest, &ctx)) {
4289 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004290 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004291 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004292 /* Is this a case when newline is simply ignored?
4293 * Some examples:
4294 * "cmd | <newline> cmd ..."
4295 * "case ... in <newline> word) ..."
4296 */
4297 if (IS_NULL_CMD(ctx.command)
4298 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004299 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004300 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004301 * Without check #1, interactive shell
4302 * ignores even bare <newline>,
4303 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004304 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004305 * ps2> _ <=== wrong, should be ps1
4306 * Without check #2, "cmd & <newline>"
4307 * is similarly mistreated.
4308 * (BTW, this makes "cmd & cmd"
4309 * and "cmd && cmd" non-orthogonal.
4310 * Really, ask yourself, why
4311 * "cmd && <newline>" doesn't start
4312 * cmd but waits for more input?
4313 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004314 */
4315 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004316 if (pi->num_cmds != 0 /* check #1 */
4317 && pi->followup != PIPE_BG /* check #2 */
4318 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004319 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004320 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004321 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004322 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004323 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004324 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4325 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004326 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004327 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004328 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004329 heredoc_cnt = 0;
4330 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004331 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004332 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004333 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004334 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004335 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004336 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004337 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004338
4339 /* "cmd}" or "cmd }..." without semicolon or &:
4340 * } is an ordinary char in this case, even inside { cmd; }
4341 * Pathological example: { ""}; } should exec "}" cmd
4342 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004343 if (ch == '}') {
4344 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4345 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004346 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004347 ) {
4348 goto ordinary_char;
4349 }
4350 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4351 goto skip_end_trigger;
4352 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004353 }
4354
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004355 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004356 && (ch != ';' || heredoc_cnt == 0)
4357#if ENABLE_HUSH_CASE
4358 && (ch != ')'
4359 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004360 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004361 )
4362#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004363 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004364 if (heredoc_cnt) {
4365 /* This is technically valid:
4366 * { cat <<HERE; }; echo Ok
4367 * heredoc
4368 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004369 * HERE
4370 * but we don't support this.
4371 * We require heredoc to be in enclosing {}/(),
4372 * if any.
4373 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004374 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004375 goto parse_error;
4376 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004377 if (done_word(&dest, &ctx)) {
4378 goto parse_error;
4379 }
4380 done_pipe(&ctx, PIPE_SEQ);
4381 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004382 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004383 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004384 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004385 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004386 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004387 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004388#if !BB_MMU
4389 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4390 if (pstring)
4391 *pstring = ctx.as_string.data;
4392 else
4393 o_free_unsafe(&ctx.as_string);
4394#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004395 debug_leave();
4396 debug_printf_parse("parse_stream return %p: "
4397 "end_trigger char found\n",
4398 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004399 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004400 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004401 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004402 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004403 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004404 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004405
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004406 /* Catch <, > before deciding whether this word is
4407 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4408 switch (ch) {
4409 case '>':
4410 redir_fd = redirect_opt_num(&dest);
4411 if (done_word(&dest, &ctx)) {
4412 goto parse_error;
4413 }
4414 redir_style = REDIRECT_OVERWRITE;
4415 if (next == '>') {
4416 redir_style = REDIRECT_APPEND;
4417 ch = i_getch(input);
4418 nommu_addchr(&ctx.as_string, ch);
4419 }
4420#if 0
4421 else if (next == '(') {
4422 syntax_error(">(process) not supported");
4423 goto parse_error;
4424 }
4425#endif
4426 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4427 goto parse_error;
4428 continue; /* back to top of while (1) */
4429 case '<':
4430 redir_fd = redirect_opt_num(&dest);
4431 if (done_word(&dest, &ctx)) {
4432 goto parse_error;
4433 }
4434 redir_style = REDIRECT_INPUT;
4435 if (next == '<') {
4436 redir_style = REDIRECT_HEREDOC;
4437 heredoc_cnt++;
4438 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4439 ch = i_getch(input);
4440 nommu_addchr(&ctx.as_string, ch);
4441 } else if (next == '>') {
4442 redir_style = REDIRECT_IO;
4443 ch = i_getch(input);
4444 nommu_addchr(&ctx.as_string, ch);
4445 }
4446#if 0
4447 else if (next == '(') {
4448 syntax_error("<(process) not supported");
4449 goto parse_error;
4450 }
4451#endif
4452 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4453 goto parse_error;
4454 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004455 case '#':
4456 if (dest.length == 0 && !dest.has_quoted_part) {
4457 /* skip "#comment" */
4458 while (1) {
4459 ch = i_peek(input);
4460 if (ch == EOF || ch == '\n')
4461 break;
4462 i_getch(input);
4463 /* note: we do not add it to &ctx.as_string */
4464 }
4465 nommu_addchr(&ctx.as_string, '\n');
4466 continue; /* back to top of while (1) */
4467 }
4468 break;
4469 case '\\':
4470 if (next == '\n') {
4471 /* It's "\<newline>" */
4472#if !BB_MMU
4473 /* Remove trailing '\' from ctx.as_string */
4474 ctx.as_string.data[--ctx.as_string.length] = '\0';
4475#endif
4476 ch = i_getch(input); /* eat it */
4477 continue; /* back to top of while (1) */
4478 }
4479 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004480 }
4481
4482 if (dest.o_assignment == MAYBE_ASSIGNMENT
4483 /* check that we are not in word in "a=1 2>word b=1": */
4484 && !ctx.pending_redirect
4485 ) {
4486 /* ch is a special char and thus this word
4487 * cannot be an assignment */
4488 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004489 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004490 }
4491
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004492 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4493
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004494 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004495 case '#': /* non-comment #: "echo a#b" etc */
4496 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004497 break;
4498 case '\\':
4499 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004500 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004501 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004502 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004503 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004504 /* note: ch != '\n' (that case does not reach this place) */
4505 o_addchr(&dest, '\\');
4506 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4507 o_addchr(&dest, ch);
4508 nommu_addchr(&ctx.as_string, ch);
4509 /* Example: echo Hello \2>file
4510 * we need to know that word 2 is quoted */
4511 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004512 break;
4513 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004514 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004515 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004516 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004517 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004518 }
Eric Andersen25f27032001-04-26 23:22:31 +00004519 break;
4520 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004521 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004522 if (next == '\'' && !ctx.pending_redirect) {
4523 insert_empty_quoted_str_marker:
4524 nommu_addchr(&ctx.as_string, next);
4525 i_getch(input); /* eat second ' */
4526 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4527 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4528 } else {
4529 while (1) {
4530 ch = i_getch(input);
4531 if (ch == EOF) {
4532 syntax_error_unterm_ch('\'');
4533 goto parse_error;
4534 }
4535 nommu_addchr(&ctx.as_string, ch);
4536 if (ch == '\'')
4537 break;
4538 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004539 }
Eric Andersen25f27032001-04-26 23:22:31 +00004540 }
Eric Andersen25f27032001-04-26 23:22:31 +00004541 break;
4542 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004543 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004544 if (next == '"' && !ctx.pending_redirect)
4545 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004546 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004547 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004548 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004549 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004550 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004551 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004552#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004553 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004554 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004555
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004556 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4557 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004558 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004559 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4560 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004561# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004562 o_addstr(&ctx.as_string, dest.data + pos);
4563 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004564# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004565 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4566 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004567 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004568 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004569#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004570 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004571#if ENABLE_HUSH_CASE
4572 case_semi:
4573#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004574 if (done_word(&dest, &ctx)) {
4575 goto parse_error;
4576 }
4577 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004578#if ENABLE_HUSH_CASE
4579 /* Eat multiple semicolons, detect
4580 * whether it means something special */
4581 while (1) {
4582 ch = i_peek(input);
4583 if (ch != ';')
4584 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004585 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004586 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004587 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004588 ctx.ctx_dsemicolon = 1;
4589 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004590 break;
4591 }
4592 }
4593#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004594 new_cmd:
4595 /* We just finished a cmd. New one may start
4596 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004597 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004598 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004599 break;
4600 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004601 if (done_word(&dest, &ctx)) {
4602 goto parse_error;
4603 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004604 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004605 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004606 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004607 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004608 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004609 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004610 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004611 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004612 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004613 if (done_word(&dest, &ctx)) {
4614 goto parse_error;
4615 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004616#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004617 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004618 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004619#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004620 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004621 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004622 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004623 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004624 } else {
4625 /* we could pick up a file descriptor choice here
4626 * with redirect_opt_num(), but bash doesn't do it.
4627 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004628 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004629#if !BB_MMU
4630 o_reset_to_empty_unquoted(&ctx.as_string);
4631#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004632 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004633 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004634 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004635#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004636 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004637 if (ctx.ctx_res_w == RES_MATCH
4638 && ctx.command->argv == NULL /* not (word|(... */
4639 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004640 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004641 ) {
4642 continue;
4643 }
4644#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004645 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004646 if (parse_group(&dest, &ctx, input, ch) != 0) {
4647 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004648 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004649 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004650 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004651#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004652 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004653 goto case_semi;
4654#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004655 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004656 /* proper use of this character is caught by end_trigger:
4657 * if we see {, we call parse_group(..., end_trigger='}')
4658 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004659 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004660 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004661 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004662 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004663 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004664 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004665 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004666
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004667 parse_error:
4668 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004669 struct parse_context *pctx;
4670 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004671
4672 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004673 * Sample for finding leaks on syntax error recovery path.
4674 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004675 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004676 * Samples to catch leaks at execution:
4677 * while if (true | {true;}); then echo ok; fi; do break; done
4678 * 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 +00004679 */
4680 pctx = &ctx;
4681 do {
4682 /* Update pipe/command counts,
4683 * otherwise freeing may miss some */
4684 done_pipe(pctx, PIPE_SEQ);
4685 debug_printf_clean("freeing list %p from ctx %p\n",
4686 pctx->list_head, pctx);
4687 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004688 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004689 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004690#if !BB_MMU
4691 o_free_unsafe(&pctx->as_string);
4692#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004693 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004694 if (pctx != &ctx) {
4695 free(pctx);
4696 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004697 IF_HAS_KEYWORDS(pctx = p2;)
4698 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004699
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004700 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004701 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004702#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004703 if (pstring)
4704 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004705#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004706 debug_leave();
4707 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004708 }
Eric Andersen25f27032001-04-26 23:22:31 +00004709}
4710
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004711
4712/*** Execution routines ***/
4713
4714/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004715#if !ENABLE_HUSH_BASH_COMPAT
4716/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4717#define expand_string_to_string(str, do_unbackslash) \
4718 expand_string_to_string(str)
4719#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004720static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004721#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004722static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004723#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004724
4725/* expand_strvec_to_strvec() takes a list of strings, expands
4726 * all variable references within and returns a pointer to
4727 * a list of expanded strings, possibly with larger number
4728 * of strings. (Think VAR="a b"; echo $VAR).
4729 * This new list is allocated as a single malloc block.
4730 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004731 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004732 * Caller can deallocate entire list by single free(list). */
4733
Denys Vlasenko238081f2010-10-03 14:26:26 +02004734/* A horde of its helpers come first: */
4735
4736static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4737{
4738 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004739 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004740
Denys Vlasenko9e800222010-10-03 14:28:04 +02004741#if ENABLE_HUSH_BRACE_EXPANSION
4742 if (c == '{' || c == '}') {
4743 /* { -> \{, } -> \} */
4744 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004745 /* And now we want to add { or } and continue:
4746 * o_addchr(o, c);
4747 * continue;
4748 * luckily, just falling throught achieves this.
4749 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004750 }
4751#endif
4752 o_addchr(o, c);
4753 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004754 /* \z -> \\\z; \<eol> -> \\<eol> */
4755 o_addchr(o, '\\');
4756 if (len) {
4757 len--;
4758 o_addchr(o, '\\');
4759 o_addchr(o, *str++);
4760 }
4761 }
4762 }
4763}
4764
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004765/* Store given string, finalizing the word and starting new one whenever
4766 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004767 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4768 * Return in *ended_with_ifs:
4769 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4770 */
4771static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004772{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004773 int last_is_ifs = 0;
4774
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004775 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004776 int word_len;
4777
4778 if (!*str) /* EOL - do not finalize word */
4779 break;
4780 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004781 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004782 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02004783 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004784 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004785 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004786 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004787 * Example: "v='\*'; echo b$v" prints "b\*"
4788 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004789 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004790 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004791 /*/ Why can't we do it easier? */
4792 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4793 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4794 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004795 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004796 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004797 if (!*str) /* EOL - do not finalize word */
4798 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004799 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004800
4801 /* We know str here points to at least one IFS char */
4802 last_is_ifs = 1;
4803 str += strspn(str, G.ifs); /* skip IFS chars */
4804 if (!*str) /* EOL - do not finalize word */
4805 break;
4806
4807 /* Start new word... but not always! */
4808 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004809 if (output->has_quoted_part
4810 /* Case "v=' a'; echo $v":
4811 * here nothing precedes the space in $v expansion,
4812 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004813 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004814 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004815 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004816 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004817 o_addchr(output, '\0');
4818 debug_print_list("expand_on_ifs", output, n);
4819 n = o_save_ptr(output, n);
4820 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004821 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004822
4823 if (ended_with_ifs)
4824 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004825 debug_print_list("expand_on_ifs[1]", output, n);
4826 return n;
4827}
4828
4829/* Helper to expand $((...)) and heredoc body. These act as if
4830 * they are in double quotes, with the exception that they are not :).
4831 * Just the rules are similar: "expand only $var and `cmd`"
4832 *
4833 * Returns malloced string.
4834 * As an optimization, we return NULL if expansion is not needed.
4835 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004836#if !ENABLE_HUSH_BASH_COMPAT
4837/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4838#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4839 encode_then_expand_string(str)
4840#endif
4841static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004842{
4843 char *exp_str;
4844 struct in_str input;
4845 o_string dest = NULL_O_STRING;
4846
4847 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004848 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004849#if ENABLE_HUSH_TICK
4850 && !strchr(str, '`')
4851#endif
4852 ) {
4853 return NULL;
4854 }
4855
4856 /* We need to expand. Example:
4857 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4858 */
4859 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004860 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004861//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004862 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004863 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004864 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4865 o_free_unsafe(&dest);
4866 return exp_str;
4867}
4868
4869#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004870static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004871{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004872 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004873 arith_t res;
4874 char *exp_str;
4875
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004876 math_state.lookupvar = get_local_var_value;
4877 math_state.setvar = set_local_var_from_halves;
4878 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004879 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004880 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004881 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004882 if (errmsg_p)
4883 *errmsg_p = math_state.errmsg;
4884 if (math_state.errmsg)
4885 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004886 return res;
4887}
4888#endif
4889
4890#if ENABLE_HUSH_BASH_COMPAT
4891/* ${var/[/]pattern[/repl]} helpers */
4892static char *strstr_pattern(char *val, const char *pattern, int *size)
4893{
4894 while (1) {
4895 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4896 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4897 if (end) {
4898 *size = end - val;
4899 return val;
4900 }
4901 if (*val == '\0')
4902 return NULL;
4903 /* Optimization: if "*pat" did not match the start of "string",
4904 * we know that "tring", "ring" etc will not match too:
4905 */
4906 if (pattern[0] == '*')
4907 return NULL;
4908 val++;
4909 }
4910}
4911static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4912{
4913 char *result = NULL;
4914 unsigned res_len = 0;
4915 unsigned repl_len = strlen(repl);
4916
4917 while (1) {
4918 int size;
4919 char *s = strstr_pattern(val, pattern, &size);
4920 if (!s)
4921 break;
4922
4923 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4924 memcpy(result + res_len, val, s - val);
4925 res_len += s - val;
4926 strcpy(result + res_len, repl);
4927 res_len += repl_len;
4928 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4929
4930 val = s + size;
4931 if (exp_op == '/')
4932 break;
4933 }
4934 if (val[0] && result) {
4935 result = xrealloc(result, res_len + strlen(val) + 1);
4936 strcpy(result + res_len, val);
4937 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4938 }
4939 debug_printf_varexp("result:'%s'\n", result);
4940 return result;
4941}
4942#endif
4943
4944/* Helper:
4945 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4946 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004947static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004948{
4949 const char *val = NULL;
4950 char *to_be_freed = NULL;
4951 char *p = *pp;
4952 char *var;
4953 char first_char;
4954 char exp_op;
4955 char exp_save = exp_save; /* for compiler */
4956 char *exp_saveptr; /* points to expansion operator */
4957 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004958 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004959
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004960 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004961 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004962 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004963 arg0 = arg[0];
4964 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004965 exp_op = 0;
4966
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004967 if (first_char == '#' /* ${#... */
4968 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4969 ) {
4970 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004971 var++;
4972 exp_op = 'L';
4973 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004974 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004975 if (exp_saveptr /* if 2nd char is one of expansion operators */
4976 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4977 ) {
4978 /* ${?:0}, ${#[:]%0} etc */
4979 exp_saveptr = var + 1;
4980 } else {
4981 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4982 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4983 }
4984 exp_op = exp_save = *exp_saveptr;
4985 if (exp_op) {
4986 exp_word = exp_saveptr + 1;
4987 if (exp_op == ':') {
4988 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004989//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004990 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004991 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004992 ) {
4993 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4994 exp_op = ':';
4995 exp_word--;
4996 }
4997 }
4998 *exp_saveptr = '\0';
4999 } /* else: it's not an expansion op, but bare ${var} */
5000 }
5001
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005002 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005003 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005004 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005005 int n = xatoi_positive(var);
5006 if (n < G.global_argc)
5007 val = G.global_argv[n];
5008 /* else val remains NULL: $N with too big N */
5009 } else {
5010 switch (var[0]) {
5011 case '$': /* pid */
5012 val = utoa(G.root_pid);
5013 break;
5014 case '!': /* bg pid */
5015 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5016 break;
5017 case '?': /* exitcode */
5018 val = utoa(G.last_exitcode);
5019 break;
5020 case '#': /* argc */
5021 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5022 break;
5023 default:
5024 val = get_local_var_value(var);
5025 }
5026 }
5027
5028 /* Handle any expansions */
5029 if (exp_op == 'L') {
5030 debug_printf_expand("expand: length(%s)=", val);
5031 val = utoa(val ? strlen(val) : 0);
5032 debug_printf_expand("%s\n", val);
5033 } else if (exp_op) {
5034 if (exp_op == '%' || exp_op == '#') {
5035 /* Standard-mandated substring removal ops:
5036 * ${parameter%word} - remove smallest suffix pattern
5037 * ${parameter%%word} - remove largest suffix pattern
5038 * ${parameter#word} - remove smallest prefix pattern
5039 * ${parameter##word} - remove largest prefix pattern
5040 *
5041 * Word is expanded to produce a glob pattern.
5042 * Then var's value is matched to it and matching part removed.
5043 */
5044 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005045 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005046 char *exp_exp_word;
5047 char *loc;
5048 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005049 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005050 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005051 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005052 if (exp_exp_word)
5053 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005054 /* HACK ALERT. We depend here on the fact that
5055 * G.global_argv and results of utoa and get_local_var_value
5056 * are actually in writable memory:
5057 * scan_and_match momentarily stores NULs there. */
5058 t = (char*)val;
5059 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005060 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005061 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005062 free(exp_exp_word);
5063 if (loc) { /* match was found */
5064 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005065 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005066 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005067 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005068 }
5069 }
5070 }
5071#if ENABLE_HUSH_BASH_COMPAT
5072 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005073 /* It's ${var/[/]pattern[/repl]} thing.
5074 * Note that in encoded form it has TWO parts:
5075 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005076 * and if // is used, it is encoded as \:
5077 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005078 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005079 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005080 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005081 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005082 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005083 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005084 * by the usual expansion rules:
5085 * >az; >bz;
5086 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5087 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5088 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5089 * v='a bz'; echo ${v/a*z/\z} prints "z"
5090 * (note that a*z _pattern_ is never globbed!)
5091 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005092 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005093 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005094 if (!pattern)
5095 pattern = xstrdup(exp_word);
5096 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5097 *p++ = SPECIAL_VAR_SYMBOL;
5098 exp_word = p;
5099 p = strchr(p, SPECIAL_VAR_SYMBOL);
5100 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005101 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005102 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5103 /* HACK ALERT. We depend here on the fact that
5104 * G.global_argv and results of utoa and get_local_var_value
5105 * are actually in writable memory:
5106 * replace_pattern momentarily stores NULs there. */
5107 t = (char*)val;
5108 to_be_freed = replace_pattern(t,
5109 pattern,
5110 (repl ? repl : exp_word),
5111 exp_op);
5112 if (to_be_freed) /* at least one replace happened */
5113 val = to_be_freed;
5114 free(pattern);
5115 free(repl);
5116 }
5117 }
5118#endif
5119 else if (exp_op == ':') {
5120#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5121 /* It's ${var:N[:M]} bashism.
5122 * Note that in encoded form it has TWO parts:
5123 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5124 */
5125 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005126 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005127
Denys Vlasenko063847d2010-09-15 13:33:02 +02005128 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5129 if (errmsg)
5130 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005131 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5132 *p++ = SPECIAL_VAR_SYMBOL;
5133 exp_word = p;
5134 p = strchr(p, SPECIAL_VAR_SYMBOL);
5135 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005136 len = expand_and_evaluate_arith(exp_word, &errmsg);
5137 if (errmsg)
5138 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005139 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005140 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005141 if (beg < 0) /* bash compat */
5142 beg = 0;
5143 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005144 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005145 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005146 val = NULL;
5147 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005148 /* Paranoia. What if user entered 9999999999999
5149 * which fits in arith_t but not int? */
5150 if (len >= INT_MAX)
5151 len = INT_MAX;
5152 val = to_be_freed = xstrndup(val + beg, len);
5153 }
5154 debug_printf_varexp("val:'%s'\n", val);
5155 } else
5156#endif
5157 {
5158 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005159 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005160 }
5161 } else { /* one of "-=+?" */
5162 /* Standard-mandated substitution ops:
5163 * ${var?word} - indicate error if unset
5164 * If var is unset, word (or a message indicating it is unset
5165 * if word is null) is written to standard error
5166 * and the shell exits with a non-zero exit status.
5167 * Otherwise, the value of var is substituted.
5168 * ${var-word} - use default value
5169 * If var is unset, word is substituted.
5170 * ${var=word} - assign and use default value
5171 * If var is unset, word is assigned to var.
5172 * In all cases, final value of var is substituted.
5173 * ${var+word} - use alternative value
5174 * If var is unset, null is substituted.
5175 * Otherwise, word is substituted.
5176 *
5177 * Word is subjected to tilde expansion, parameter expansion,
5178 * command substitution, and arithmetic expansion.
5179 * If word is not needed, it is not expanded.
5180 *
5181 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5182 * but also treat null var as if it is unset.
5183 */
5184 int use_word = (!val || ((exp_save == ':') && !val[0]));
5185 if (exp_op == '+')
5186 use_word = !use_word;
5187 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5188 (exp_save == ':') ? "true" : "false", use_word);
5189 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005190 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005191 if (to_be_freed)
5192 exp_word = to_be_freed;
5193 if (exp_op == '?') {
5194 /* mimic bash message */
5195 die_if_script("%s: %s",
5196 var,
5197 exp_word[0] ? exp_word : "parameter null or not set"
5198 );
5199//TODO: how interactive bash aborts expansion mid-command?
5200 } else {
5201 val = exp_word;
5202 }
5203
5204 if (exp_op == '=') {
5205 /* ${var=[word]} or ${var:=[word]} */
5206 if (isdigit(var[0]) || var[0] == '#') {
5207 /* mimic bash message */
5208 die_if_script("$%s: cannot assign in this way", var);
5209 val = NULL;
5210 } else {
5211 char *new_var = xasprintf("%s=%s", var, val);
5212 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5213 }
5214 }
5215 }
5216 } /* one of "-=+?" */
5217
5218 *exp_saveptr = exp_save;
5219 } /* if (exp_op) */
5220
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005221 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005222
5223 *pp = p;
5224 *to_be_freed_pp = to_be_freed;
5225 return val;
5226}
5227
5228/* Expand all variable references in given string, adding words to list[]
5229 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5230 * to be filled). This routine is extremely tricky: has to deal with
5231 * variables/parameters with whitespace, $* and $@, and constructs like
5232 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005233static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005234{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005235 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005236 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005237 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005238 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005239 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005240 char *p;
5241
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005242 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5243 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005244 debug_print_list("expand_vars_to_list", output, n);
5245 n = o_save_ptr(output, n);
5246 debug_print_list("expand_vars_to_list[0]", output, n);
5247
5248 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5249 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005250 char *to_be_freed = NULL;
5251 const char *val = NULL;
5252#if ENABLE_HUSH_TICK
5253 o_string subst_result = NULL_O_STRING;
5254#endif
5255#if ENABLE_SH_MATH_SUPPORT
5256 char arith_buf[sizeof(arith_t)*3 + 2];
5257#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005258
5259 if (ended_in_ifs) {
5260 o_addchr(output, '\0');
5261 n = o_save_ptr(output, n);
5262 ended_in_ifs = 0;
5263 }
5264
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005265 o_addblock(output, arg, p - arg);
5266 debug_print_list("expand_vars_to_list[1]", output, n);
5267 arg = ++p;
5268 p = strchr(p, SPECIAL_VAR_SYMBOL);
5269
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005270 /* Fetch special var name (if it is indeed one of them)
5271 * and quote bit, force the bit on if singleword expansion -
5272 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005273 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005274
5275 /* Is this variable quoted and thus expansion can't be null?
5276 * "$@" is special. Even if quoted, it can still
5277 * expand to nothing (not even an empty string),
5278 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005279 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005280 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005281
5282 switch (first_ch & 0x7f) {
5283 /* Highest bit in first_ch indicates that var is double-quoted */
5284 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005285 case '@': {
5286 int i;
5287 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005288 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005289 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005290 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005291 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005292 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005293 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005294 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5295 if (G.global_argv[i++][0] && G.global_argv[i]) {
5296 /* this argv[] is not empty and not last:
5297 * put terminating NUL, start new word */
5298 o_addchr(output, '\0');
5299 debug_print_list("expand_vars_to_list[2]", output, n);
5300 n = o_save_ptr(output, n);
5301 debug_print_list("expand_vars_to_list[3]", output, n);
5302 }
5303 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005304 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005305 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005306 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005307 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005308 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005309 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005310 while (1) {
5311 o_addQstr(output, G.global_argv[i]);
5312 if (++i >= G.global_argc)
5313 break;
5314 o_addchr(output, '\0');
5315 debug_print_list("expand_vars_to_list[4]", output, n);
5316 n = o_save_ptr(output, n);
5317 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005318 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005319 while (1) {
5320 o_addQstr(output, G.global_argv[i]);
5321 if (!G.global_argv[++i])
5322 break;
5323 if (G.ifs[0])
5324 o_addchr(output, G.ifs[0]);
5325 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005326 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005327 }
5328 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005329 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005330 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5331 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005332 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005333 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005334 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005335 break;
5336#if ENABLE_HUSH_TICK
5337 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005338 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005339 arg++;
5340 /* Can't just stuff it into output o_string,
5341 * expanded result may need to be globbed
5342 * and $IFS-splitted */
5343 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5344 G.last_exitcode = process_command_subs(&subst_result, arg);
5345 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5346 val = subst_result.data;
5347 goto store_val;
5348#endif
5349#if ENABLE_SH_MATH_SUPPORT
5350 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5351 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005352
5353 arg++; /* skip '+' */
5354 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5355 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005356 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005357 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5358 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005359 val = arith_buf;
5360 break;
5361 }
5362#endif
5363 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005364 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005365 IF_HUSH_TICK(store_val:)
5366 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005367 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5368 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005369 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005370 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005371 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005372 }
5373 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005374 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005375 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5376 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005377 }
5378 break;
5379
5380 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5381
5382 if (val && val[0]) {
5383 o_addQstr(output, val);
5384 }
5385 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005386
5387 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5388 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005389 if (*p != SPECIAL_VAR_SYMBOL)
5390 *p = SPECIAL_VAR_SYMBOL;
5391
5392#if ENABLE_HUSH_TICK
5393 o_free(&subst_result);
5394#endif
5395 arg = ++p;
5396 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5397
5398 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005399 if (ended_in_ifs) {
5400 o_addchr(output, '\0');
5401 n = o_save_ptr(output, n);
5402 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005403 debug_print_list("expand_vars_to_list[a]", output, n);
5404 /* this part is literal, and it was already pre-quoted
5405 * if needed (much earlier), do not use o_addQstr here! */
5406 o_addstr_with_NUL(output, arg);
5407 debug_print_list("expand_vars_to_list[b]", output, n);
5408 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005409 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005410 ) {
5411 n--;
5412 /* allow to reuse list[n] later without re-growth */
5413 output->has_empty_slot = 1;
5414 } else {
5415 o_addchr(output, '\0');
5416 }
5417
5418 return n;
5419}
5420
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005421static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005422{
5423 int n;
5424 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005425 o_string output = NULL_O_STRING;
5426
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005427 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005428
5429 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005430 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005431 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005432 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005433 }
5434 debug_print_list("expand_variables", &output, n);
5435
5436 /* output.data (malloced in one block) gets returned in "list" */
5437 list = o_finalize_list(&output, n);
5438 debug_print_strings("expand_variables[1]", list);
5439 return list;
5440}
5441
5442static char **expand_strvec_to_strvec(char **argv)
5443{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005444 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005445}
5446
5447#if ENABLE_HUSH_BASH_COMPAT
5448static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5449{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005450 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005451}
5452#endif
5453
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005454/* Used for expansion of right hand of assignments,
5455 * $((...)), heredocs, variable espansion parts.
5456 *
5457 * NB: should NOT do globbing!
5458 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5459 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005460static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005461{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005462#if !ENABLE_HUSH_BASH_COMPAT
5463 const int do_unbackslash = 1;
5464#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005465 char *argv[2], **list;
5466
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005467 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005468 /* This is generally an optimization, but it also
5469 * handles "", which otherwise trips over !list[0] check below.
5470 * (is this ever happens that we actually get str="" here?)
5471 */
5472 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5473 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005474 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005475 return xstrdup(str);
5476 }
5477
5478 argv[0] = (char*)str;
5479 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005480 list = expand_variables(argv, do_unbackslash
5481 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5482 : EXP_FLAG_SINGLEWORD
5483 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005484 if (HUSH_DEBUG)
5485 if (!list[0] || list[1])
5486 bb_error_msg_and_die("BUG in varexp2");
5487 /* actually, just move string 2*sizeof(char*) bytes back */
5488 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005489 if (do_unbackslash)
5490 unbackslash((char*)list);
5491 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005492 return (char*)list;
5493}
5494
5495/* Used for "eval" builtin */
5496static char* expand_strvec_to_string(char **argv)
5497{
5498 char **list;
5499
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005500 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005501 /* Convert all NULs to spaces */
5502 if (list[0]) {
5503 int n = 1;
5504 while (list[n]) {
5505 if (HUSH_DEBUG)
5506 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5507 bb_error_msg_and_die("BUG in varexp3");
5508 /* bash uses ' ' regardless of $IFS contents */
5509 list[n][-1] = ' ';
5510 n++;
5511 }
5512 }
5513 overlapping_strcpy((char*)list, list[0]);
5514 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5515 return (char*)list;
5516}
5517
5518static char **expand_assignments(char **argv, int count)
5519{
5520 int i;
5521 char **p;
5522
5523 G.expanded_assignments = p = NULL;
5524 /* Expand assignments into one string each */
5525 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005526 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005527 }
5528 G.expanded_assignments = NULL;
5529 return p;
5530}
5531
5532
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005533static void switch_off_special_sigs(unsigned mask)
5534{
5535 unsigned sig = 0;
5536 while ((mask >>= 1) != 0) {
5537 sig++;
5538 if (!(mask & 1))
5539 continue;
5540 if (G.traps) {
5541 if (G.traps[sig] && !G.traps[sig][0])
5542 /* trap is '', has to remain SIG_IGN */
5543 continue;
5544 free(G.traps[sig]);
5545 G.traps[sig] = NULL;
5546 }
5547 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005548 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005549 }
5550}
5551
Denys Vlasenkob347df92011-08-09 22:49:15 +02005552#if BB_MMU
5553/* never called */
5554void re_execute_shell(char ***to_free, const char *s,
5555 char *g_argv0, char **g_argv,
5556 char **builtin_argv) NORETURN;
5557
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005558static void reset_traps_to_defaults(void)
5559{
5560 /* This function is always called in a child shell
5561 * after fork (not vfork, NOMMU doesn't use this function).
5562 */
5563 unsigned sig;
5564 unsigned mask;
5565
5566 /* Child shells are not interactive.
5567 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5568 * Testcase: (while :; do :; done) + ^Z should background.
5569 * Same goes for SIGTERM, SIGHUP, SIGINT.
5570 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005571 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5572 if (!G.traps && !mask)
5573 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005574
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005575 /* Switch off special sigs */
5576 switch_off_special_sigs(mask);
5577#if ENABLE_HUSH_JOB
5578 G_fatal_sig_mask = 0;
5579#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005580 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005581 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5582 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005583
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005584 if (!G.traps)
5585 return;
5586
5587 /* Reset all sigs to default except ones with empty traps */
5588 for (sig = 0; sig < NSIG; sig++) {
5589 if (!G.traps[sig])
5590 continue; /* no trap: nothing to do */
5591 if (!G.traps[sig][0])
5592 continue; /* empty trap: has to remain SIG_IGN */
5593 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005594 free(G.traps[sig]);
5595 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005596 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005597 if (sig == 0)
5598 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005599 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005600 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005601}
5602
5603#else /* !BB_MMU */
5604
5605static void re_execute_shell(char ***to_free, const char *s,
5606 char *g_argv0, char **g_argv,
5607 char **builtin_argv) NORETURN;
5608static void re_execute_shell(char ***to_free, const char *s,
5609 char *g_argv0, char **g_argv,
5610 char **builtin_argv)
5611{
5612# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5613 /* delims + 2 * (number of bytes in printed hex numbers) */
5614 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5615 char *heredoc_argv[4];
5616 struct variable *cur;
5617# if ENABLE_HUSH_FUNCTIONS
5618 struct function *funcp;
5619# endif
5620 char **argv, **pp;
5621 unsigned cnt;
5622 unsigned long long empty_trap_mask;
5623
5624 if (!g_argv0) { /* heredoc */
5625 argv = heredoc_argv;
5626 argv[0] = (char *) G.argv0_for_re_execing;
5627 argv[1] = (char *) "-<";
5628 argv[2] = (char *) s;
5629 argv[3] = NULL;
5630 pp = &argv[3]; /* used as pointer to empty environment */
5631 goto do_exec;
5632 }
5633
5634 cnt = 0;
5635 pp = builtin_argv;
5636 if (pp) while (*pp++)
5637 cnt++;
5638
5639 empty_trap_mask = 0;
5640 if (G.traps) {
5641 int sig;
5642 for (sig = 1; sig < NSIG; sig++) {
5643 if (G.traps[sig] && !G.traps[sig][0])
5644 empty_trap_mask |= 1LL << sig;
5645 }
5646 }
5647
5648 sprintf(param_buf, NOMMU_HACK_FMT
5649 , (unsigned) G.root_pid
5650 , (unsigned) G.root_ppid
5651 , (unsigned) G.last_bg_pid
5652 , (unsigned) G.last_exitcode
5653 , cnt
5654 , empty_trap_mask
5655 IF_HUSH_LOOPS(, G.depth_of_loop)
5656 );
5657# undef NOMMU_HACK_FMT
5658 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5659 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5660 */
5661 cnt += 6;
5662 for (cur = G.top_var; cur; cur = cur->next) {
5663 if (!cur->flg_export || cur->flg_read_only)
5664 cnt += 2;
5665 }
5666# if ENABLE_HUSH_FUNCTIONS
5667 for (funcp = G.top_func; funcp; funcp = funcp->next)
5668 cnt += 3;
5669# endif
5670 pp = g_argv;
5671 while (*pp++)
5672 cnt++;
5673 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5674 *pp++ = (char *) G.argv0_for_re_execing;
5675 *pp++ = param_buf;
5676 for (cur = G.top_var; cur; cur = cur->next) {
5677 if (strcmp(cur->varstr, hush_version_str) == 0)
5678 continue;
5679 if (cur->flg_read_only) {
5680 *pp++ = (char *) "-R";
5681 *pp++ = cur->varstr;
5682 } else if (!cur->flg_export) {
5683 *pp++ = (char *) "-V";
5684 *pp++ = cur->varstr;
5685 }
5686 }
5687# if ENABLE_HUSH_FUNCTIONS
5688 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5689 *pp++ = (char *) "-F";
5690 *pp++ = funcp->name;
5691 *pp++ = funcp->body_as_string;
5692 }
5693# endif
5694 /* We can pass activated traps here. Say, -Tnn:trap_string
5695 *
5696 * However, POSIX says that subshells reset signals with traps
5697 * to SIG_DFL.
5698 * I tested bash-3.2 and it not only does that with true subshells
5699 * of the form ( list ), but with any forked children shells.
5700 * I set trap "echo W" WINCH; and then tried:
5701 *
5702 * { echo 1; sleep 20; echo 2; } &
5703 * while true; do echo 1; sleep 20; echo 2; break; done &
5704 * true | { echo 1; sleep 20; echo 2; } | cat
5705 *
5706 * In all these cases sending SIGWINCH to the child shell
5707 * did not run the trap. If I add trap "echo V" WINCH;
5708 * _inside_ group (just before echo 1), it works.
5709 *
5710 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005711 */
5712 *pp++ = (char *) "-c";
5713 *pp++ = (char *) s;
5714 if (builtin_argv) {
5715 while (*++builtin_argv)
5716 *pp++ = *builtin_argv;
5717 *pp++ = (char *) "";
5718 }
5719 *pp++ = g_argv0;
5720 while (*g_argv)
5721 *pp++ = *g_argv++;
5722 /* *pp = NULL; - is already there */
5723 pp = environ;
5724
5725 do_exec:
5726 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02005727 /* Don't propagate SIG_IGN to the child */
5728 if (SPECIAL_JOBSTOP_SIGS != 0)
5729 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005730 execve(bb_busybox_exec_path, argv, pp);
5731 /* Fallback. Useful for init=/bin/hush usage etc */
5732 if (argv[0][0] == '/')
5733 execve(argv[0], argv, pp);
5734 xfunc_error_retval = 127;
5735 bb_error_msg_and_die("can't re-execute the shell");
5736}
5737#endif /* !BB_MMU */
5738
5739
5740static int run_and_free_list(struct pipe *pi);
5741
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005742/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005743 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5744 * end_trigger controls how often we stop parsing
5745 * NUL: parse all, execute, return
5746 * ';': parse till ';' or newline, execute, repeat till EOF
5747 */
5748static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005749{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005750 /* Why we need empty flag?
5751 * An obscure corner case "false; ``; echo $?":
5752 * empty command in `` should still set $? to 0.
5753 * But we can't just set $? to 0 at the start,
5754 * this breaks "false; echo `echo $?`" case.
5755 */
5756 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005757 while (1) {
5758 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005759
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005760#if ENABLE_HUSH_INTERACTIVE
5761 if (end_trigger == ';')
5762 inp->promptmode = 0; /* PS1 */
5763#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005764 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005765 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5766 /* If we are in "big" script
5767 * (not in `cmd` or something similar)...
5768 */
5769 if (pipe_list == ERR_PTR && end_trigger == ';') {
5770 /* Discard cached input (rest of line) */
5771 int ch = inp->last_char;
5772 while (ch != EOF && ch != '\n') {
5773 //bb_error_msg("Discarded:'%c'", ch);
5774 ch = i_getch(inp);
5775 }
5776 /* Force prompt */
5777 inp->p = NULL;
5778 /* This stream isn't empty */
5779 empty = 0;
5780 continue;
5781 }
5782 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01005783 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005784 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005785 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005786 debug_print_tree(pipe_list, 0);
5787 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5788 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005789 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005790#if ENABLE_HUSH_FUNCTIONS
5791 if (G.flag_return_in_progress == 1)
5792 break;
5793#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005794 }
Eric Andersen25f27032001-04-26 23:22:31 +00005795}
5796
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005797static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005798{
5799 struct in_str input;
5800 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005801 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005802}
5803
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005804static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005805{
Eric Andersen25f27032001-04-26 23:22:31 +00005806 struct in_str input;
5807 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005808 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005809}
5810
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005811#if ENABLE_HUSH_TICK
5812static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5813{
5814 pid_t pid;
5815 int channel[2];
5816# if !BB_MMU
5817 char **to_free = NULL;
5818# endif
5819
5820 xpipe(channel);
5821 pid = BB_MMU ? xfork() : xvfork();
5822 if (pid == 0) { /* child */
5823 disable_restore_tty_pgrp_on_exit();
5824 /* Process substitution is not considered to be usual
5825 * 'command execution'.
5826 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5827 */
5828 bb_signals(0
5829 + (1 << SIGTSTP)
5830 + (1 << SIGTTIN)
5831 + (1 << SIGTTOU)
5832 , SIG_IGN);
5833 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5834 close(channel[0]); /* NB: close _first_, then move fd! */
5835 xmove_fd(channel[1], 1);
5836 /* Prevent it from trying to handle ctrl-z etc */
5837 IF_HUSH_JOB(G.run_list_level = 1;)
5838 /* Awful hack for `trap` or $(trap).
5839 *
5840 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5841 * contains an example where "trap" is executed in a subshell:
5842 *
5843 * save_traps=$(trap)
5844 * ...
5845 * eval "$save_traps"
5846 *
5847 * Standard does not say that "trap" in subshell shall print
5848 * parent shell's traps. It only says that its output
5849 * must have suitable form, but then, in the above example
5850 * (which is not supposed to be normative), it implies that.
5851 *
5852 * bash (and probably other shell) does implement it
5853 * (traps are reset to defaults, but "trap" still shows them),
5854 * but as a result, "trap" logic is hopelessly messed up:
5855 *
5856 * # trap
5857 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5858 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5859 * # true | trap <--- trap is in subshell - no output (ditto)
5860 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5861 * trap -- 'echo Ho' SIGWINCH
5862 * # echo `(trap)` <--- in subshell in subshell - output
5863 * trap -- 'echo Ho' SIGWINCH
5864 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5865 * trap -- 'echo Ho' SIGWINCH
5866 *
5867 * The rules when to forget and when to not forget traps
5868 * get really complex and nonsensical.
5869 *
5870 * Our solution: ONLY bare $(trap) or `trap` is special.
5871 */
5872 s = skip_whitespace(s);
5873 if (strncmp(s, "trap", 4) == 0
5874 && skip_whitespace(s + 4)[0] == '\0'
5875 ) {
5876 static const char *const argv[] = { NULL, NULL };
5877 builtin_trap((char**)argv);
5878 exit(0); /* not _exit() - we need to fflush */
5879 }
5880# if BB_MMU
5881 reset_traps_to_defaults();
5882 parse_and_run_string(s);
5883 _exit(G.last_exitcode);
5884# else
5885 /* We re-execute after vfork on NOMMU. This makes this script safe:
5886 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5887 * huge=`cat BIG` # was blocking here forever
5888 * echo OK
5889 */
5890 re_execute_shell(&to_free,
5891 s,
5892 G.global_argv[0],
5893 G.global_argv + 1,
5894 NULL);
5895# endif
5896 }
5897
5898 /* parent */
5899 *pid_p = pid;
5900# if ENABLE_HUSH_FAST
5901 G.count_SIGCHLD++;
5902//bb_error_msg("[%d] fork in generate_stream_from_string:"
5903// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5904// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5905# endif
5906 enable_restore_tty_pgrp_on_exit();
5907# if !BB_MMU
5908 free(to_free);
5909# endif
5910 close(channel[1]);
5911 close_on_exec_on(channel[0]);
5912 return xfdopen_for_read(channel[0]);
5913}
5914
5915/* Return code is exit status of the process that is run. */
5916static int process_command_subs(o_string *dest, const char *s)
5917{
5918 FILE *fp;
5919 struct in_str pipe_str;
5920 pid_t pid;
5921 int status, ch, eol_cnt;
5922
5923 fp = generate_stream_from_string(s, &pid);
5924
5925 /* Now send results of command back into original context */
5926 setup_file_in_str(&pipe_str, fp);
5927 eol_cnt = 0;
5928 while ((ch = i_getch(&pipe_str)) != EOF) {
5929 if (ch == '\n') {
5930 eol_cnt++;
5931 continue;
5932 }
5933 while (eol_cnt) {
5934 o_addchr(dest, '\n');
5935 eol_cnt--;
5936 }
5937 o_addQchr(dest, ch);
5938 }
5939
5940 debug_printf("done reading from `cmd` pipe, closing it\n");
5941 fclose(fp);
5942 /* We need to extract exitcode. Test case
5943 * "true; echo `sleep 1; false` $?"
5944 * should print 1 */
5945 safe_waitpid(pid, &status, 0);
5946 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5947 return WEXITSTATUS(status);
5948}
5949#endif /* ENABLE_HUSH_TICK */
5950
5951
5952static void setup_heredoc(struct redir_struct *redir)
5953{
5954 struct fd_pair pair;
5955 pid_t pid;
5956 int len, written;
5957 /* the _body_ of heredoc (misleading field name) */
5958 const char *heredoc = redir->rd_filename;
5959 char *expanded;
5960#if !BB_MMU
5961 char **to_free;
5962#endif
5963
5964 expanded = NULL;
5965 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005966 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005967 if (expanded)
5968 heredoc = expanded;
5969 }
5970 len = strlen(heredoc);
5971
5972 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5973 xpiped_pair(pair);
5974 xmove_fd(pair.rd, redir->rd_fd);
5975
5976 /* Try writing without forking. Newer kernels have
5977 * dynamically growing pipes. Must use non-blocking write! */
5978 ndelay_on(pair.wr);
5979 while (1) {
5980 written = write(pair.wr, heredoc, len);
5981 if (written <= 0)
5982 break;
5983 len -= written;
5984 if (len == 0) {
5985 close(pair.wr);
5986 free(expanded);
5987 return;
5988 }
5989 heredoc += written;
5990 }
5991 ndelay_off(pair.wr);
5992
5993 /* Okay, pipe buffer was not big enough */
5994 /* Note: we must not create a stray child (bastard? :)
5995 * for the unsuspecting parent process. Child creates a grandchild
5996 * and exits before parent execs the process which consumes heredoc
5997 * (that exec happens after we return from this function) */
5998#if !BB_MMU
5999 to_free = NULL;
6000#endif
6001 pid = xvfork();
6002 if (pid == 0) {
6003 /* child */
6004 disable_restore_tty_pgrp_on_exit();
6005 pid = BB_MMU ? xfork() : xvfork();
6006 if (pid != 0)
6007 _exit(0);
6008 /* grandchild */
6009 close(redir->rd_fd); /* read side of the pipe */
6010#if BB_MMU
6011 full_write(pair.wr, heredoc, len); /* may loop or block */
6012 _exit(0);
6013#else
6014 /* Delegate blocking writes to another process */
6015 xmove_fd(pair.wr, STDOUT_FILENO);
6016 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6017#endif
6018 }
6019 /* parent */
6020#if ENABLE_HUSH_FAST
6021 G.count_SIGCHLD++;
6022//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6023#endif
6024 enable_restore_tty_pgrp_on_exit();
6025#if !BB_MMU
6026 free(to_free);
6027#endif
6028 close(pair.wr);
6029 free(expanded);
6030 wait(NULL); /* wait till child has died */
6031}
6032
6033/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6034 * and stderr if they are redirected. */
6035static int setup_redirects(struct command *prog, int squirrel[])
6036{
6037 int openfd, mode;
6038 struct redir_struct *redir;
6039
6040 for (redir = prog->redirects; redir; redir = redir->next) {
6041 if (redir->rd_type == REDIRECT_HEREDOC2) {
6042 /* rd_fd<<HERE case */
6043 if (squirrel && redir->rd_fd < 3
6044 && squirrel[redir->rd_fd] < 0
6045 ) {
6046 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6047 }
6048 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6049 * of the heredoc */
6050 debug_printf_parse("set heredoc '%s'\n",
6051 redir->rd_filename);
6052 setup_heredoc(redir);
6053 continue;
6054 }
6055
6056 if (redir->rd_dup == REDIRFD_TO_FILE) {
6057 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6058 char *p;
6059 if (redir->rd_filename == NULL) {
6060 /* Something went wrong in the parse.
6061 * Pretend it didn't happen */
6062 bb_error_msg("bug in redirect parse");
6063 continue;
6064 }
6065 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006066 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006067 openfd = open_or_warn(p, mode);
6068 free(p);
6069 if (openfd < 0) {
6070 /* this could get lost if stderr has been redirected, but
6071 * bash and ash both lose it as well (though zsh doesn't!) */
6072//what the above comment tries to say?
6073 return 1;
6074 }
6075 } else {
6076 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6077 openfd = redir->rd_dup;
6078 }
6079
6080 if (openfd != redir->rd_fd) {
6081 if (squirrel && redir->rd_fd < 3
6082 && squirrel[redir->rd_fd] < 0
6083 ) {
6084 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6085 }
6086 if (openfd == REDIRFD_CLOSE) {
6087 /* "n>-" means "close me" */
6088 close(redir->rd_fd);
6089 } else {
6090 xdup2(openfd, redir->rd_fd);
6091 if (redir->rd_dup == REDIRFD_TO_FILE)
6092 close(openfd);
6093 }
6094 }
6095 }
6096 return 0;
6097}
6098
6099static void restore_redirects(int squirrel[])
6100{
6101 int i, fd;
6102 for (i = 0; i < 3; i++) {
6103 fd = squirrel[i];
6104 if (fd != -1) {
6105 /* We simply die on error */
6106 xmove_fd(fd, i);
6107 }
6108 }
6109}
6110
6111static char *find_in_path(const char *arg)
6112{
6113 char *ret = NULL;
6114 const char *PATH = get_local_var_value("PATH");
6115
6116 if (!PATH)
6117 return NULL;
6118
6119 while (1) {
6120 const char *end = strchrnul(PATH, ':');
6121 int sz = end - PATH; /* must be int! */
6122
6123 free(ret);
6124 if (sz != 0) {
6125 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6126 } else {
6127 /* We have xxx::yyyy in $PATH,
6128 * it means "use current dir" */
6129 ret = xstrdup(arg);
6130 }
6131 if (access(ret, F_OK) == 0)
6132 break;
6133
6134 if (*end == '\0') {
6135 free(ret);
6136 return NULL;
6137 }
6138 PATH = end + 1;
6139 }
6140
6141 return ret;
6142}
6143
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006144static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006145 const struct built_in_command *x,
6146 const struct built_in_command *end)
6147{
6148 while (x != end) {
6149 if (strcmp(name, x->b_cmd) != 0) {
6150 x++;
6151 continue;
6152 }
6153 debug_printf_exec("found builtin '%s'\n", name);
6154 return x;
6155 }
6156 return NULL;
6157}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006158static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006159{
6160 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6161}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006162static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006163{
6164 const struct built_in_command *x = find_builtin1(name);
6165 if (x)
6166 return x;
6167 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6168}
6169
6170#if ENABLE_HUSH_FUNCTIONS
6171static struct function **find_function_slot(const char *name)
6172{
6173 struct function **funcpp = &G.top_func;
6174 while (*funcpp) {
6175 if (strcmp(name, (*funcpp)->name) == 0) {
6176 break;
6177 }
6178 funcpp = &(*funcpp)->next;
6179 }
6180 return funcpp;
6181}
6182
6183static const struct function *find_function(const char *name)
6184{
6185 const struct function *funcp = *find_function_slot(name);
6186 if (funcp)
6187 debug_printf_exec("found function '%s'\n", name);
6188 return funcp;
6189}
6190
6191/* Note: takes ownership on name ptr */
6192static struct function *new_function(char *name)
6193{
6194 struct function **funcpp = find_function_slot(name);
6195 struct function *funcp = *funcpp;
6196
6197 if (funcp != NULL) {
6198 struct command *cmd = funcp->parent_cmd;
6199 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6200 if (!cmd) {
6201 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6202 free(funcp->name);
6203 /* Note: if !funcp->body, do not free body_as_string!
6204 * This is a special case of "-F name body" function:
6205 * body_as_string was not malloced! */
6206 if (funcp->body) {
6207 free_pipe_list(funcp->body);
6208# if !BB_MMU
6209 free(funcp->body_as_string);
6210# endif
6211 }
6212 } else {
6213 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6214 cmd->argv[0] = funcp->name;
6215 cmd->group = funcp->body;
6216# if !BB_MMU
6217 cmd->group_as_string = funcp->body_as_string;
6218# endif
6219 }
6220 } else {
6221 debug_printf_exec("remembering new function '%s'\n", name);
6222 funcp = *funcpp = xzalloc(sizeof(*funcp));
6223 /*funcp->next = NULL;*/
6224 }
6225
6226 funcp->name = name;
6227 return funcp;
6228}
6229
6230static void unset_func(const char *name)
6231{
6232 struct function **funcpp = find_function_slot(name);
6233 struct function *funcp = *funcpp;
6234
6235 if (funcp != NULL) {
6236 debug_printf_exec("freeing function '%s'\n", funcp->name);
6237 *funcpp = funcp->next;
6238 /* funcp is unlinked now, deleting it.
6239 * Note: if !funcp->body, the function was created by
6240 * "-F name body", do not free ->body_as_string
6241 * and ->name as they were not malloced. */
6242 if (funcp->body) {
6243 free_pipe_list(funcp->body);
6244 free(funcp->name);
6245# if !BB_MMU
6246 free(funcp->body_as_string);
6247# endif
6248 }
6249 free(funcp);
6250 }
6251}
6252
6253# if BB_MMU
6254#define exec_function(to_free, funcp, argv) \
6255 exec_function(funcp, argv)
6256# endif
6257static void exec_function(char ***to_free,
6258 const struct function *funcp,
6259 char **argv) NORETURN;
6260static void exec_function(char ***to_free,
6261 const struct function *funcp,
6262 char **argv)
6263{
6264# if BB_MMU
6265 int n = 1;
6266
6267 argv[0] = G.global_argv[0];
6268 G.global_argv = argv;
6269 while (*++argv)
6270 n++;
6271 G.global_argc = n;
6272 /* On MMU, funcp->body is always non-NULL */
6273 n = run_list(funcp->body);
6274 fflush_all();
6275 _exit(n);
6276# else
6277 re_execute_shell(to_free,
6278 funcp->body_as_string,
6279 G.global_argv[0],
6280 argv + 1,
6281 NULL);
6282# endif
6283}
6284
6285static int run_function(const struct function *funcp, char **argv)
6286{
6287 int rc;
6288 save_arg_t sv;
6289 smallint sv_flg;
6290
6291 save_and_replace_G_args(&sv, argv);
6292
6293 /* "we are in function, ok to use return" */
6294 sv_flg = G.flag_return_in_progress;
6295 G.flag_return_in_progress = -1;
6296# if ENABLE_HUSH_LOCAL
6297 G.func_nest_level++;
6298# endif
6299
6300 /* On MMU, funcp->body is always non-NULL */
6301# if !BB_MMU
6302 if (!funcp->body) {
6303 /* Function defined by -F */
6304 parse_and_run_string(funcp->body_as_string);
6305 rc = G.last_exitcode;
6306 } else
6307# endif
6308 {
6309 rc = run_list(funcp->body);
6310 }
6311
6312# if ENABLE_HUSH_LOCAL
6313 {
6314 struct variable *var;
6315 struct variable **var_pp;
6316
6317 var_pp = &G.top_var;
6318 while ((var = *var_pp) != NULL) {
6319 if (var->func_nest_level < G.func_nest_level) {
6320 var_pp = &var->next;
6321 continue;
6322 }
6323 /* Unexport */
6324 if (var->flg_export)
6325 bb_unsetenv(var->varstr);
6326 /* Remove from global list */
6327 *var_pp = var->next;
6328 /* Free */
6329 if (!var->max_len)
6330 free(var->varstr);
6331 free(var);
6332 }
6333 G.func_nest_level--;
6334 }
6335# endif
6336 G.flag_return_in_progress = sv_flg;
6337
6338 restore_G_args(&sv, argv);
6339
6340 return rc;
6341}
6342#endif /* ENABLE_HUSH_FUNCTIONS */
6343
6344
6345#if BB_MMU
6346#define exec_builtin(to_free, x, argv) \
6347 exec_builtin(x, argv)
6348#else
6349#define exec_builtin(to_free, x, argv) \
6350 exec_builtin(to_free, argv)
6351#endif
6352static void exec_builtin(char ***to_free,
6353 const struct built_in_command *x,
6354 char **argv) NORETURN;
6355static void exec_builtin(char ***to_free,
6356 const struct built_in_command *x,
6357 char **argv)
6358{
6359#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006360 int rcode;
6361 fflush_all();
6362 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006363 fflush_all();
6364 _exit(rcode);
6365#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006366 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006367 /* On NOMMU, we must never block!
6368 * Example: { sleep 99 | read line; } & echo Ok
6369 */
6370 re_execute_shell(to_free,
6371 argv[0],
6372 G.global_argv[0],
6373 G.global_argv + 1,
6374 argv);
6375#endif
6376}
6377
6378
6379static void execvp_or_die(char **argv) NORETURN;
6380static void execvp_or_die(char **argv)
6381{
6382 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006383 /* Don't propagate SIG_IGN to the child */
6384 if (SPECIAL_JOBSTOP_SIGS != 0)
6385 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006386 execvp(argv[0], argv);
6387 bb_perror_msg("can't execute '%s'", argv[0]);
6388 _exit(127); /* bash compat */
6389}
6390
6391#if ENABLE_HUSH_MODE_X
6392static void dump_cmd_in_x_mode(char **argv)
6393{
6394 if (G_x_mode && argv) {
6395 /* We want to output the line in one write op */
6396 char *buf, *p;
6397 int len;
6398 int n;
6399
6400 len = 3;
6401 n = 0;
6402 while (argv[n])
6403 len += strlen(argv[n++]) + 1;
6404 buf = xmalloc(len);
6405 buf[0] = '+';
6406 p = buf + 1;
6407 n = 0;
6408 while (argv[n])
6409 p += sprintf(p, " %s", argv[n++]);
6410 *p++ = '\n';
6411 *p = '\0';
6412 fputs(buf, stderr);
6413 free(buf);
6414 }
6415}
6416#else
6417# define dump_cmd_in_x_mode(argv) ((void)0)
6418#endif
6419
6420#if BB_MMU
6421#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6422 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6423#define pseudo_exec(nommu_save, command, argv_expanded) \
6424 pseudo_exec(command, argv_expanded)
6425#endif
6426
6427/* Called after [v]fork() in run_pipe, or from builtin_exec.
6428 * Never returns.
6429 * Don't exit() here. If you don't exec, use _exit instead.
6430 * The at_exit handlers apparently confuse the calling process,
6431 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6432static void pseudo_exec_argv(nommu_save_t *nommu_save,
6433 char **argv, int assignment_cnt,
6434 char **argv_expanded) NORETURN;
6435static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6436 char **argv, int assignment_cnt,
6437 char **argv_expanded)
6438{
6439 char **new_env;
6440
6441 new_env = expand_assignments(argv, assignment_cnt);
6442 dump_cmd_in_x_mode(new_env);
6443
6444 if (!argv[assignment_cnt]) {
6445 /* Case when we are here: ... | var=val | ...
6446 * (note that we do not exit early, i.e., do not optimize out
6447 * expand_assignments(): think about ... | var=`sleep 1` | ...
6448 */
6449 free_strings(new_env);
6450 _exit(EXIT_SUCCESS);
6451 }
6452
6453#if BB_MMU
6454 set_vars_and_save_old(new_env);
6455 free(new_env); /* optional */
6456 /* we can also destroy set_vars_and_save_old's return value,
6457 * to save memory */
6458#else
6459 nommu_save->new_env = new_env;
6460 nommu_save->old_vars = set_vars_and_save_old(new_env);
6461#endif
6462
6463 if (argv_expanded) {
6464 argv = argv_expanded;
6465 } else {
6466 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6467#if !BB_MMU
6468 nommu_save->argv = argv;
6469#endif
6470 }
6471 dump_cmd_in_x_mode(argv);
6472
6473#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6474 if (strchr(argv[0], '/') != NULL)
6475 goto skip;
6476#endif
6477
6478 /* Check if the command matches any of the builtins.
6479 * Depending on context, this might be redundant. But it's
6480 * easier to waste a few CPU cycles than it is to figure out
6481 * if this is one of those cases.
6482 */
6483 {
6484 /* On NOMMU, it is more expensive to re-execute shell
6485 * just in order to run echo or test builtin.
6486 * It's better to skip it here and run corresponding
6487 * non-builtin later. */
6488 const struct built_in_command *x;
6489 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6490 if (x) {
6491 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6492 }
6493 }
6494#if ENABLE_HUSH_FUNCTIONS
6495 /* Check if the command matches any functions */
6496 {
6497 const struct function *funcp = find_function(argv[0]);
6498 if (funcp) {
6499 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6500 }
6501 }
6502#endif
6503
6504#if ENABLE_FEATURE_SH_STANDALONE
6505 /* Check if the command matches any busybox applets */
6506 {
6507 int a = find_applet_by_name(argv[0]);
6508 if (a >= 0) {
6509# if BB_MMU /* see above why on NOMMU it is not allowed */
6510 if (APPLET_IS_NOEXEC(a)) {
6511 debug_printf_exec("running applet '%s'\n", argv[0]);
6512 run_applet_no_and_exit(a, argv);
6513 }
6514# endif
6515 /* Re-exec ourselves */
6516 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006517 /* Don't propagate SIG_IGN to the child */
6518 if (SPECIAL_JOBSTOP_SIGS != 0)
6519 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006520 execv(bb_busybox_exec_path, argv);
6521 /* If they called chroot or otherwise made the binary no longer
6522 * executable, fall through */
6523 }
6524 }
6525#endif
6526
6527#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6528 skip:
6529#endif
6530 execvp_or_die(argv);
6531}
6532
6533/* Called after [v]fork() in run_pipe
6534 */
6535static void pseudo_exec(nommu_save_t *nommu_save,
6536 struct command *command,
6537 char **argv_expanded) NORETURN;
6538static void pseudo_exec(nommu_save_t *nommu_save,
6539 struct command *command,
6540 char **argv_expanded)
6541{
6542 if (command->argv) {
6543 pseudo_exec_argv(nommu_save, command->argv,
6544 command->assignment_cnt, argv_expanded);
6545 }
6546
6547 if (command->group) {
6548 /* Cases when we are here:
6549 * ( list )
6550 * { list } &
6551 * ... | ( list ) | ...
6552 * ... | { list } | ...
6553 */
6554#if BB_MMU
6555 int rcode;
6556 debug_printf_exec("pseudo_exec: run_list\n");
6557 reset_traps_to_defaults();
6558 rcode = run_list(command->group);
6559 /* OK to leak memory by not calling free_pipe_list,
6560 * since this process is about to exit */
6561 _exit(rcode);
6562#else
6563 re_execute_shell(&nommu_save->argv_from_re_execing,
6564 command->group_as_string,
6565 G.global_argv[0],
6566 G.global_argv + 1,
6567 NULL);
6568#endif
6569 }
6570
6571 /* Case when we are here: ... | >file */
6572 debug_printf_exec("pseudo_exec'ed null command\n");
6573 _exit(EXIT_SUCCESS);
6574}
6575
6576#if ENABLE_HUSH_JOB
6577static const char *get_cmdtext(struct pipe *pi)
6578{
6579 char **argv;
6580 char *p;
6581 int len;
6582
6583 /* This is subtle. ->cmdtext is created only on first backgrounding.
6584 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6585 * On subsequent bg argv is trashed, but we won't use it */
6586 if (pi->cmdtext)
6587 return pi->cmdtext;
6588 argv = pi->cmds[0].argv;
6589 if (!argv || !argv[0]) {
6590 pi->cmdtext = xzalloc(1);
6591 return pi->cmdtext;
6592 }
6593
6594 len = 0;
6595 do {
6596 len += strlen(*argv) + 1;
6597 } while (*++argv);
6598 p = xmalloc(len);
6599 pi->cmdtext = p;
6600 argv = pi->cmds[0].argv;
6601 do {
6602 len = strlen(*argv);
6603 memcpy(p, *argv, len);
6604 p += len;
6605 *p++ = ' ';
6606 } while (*++argv);
6607 p[-1] = '\0';
6608 return pi->cmdtext;
6609}
6610
6611static void insert_bg_job(struct pipe *pi)
6612{
6613 struct pipe *job, **jobp;
6614 int i;
6615
6616 /* Linear search for the ID of the job to use */
6617 pi->jobid = 1;
6618 for (job = G.job_list; job; job = job->next)
6619 if (job->jobid >= pi->jobid)
6620 pi->jobid = job->jobid + 1;
6621
6622 /* Add job to the list of running jobs */
6623 jobp = &G.job_list;
6624 while ((job = *jobp) != NULL)
6625 jobp = &job->next;
6626 job = *jobp = xmalloc(sizeof(*job));
6627
6628 *job = *pi; /* physical copy */
6629 job->next = NULL;
6630 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6631 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6632 for (i = 0; i < pi->num_cmds; i++) {
6633 job->cmds[i].pid = pi->cmds[i].pid;
6634 /* all other fields are not used and stay zero */
6635 }
6636 job->cmdtext = xstrdup(get_cmdtext(pi));
6637
6638 if (G_interactive_fd)
6639 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6640 G.last_jobid = job->jobid;
6641}
6642
6643static void remove_bg_job(struct pipe *pi)
6644{
6645 struct pipe *prev_pipe;
6646
6647 if (pi == G.job_list) {
6648 G.job_list = pi->next;
6649 } else {
6650 prev_pipe = G.job_list;
6651 while (prev_pipe->next != pi)
6652 prev_pipe = prev_pipe->next;
6653 prev_pipe->next = pi->next;
6654 }
6655 if (G.job_list)
6656 G.last_jobid = G.job_list->jobid;
6657 else
6658 G.last_jobid = 0;
6659}
6660
6661/* Remove a backgrounded job */
6662static void delete_finished_bg_job(struct pipe *pi)
6663{
6664 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006665 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006666}
6667#endif /* JOB */
6668
6669/* Check to see if any processes have exited -- if they
6670 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006671static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006672{
6673 int attributes;
6674 int status;
6675#if ENABLE_HUSH_JOB
6676 struct pipe *pi;
6677#endif
6678 pid_t childpid;
6679 int rcode = 0;
6680
6681 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6682
6683 attributes = WUNTRACED;
6684 if (fg_pipe == NULL)
6685 attributes |= WNOHANG;
6686
6687 errno = 0;
6688#if ENABLE_HUSH_FAST
6689 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6690//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6691//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6692 /* There was neither fork nor SIGCHLD since last waitpid */
6693 /* Avoid doing waitpid syscall if possible */
6694 if (!G.we_have_children) {
6695 errno = ECHILD;
6696 return -1;
6697 }
6698 if (fg_pipe == NULL) { /* is WNOHANG set? */
6699 /* We have children, but they did not exit
6700 * or stop yet (we saw no SIGCHLD) */
6701 return 0;
6702 }
6703 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6704 }
6705#endif
6706
6707/* Do we do this right?
6708 * bash-3.00# sleep 20 | false
6709 * <ctrl-Z pressed>
6710 * [3]+ Stopped sleep 20 | false
6711 * bash-3.00# echo $?
6712 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6713 * [hush 1.14.0: yes we do it right]
6714 */
6715 wait_more:
6716 while (1) {
6717 int i;
6718 int dead;
6719
6720#if ENABLE_HUSH_FAST
6721 i = G.count_SIGCHLD;
6722#endif
6723 childpid = waitpid(-1, &status, attributes);
6724 if (childpid <= 0) {
6725 if (childpid && errno != ECHILD)
6726 bb_perror_msg("waitpid");
6727#if ENABLE_HUSH_FAST
6728 else { /* Until next SIGCHLD, waitpid's are useless */
6729 G.we_have_children = (childpid == 0);
6730 G.handled_SIGCHLD = i;
6731//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6732 }
6733#endif
6734 break;
6735 }
6736 dead = WIFEXITED(status) || WIFSIGNALED(status);
6737
6738#if DEBUG_JOBS
6739 if (WIFSTOPPED(status))
6740 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6741 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6742 if (WIFSIGNALED(status))
6743 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6744 childpid, WTERMSIG(status), WEXITSTATUS(status));
6745 if (WIFEXITED(status))
6746 debug_printf_jobs("pid %d exited, exitcode %d\n",
6747 childpid, WEXITSTATUS(status));
6748#endif
6749 /* Were we asked to wait for fg pipe? */
6750 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006751 i = fg_pipe->num_cmds;
6752 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006753 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6754 if (fg_pipe->cmds[i].pid != childpid)
6755 continue;
6756 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006757 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006758 fg_pipe->cmds[i].pid = 0;
6759 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006760 ex = WEXITSTATUS(status);
6761 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006762 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006763 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6764 */
6765 if (WIFSIGNALED(status)) {
6766 int sig = WTERMSIG(status);
6767 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006768 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6769 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6770 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006771 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6772 * Maybe we need to use sig | 128? */
6773 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006774 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006775 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006776 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006777 fg_pipe->stopped_cmds++;
6778 }
6779 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6780 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006781 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006782 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006783 i = fg_pipe->num_cmds;
6784 while (--i >= 0) {
6785 rcode = fg_pipe->cmds[i].cmd_exitcode;
6786 /* usually last process gives overall exitstatus,
6787 * but with "set -o pipefail", last *failed* process does */
6788 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6789 break;
6790 }
6791 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006792/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6793 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6794 * and "killall -STOP cat" */
6795 if (G_interactive_fd) {
6796#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006797 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006798 insert_bg_job(fg_pipe);
6799#endif
6800 return rcode;
6801 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006802 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006803 return rcode;
6804 }
6805 /* There are still running processes in the fg pipe */
6806 goto wait_more; /* do waitpid again */
6807 }
6808 /* it wasnt fg_pipe, look for process in bg pipes */
6809 }
6810
6811#if ENABLE_HUSH_JOB
6812 /* We asked to wait for bg or orphaned children */
6813 /* No need to remember exitcode in this case */
6814 for (pi = G.job_list; pi; pi = pi->next) {
6815 for (i = 0; i < pi->num_cmds; i++) {
6816 if (pi->cmds[i].pid == childpid)
6817 goto found_pi_and_prognum;
6818 }
6819 }
6820 /* Happens when shell is used as init process (init=/bin/sh) */
6821 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6822 continue; /* do waitpid again */
6823
6824 found_pi_and_prognum:
6825 if (dead) {
6826 /* child exited */
6827 pi->cmds[i].pid = 0;
6828 pi->alive_cmds--;
6829 if (!pi->alive_cmds) {
6830 if (G_interactive_fd)
6831 printf(JOB_STATUS_FORMAT, pi->jobid,
6832 "Done", pi->cmdtext);
6833 delete_finished_bg_job(pi);
6834 }
6835 } else {
6836 /* child stopped */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006837 pi->stopped_cmds++;
6838 }
6839#endif
6840 } /* while (waitpid succeeds)... */
6841
6842 return rcode;
6843}
6844
6845#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006846static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006847{
6848 pid_t p;
6849 int rcode = checkjobs(fg_pipe);
6850 if (G_saved_tty_pgrp) {
6851 /* Job finished, move the shell to the foreground */
6852 p = getpgrp(); /* our process group id */
6853 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6854 tcsetpgrp(G_interactive_fd, p);
6855 }
6856 return rcode;
6857}
6858#endif
6859
6860/* Start all the jobs, but don't wait for anything to finish.
6861 * See checkjobs().
6862 *
6863 * Return code is normally -1, when the caller has to wait for children
6864 * to finish to determine the exit status of the pipe. If the pipe
6865 * is a simple builtin command, however, the action is done by the
6866 * time run_pipe returns, and the exit code is provided as the
6867 * return value.
6868 *
6869 * Returns -1 only if started some children. IOW: we have to
6870 * mask out retvals of builtins etc with 0xff!
6871 *
6872 * The only case when we do not need to [v]fork is when the pipe
6873 * is single, non-backgrounded, non-subshell command. Examples:
6874 * cmd ; ... { list } ; ...
6875 * cmd && ... { list } && ...
6876 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006877 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006878 * or (if SH_STANDALONE) an applet, and we can run the { list }
6879 * with run_list. If it isn't one of these, we fork and exec cmd.
6880 *
6881 * Cases when we must fork:
6882 * non-single: cmd | cmd
6883 * backgrounded: cmd & { list } &
6884 * subshell: ( list ) [&]
6885 */
6886#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006887#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006888 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6889#endif
6890static int redirect_and_varexp_helper(char ***new_env_p,
6891 struct variable **old_vars_p,
6892 struct command *command,
6893 int squirrel[3],
6894 char **argv_expanded)
6895{
6896 /* setup_redirects acts on file descriptors, not FILEs.
6897 * This is perfect for work that comes after exec().
6898 * Is it really safe for inline use? Experimentally,
6899 * things seem to work. */
6900 int rcode = setup_redirects(command, squirrel);
6901 if (rcode == 0) {
6902 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6903 *new_env_p = new_env;
6904 dump_cmd_in_x_mode(new_env);
6905 dump_cmd_in_x_mode(argv_expanded);
6906 if (old_vars_p)
6907 *old_vars_p = set_vars_and_save_old(new_env);
6908 }
6909 return rcode;
6910}
6911static NOINLINE int run_pipe(struct pipe *pi)
6912{
6913 static const char *const null_ptr = NULL;
6914
6915 int cmd_no;
6916 int next_infd;
6917 struct command *command;
6918 char **argv_expanded;
6919 char **argv;
6920 /* it is not always needed, but we aim to smaller code */
6921 int squirrel[] = { -1, -1, -1 };
6922 int rcode;
6923
6924 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6925 debug_enter();
6926
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006927 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6928 * Result should be 3 lines: q w e, qwe, q w e
6929 */
6930 G.ifs = get_local_var_value("IFS");
6931 if (!G.ifs)
6932 G.ifs = defifs;
6933
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006934 IF_HUSH_JOB(pi->pgrp = -1;)
6935 pi->stopped_cmds = 0;
6936 command = &pi->cmds[0];
6937 argv_expanded = NULL;
6938
6939 if (pi->num_cmds != 1
6940 || pi->followup == PIPE_BG
6941 || command->cmd_type == CMD_SUBSHELL
6942 ) {
6943 goto must_fork;
6944 }
6945
6946 pi->alive_cmds = 1;
6947
6948 debug_printf_exec(": group:%p argv:'%s'\n",
6949 command->group, command->argv ? command->argv[0] : "NONE");
6950
6951 if (command->group) {
6952#if ENABLE_HUSH_FUNCTIONS
6953 if (command->cmd_type == CMD_FUNCDEF) {
6954 /* "executing" func () { list } */
6955 struct function *funcp;
6956
6957 funcp = new_function(command->argv[0]);
6958 /* funcp->name is already set to argv[0] */
6959 funcp->body = command->group;
6960# if !BB_MMU
6961 funcp->body_as_string = command->group_as_string;
6962 command->group_as_string = NULL;
6963# endif
6964 command->group = NULL;
6965 command->argv[0] = NULL;
6966 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6967 funcp->parent_cmd = command;
6968 command->child_func = funcp;
6969
6970 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6971 debug_leave();
6972 return EXIT_SUCCESS;
6973 }
6974#endif
6975 /* { list } */
6976 debug_printf("non-subshell group\n");
6977 rcode = 1; /* exitcode if redir failed */
6978 if (setup_redirects(command, squirrel) == 0) {
6979 debug_printf_exec(": run_list\n");
6980 rcode = run_list(command->group) & 0xff;
6981 }
6982 restore_redirects(squirrel);
6983 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6984 debug_leave();
6985 debug_printf_exec("run_pipe: return %d\n", rcode);
6986 return rcode;
6987 }
6988
6989 argv = command->argv ? command->argv : (char **) &null_ptr;
6990 {
6991 const struct built_in_command *x;
6992#if ENABLE_HUSH_FUNCTIONS
6993 const struct function *funcp;
6994#else
6995 enum { funcp = 0 };
6996#endif
6997 char **new_env = NULL;
6998 struct variable *old_vars = NULL;
6999
7000 if (argv[command->assignment_cnt] == NULL) {
7001 /* Assignments, but no command */
7002 /* Ensure redirects take effect (that is, create files).
7003 * Try "a=t >file" */
7004#if 0 /* A few cases in testsuite fail with this code. FIXME */
7005 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7006 /* Set shell variables */
7007 if (new_env) {
7008 argv = new_env;
7009 while (*argv) {
7010 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7011 /* Do we need to flag set_local_var() errors?
7012 * "assignment to readonly var" and "putenv error"
7013 */
7014 argv++;
7015 }
7016 }
7017 /* Redirect error sets $? to 1. Otherwise,
7018 * if evaluating assignment value set $?, retain it.
7019 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7020 if (rcode == 0)
7021 rcode = G.last_exitcode;
7022 /* Exit, _skipping_ variable restoring code: */
7023 goto clean_up_and_ret0;
7024
7025#else /* Older, bigger, but more correct code */
7026
7027 rcode = setup_redirects(command, squirrel);
7028 restore_redirects(squirrel);
7029 /* Set shell variables */
7030 if (G_x_mode)
7031 bb_putchar_stderr('+');
7032 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007033 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007034 if (G_x_mode)
7035 fprintf(stderr, " %s", p);
7036 debug_printf_exec("set shell var:'%s'->'%s'\n",
7037 *argv, p);
7038 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7039 /* Do we need to flag set_local_var() errors?
7040 * "assignment to readonly var" and "putenv error"
7041 */
7042 argv++;
7043 }
7044 if (G_x_mode)
7045 bb_putchar_stderr('\n');
7046 /* Redirect error sets $? to 1. Otherwise,
7047 * if evaluating assignment value set $?, retain it.
7048 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7049 if (rcode == 0)
7050 rcode = G.last_exitcode;
7051 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7052 debug_leave();
7053 debug_printf_exec("run_pipe: return %d\n", rcode);
7054 return rcode;
7055#endif
7056 }
7057
7058 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007059#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007060 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007061 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007062 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007063#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007064 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007065 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7066 }
7067
7068 /* if someone gives us an empty string: `cmd with empty output` */
7069 if (!argv_expanded[0]) {
7070 free(argv_expanded);
7071 debug_leave();
7072 return G.last_exitcode;
7073 }
7074
7075 x = find_builtin(argv_expanded[0]);
7076#if ENABLE_HUSH_FUNCTIONS
7077 funcp = NULL;
7078 if (!x)
7079 funcp = find_function(argv_expanded[0]);
7080#endif
7081 if (x || funcp) {
7082 if (!funcp) {
7083 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7084 debug_printf("exec with redirects only\n");
7085 rcode = setup_redirects(command, NULL);
7086 goto clean_up_and_ret1;
7087 }
7088 }
7089 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7090 if (rcode == 0) {
7091 if (!funcp) {
7092 debug_printf_exec(": builtin '%s' '%s'...\n",
7093 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007094 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007095 rcode = x->b_function(argv_expanded) & 0xff;
7096 fflush_all();
7097 }
7098#if ENABLE_HUSH_FUNCTIONS
7099 else {
7100# if ENABLE_HUSH_LOCAL
7101 struct variable **sv;
7102 sv = G.shadowed_vars_pp;
7103 G.shadowed_vars_pp = &old_vars;
7104# endif
7105 debug_printf_exec(": function '%s' '%s'...\n",
7106 funcp->name, argv_expanded[1]);
7107 rcode = run_function(funcp, argv_expanded) & 0xff;
7108# if ENABLE_HUSH_LOCAL
7109 G.shadowed_vars_pp = sv;
7110# endif
7111 }
7112#endif
7113 }
7114 clean_up_and_ret:
7115 unset_vars(new_env);
7116 add_vars(old_vars);
7117/* clean_up_and_ret0: */
7118 restore_redirects(squirrel);
7119 clean_up_and_ret1:
7120 free(argv_expanded);
7121 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7122 debug_leave();
7123 debug_printf_exec("run_pipe return %d\n", rcode);
7124 return rcode;
7125 }
7126
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007127 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007128 int n = find_applet_by_name(argv_expanded[0]);
7129 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7130 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7131 if (rcode == 0) {
7132 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7133 argv_expanded[0], argv_expanded[1]);
7134 rcode = run_nofork_applet(n, argv_expanded);
7135 }
7136 goto clean_up_and_ret;
7137 }
7138 }
7139 /* It is neither builtin nor applet. We must fork. */
7140 }
7141
7142 must_fork:
7143 /* NB: argv_expanded may already be created, and that
7144 * might include `cmd` runs! Do not rerun it! We *must*
7145 * use argv_expanded if it's non-NULL */
7146
7147 /* Going to fork a child per each pipe member */
7148 pi->alive_cmds = 0;
7149 next_infd = 0;
7150
7151 cmd_no = 0;
7152 while (cmd_no < pi->num_cmds) {
7153 struct fd_pair pipefds;
7154#if !BB_MMU
7155 volatile nommu_save_t nommu_save;
7156 nommu_save.new_env = NULL;
7157 nommu_save.old_vars = NULL;
7158 nommu_save.argv = NULL;
7159 nommu_save.argv_from_re_execing = NULL;
7160#endif
7161 command = &pi->cmds[cmd_no];
7162 cmd_no++;
7163 if (command->argv) {
7164 debug_printf_exec(": pipe member '%s' '%s'...\n",
7165 command->argv[0], command->argv[1]);
7166 } else {
7167 debug_printf_exec(": pipe member with no argv\n");
7168 }
7169
7170 /* pipes are inserted between pairs of commands */
7171 pipefds.rd = 0;
7172 pipefds.wr = 1;
7173 if (cmd_no < pi->num_cmds)
7174 xpiped_pair(pipefds);
7175
7176 command->pid = BB_MMU ? fork() : vfork();
7177 if (!command->pid) { /* child */
7178#if ENABLE_HUSH_JOB
7179 disable_restore_tty_pgrp_on_exit();
7180 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7181
7182 /* Every child adds itself to new process group
7183 * with pgid == pid_of_first_child_in_pipe */
7184 if (G.run_list_level == 1 && G_interactive_fd) {
7185 pid_t pgrp;
7186 pgrp = pi->pgrp;
7187 if (pgrp < 0) /* true for 1st process only */
7188 pgrp = getpid();
7189 if (setpgid(0, pgrp) == 0
7190 && pi->followup != PIPE_BG
7191 && G_saved_tty_pgrp /* we have ctty */
7192 ) {
7193 /* We do it in *every* child, not just first,
7194 * to avoid races */
7195 tcsetpgrp(G_interactive_fd, pgrp);
7196 }
7197 }
7198#endif
7199 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7200 /* 1st cmd in backgrounded pipe
7201 * should have its stdin /dev/null'ed */
7202 close(0);
7203 if (open(bb_dev_null, O_RDONLY))
7204 xopen("/", O_RDONLY);
7205 } else {
7206 xmove_fd(next_infd, 0);
7207 }
7208 xmove_fd(pipefds.wr, 1);
7209 if (pipefds.rd > 1)
7210 close(pipefds.rd);
7211 /* Like bash, explicit redirects override pipes,
7212 * and the pipe fd is available for dup'ing. */
7213 if (setup_redirects(command, NULL))
7214 _exit(1);
7215
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007216 /* Stores to nommu_save list of env vars putenv'ed
7217 * (NOMMU, on MMU we don't need that) */
7218 /* cast away volatility... */
7219 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7220 /* pseudo_exec() does not return */
7221 }
7222
7223 /* parent or error */
7224#if ENABLE_HUSH_FAST
7225 G.count_SIGCHLD++;
7226//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7227#endif
7228 enable_restore_tty_pgrp_on_exit();
7229#if !BB_MMU
7230 /* Clean up after vforked child */
7231 free(nommu_save.argv);
7232 free(nommu_save.argv_from_re_execing);
7233 unset_vars(nommu_save.new_env);
7234 add_vars(nommu_save.old_vars);
7235#endif
7236 free(argv_expanded);
7237 argv_expanded = NULL;
7238 if (command->pid < 0) { /* [v]fork failed */
7239 /* Clearly indicate, was it fork or vfork */
7240 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7241 } else {
7242 pi->alive_cmds++;
7243#if ENABLE_HUSH_JOB
7244 /* Second and next children need to know pid of first one */
7245 if (pi->pgrp < 0)
7246 pi->pgrp = command->pid;
7247#endif
7248 }
7249
7250 if (cmd_no > 1)
7251 close(next_infd);
7252 if (cmd_no < pi->num_cmds)
7253 close(pipefds.wr);
7254 /* Pass read (output) pipe end to next iteration */
7255 next_infd = pipefds.rd;
7256 }
7257
7258 if (!pi->alive_cmds) {
7259 debug_leave();
7260 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7261 return 1;
7262 }
7263
7264 debug_leave();
7265 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7266 return -1;
7267}
7268
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007269/* NB: called by pseudo_exec, and therefore must not modify any
7270 * global data until exec/_exit (we can be a child after vfork!) */
7271static int run_list(struct pipe *pi)
7272{
7273#if ENABLE_HUSH_CASE
7274 char *case_word = NULL;
7275#endif
7276#if ENABLE_HUSH_LOOPS
7277 struct pipe *loop_top = NULL;
7278 char **for_lcur = NULL;
7279 char **for_list = NULL;
7280#endif
7281 smallint last_followup;
7282 smalluint rcode;
7283#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7284 smalluint cond_code = 0;
7285#else
7286 enum { cond_code = 0 };
7287#endif
7288#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007289 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007290 smallint last_rword; /* ditto */
7291#endif
7292
7293 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7294 debug_enter();
7295
7296#if ENABLE_HUSH_LOOPS
7297 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007298 {
7299 struct pipe *cpipe;
7300 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7301 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7302 continue;
7303 /* current word is FOR or IN (BOLD in comments below) */
7304 if (cpipe->next == NULL) {
7305 syntax_error("malformed for");
7306 debug_leave();
7307 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7308 return 1;
7309 }
7310 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7311 if (cpipe->next->res_word == RES_DO)
7312 continue;
7313 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7314 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7315 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7316 ) {
7317 syntax_error("malformed for");
7318 debug_leave();
7319 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7320 return 1;
7321 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007322 }
7323 }
7324#endif
7325
7326 /* Past this point, all code paths should jump to ret: label
7327 * in order to return, no direct "return" statements please.
7328 * This helps to ensure that no memory is leaked. */
7329
7330#if ENABLE_HUSH_JOB
7331 G.run_list_level++;
7332#endif
7333
7334#if HAS_KEYWORDS
7335 rword = RES_NONE;
7336 last_rword = RES_XXXX;
7337#endif
7338 last_followup = PIPE_SEQ;
7339 rcode = G.last_exitcode;
7340
7341 /* Go through list of pipes, (maybe) executing them. */
7342 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7343 if (G.flag_SIGINT)
7344 break;
7345
7346 IF_HAS_KEYWORDS(rword = pi->res_word;)
7347 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7348 rword, cond_code, last_rword);
7349#if ENABLE_HUSH_LOOPS
7350 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7351 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7352 ) {
7353 /* start of a loop: remember where loop starts */
7354 loop_top = pi;
7355 G.depth_of_loop++;
7356 }
7357#endif
7358 /* Still in the same "if...", "then..." or "do..." branch? */
7359 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7360 if ((rcode == 0 && last_followup == PIPE_OR)
7361 || (rcode != 0 && last_followup == PIPE_AND)
7362 ) {
7363 /* It is "<true> || CMD" or "<false> && CMD"
7364 * and we should not execute CMD */
7365 debug_printf_exec("skipped cmd because of || or &&\n");
7366 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02007367 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007368 }
7369 }
7370 last_followup = pi->followup;
7371 IF_HAS_KEYWORDS(last_rword = rword;)
7372#if ENABLE_HUSH_IF
7373 if (cond_code) {
7374 if (rword == RES_THEN) {
7375 /* if false; then ... fi has exitcode 0! */
7376 G.last_exitcode = rcode = EXIT_SUCCESS;
7377 /* "if <false> THEN cmd": skip cmd */
7378 continue;
7379 }
7380 } else {
7381 if (rword == RES_ELSE || rword == RES_ELIF) {
7382 /* "if <true> then ... ELSE/ELIF cmd":
7383 * skip cmd and all following ones */
7384 break;
7385 }
7386 }
7387#endif
7388#if ENABLE_HUSH_LOOPS
7389 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7390 if (!for_lcur) {
7391 /* first loop through for */
7392
7393 static const char encoded_dollar_at[] ALIGN1 = {
7394 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7395 }; /* encoded representation of "$@" */
7396 static const char *const encoded_dollar_at_argv[] = {
7397 encoded_dollar_at, NULL
7398 }; /* argv list with one element: "$@" */
7399 char **vals;
7400
7401 vals = (char**)encoded_dollar_at_argv;
7402 if (pi->next->res_word == RES_IN) {
7403 /* if no variable values after "in" we skip "for" */
7404 if (!pi->next->cmds[0].argv) {
7405 G.last_exitcode = rcode = EXIT_SUCCESS;
7406 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7407 break;
7408 }
7409 vals = pi->next->cmds[0].argv;
7410 } /* else: "for var; do..." -> assume "$@" list */
7411 /* create list of variable values */
7412 debug_print_strings("for_list made from", vals);
7413 for_list = expand_strvec_to_strvec(vals);
7414 for_lcur = for_list;
7415 debug_print_strings("for_list", for_list);
7416 }
7417 if (!*for_lcur) {
7418 /* "for" loop is over, clean up */
7419 free(for_list);
7420 for_list = NULL;
7421 for_lcur = NULL;
7422 break;
7423 }
7424 /* Insert next value from for_lcur */
7425 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7426 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7427 continue;
7428 }
7429 if (rword == RES_IN) {
7430 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7431 }
7432 if (rword == RES_DONE) {
7433 continue; /* "done" has no cmds too */
7434 }
7435#endif
7436#if ENABLE_HUSH_CASE
7437 if (rword == RES_CASE) {
7438 case_word = expand_strvec_to_string(pi->cmds->argv);
7439 continue;
7440 }
7441 if (rword == RES_MATCH) {
7442 char **argv;
7443
7444 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7445 break;
7446 /* all prev words didn't match, does this one match? */
7447 argv = pi->cmds->argv;
7448 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007449 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007450 /* TODO: which FNM_xxx flags to use? */
7451 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7452 free(pattern);
7453 if (cond_code == 0) { /* match! we will execute this branch */
7454 free(case_word); /* make future "word)" stop */
7455 case_word = NULL;
7456 break;
7457 }
7458 argv++;
7459 }
7460 continue;
7461 }
7462 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7463 if (cond_code != 0)
7464 continue; /* not matched yet, skip this pipe */
7465 }
7466#endif
7467 /* Just pressing <enter> in shell should check for jobs.
7468 * OTOH, in non-interactive shell this is useless
7469 * and only leads to extra job checks */
7470 if (pi->num_cmds == 0) {
7471 if (G_interactive_fd)
7472 goto check_jobs_and_continue;
7473 continue;
7474 }
7475
7476 /* After analyzing all keywords and conditions, we decided
7477 * to execute this pipe. NB: have to do checkjobs(NULL)
7478 * after run_pipe to collect any background children,
7479 * even if list execution is to be stopped. */
7480 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7481 {
7482 int r;
7483#if ENABLE_HUSH_LOOPS
7484 G.flag_break_continue = 0;
7485#endif
7486 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7487 if (r != -1) {
7488 /* We ran a builtin, function, or group.
7489 * rcode is already known
7490 * and we don't need to wait for anything. */
7491 G.last_exitcode = rcode;
7492 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007493 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007494#if ENABLE_HUSH_LOOPS
7495 /* Was it "break" or "continue"? */
7496 if (G.flag_break_continue) {
7497 smallint fbc = G.flag_break_continue;
7498 /* We might fall into outer *loop*,
7499 * don't want to break it too */
7500 if (loop_top) {
7501 G.depth_break_continue--;
7502 if (G.depth_break_continue == 0)
7503 G.flag_break_continue = 0;
7504 /* else: e.g. "continue 2" should *break* once, *then* continue */
7505 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denys Vlasenko3beab832013-04-07 18:16:58 +02007506 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7507 checkjobs(NULL);
7508 break;
7509 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007510 /* "continue": simulate end of loop */
7511 rword = RES_DONE;
7512 continue;
7513 }
7514#endif
7515#if ENABLE_HUSH_FUNCTIONS
7516 if (G.flag_return_in_progress == 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007517 checkjobs(NULL);
7518 break;
7519 }
7520#endif
7521 } else if (pi->followup == PIPE_BG) {
7522 /* What does bash do with attempts to background builtins? */
7523 /* even bash 3.2 doesn't do that well with nested bg:
7524 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7525 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007526 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007527#if ENABLE_HUSH_JOB
7528 if (G.run_list_level == 1)
7529 insert_bg_job(pi);
7530#endif
7531 /* Last command's pid goes to $! */
7532 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7533 G.last_exitcode = rcode = EXIT_SUCCESS;
7534 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7535 } else {
7536#if ENABLE_HUSH_JOB
7537 if (G.run_list_level == 1 && G_interactive_fd) {
7538 /* Waits for completion, then fg's main shell */
7539 rcode = checkjobs_and_fg_shell(pi);
7540 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007541 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007542 } else
7543#endif
7544 { /* This one just waits for completion */
7545 rcode = checkjobs(pi);
7546 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007547 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007548 }
7549 G.last_exitcode = rcode;
7550 }
7551 }
7552
7553 /* Analyze how result affects subsequent commands */
7554#if ENABLE_HUSH_IF
7555 if (rword == RES_IF || rword == RES_ELIF)
7556 cond_code = rcode;
7557#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02007558 check_jobs_and_continue:
7559 checkjobs(NULL);
7560 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007561#if ENABLE_HUSH_LOOPS
7562 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007563 if (pi->next
7564 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02007565 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007566 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007567 if (rword == RES_WHILE) {
7568 if (rcode) {
7569 /* "while false; do...done" - exitcode 0 */
7570 G.last_exitcode = rcode = EXIT_SUCCESS;
7571 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02007572 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007573 }
7574 }
7575 if (rword == RES_UNTIL) {
7576 if (!rcode) {
7577 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007578 break;
7579 }
7580 }
7581 }
7582#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007583 } /* for (pi) */
7584
7585#if ENABLE_HUSH_JOB
7586 G.run_list_level--;
7587#endif
7588#if ENABLE_HUSH_LOOPS
7589 if (loop_top)
7590 G.depth_of_loop--;
7591 free(for_list);
7592#endif
7593#if ENABLE_HUSH_CASE
7594 free(case_word);
7595#endif
7596 debug_leave();
7597 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7598 return rcode;
7599}
7600
7601/* Select which version we will use */
7602static int run_and_free_list(struct pipe *pi)
7603{
7604 int rcode = 0;
7605 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007606 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007607 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7608 rcode = run_list(pi);
7609 }
7610 /* free_pipe_list has the side effect of clearing memory.
7611 * In the long run that function can be merged with run_list,
7612 * but doing that now would hobble the debugging effort. */
7613 free_pipe_list(pi);
7614 debug_printf_exec("run_and_free_list return %d\n", rcode);
7615 return rcode;
7616}
7617
7618
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007619static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007620{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007621 sighandler_t old_handler;
7622 unsigned sig = 0;
7623 while ((mask >>= 1) != 0) {
7624 sig++;
7625 if (!(mask & 1))
7626 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007627 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007628 /* POSIX allows shell to re-enable SIGCHLD
7629 * even if it was SIG_IGN on entry.
7630 * Therefore we skip IGN check for it:
7631 */
7632 if (sig == SIGCHLD)
7633 continue;
7634 if (old_handler == SIG_IGN) {
7635 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007636 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007637 if (!G.traps)
7638 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7639 free(G.traps[sig]);
7640 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7641 }
7642 }
7643}
7644
7645/* Called a few times only (or even once if "sh -c") */
7646static void install_special_sighandlers(void)
7647{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007648 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007649
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007650 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007651 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007652 if (G_interactive_fd) {
7653 mask |= SPECIAL_INTERACTIVE_SIGS;
7654 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007655 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007656 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007657 /* Careful, do not re-install handlers we already installed */
7658 if (G.special_sig_mask != mask) {
7659 unsigned diff = mask & ~G.special_sig_mask;
7660 G.special_sig_mask = mask;
7661 install_sighandlers(diff);
7662 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007663}
7664
7665#if ENABLE_HUSH_JOB
7666/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007667/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007668static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007669{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007670 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007671
7672 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007673 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007674 + (1 << SIGILL ) * HUSH_DEBUG
7675 + (1 << SIGFPE ) * HUSH_DEBUG
7676 + (1 << SIGBUS ) * HUSH_DEBUG
7677 + (1 << SIGSEGV) * HUSH_DEBUG
7678 + (1 << SIGTRAP) * HUSH_DEBUG
7679 + (1 << SIGABRT)
7680 /* bash 3.2 seems to handle these just like 'fatal' ones */
7681 + (1 << SIGPIPE)
7682 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007683 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007684 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007685 * we never want to restore pgrp on exit, and this fn is not called
7686 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007687 /*+ (1 << SIGHUP )*/
7688 /*+ (1 << SIGTERM)*/
7689 /*+ (1 << SIGINT )*/
7690 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007691 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007692
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007693 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007694}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007695#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007696
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007697static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007698{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007699 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007700 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007701 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007702 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007703 break;
7704 case 'x':
7705 IF_HUSH_MODE_X(G_x_mode = state;)
7706 break;
7707 case 'o':
7708 if (!o_opt) {
7709 /* "set -+o" without parameter.
7710 * in bash, set -o produces this output:
7711 * pipefail off
7712 * and set +o:
7713 * set +o pipefail
7714 * We always use the second form.
7715 */
7716 const char *p = o_opt_strings;
7717 idx = 0;
7718 while (*p) {
7719 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7720 idx++;
7721 p += strlen(p) + 1;
7722 }
7723 break;
7724 }
7725 idx = index_in_strings(o_opt_strings, o_opt);
7726 if (idx >= 0) {
7727 G.o_opt[idx] = state;
7728 break;
7729 }
7730 default:
7731 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007732 }
7733 return EXIT_SUCCESS;
7734}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007735
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007736int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007737int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007738{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007739 enum {
7740 OPT_login = (1 << 0),
7741 };
7742 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00007743 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007744 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007745 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007746 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007747 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007748
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007749 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02007750 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007751 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenko10c01312011-05-11 11:49:21 +02007752#if ENABLE_HUSH_FAST
7753 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7754#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007755#if !BB_MMU
7756 G.argv0_for_re_execing = argv[0];
7757#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007758 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007759 shell_ver = xzalloc(sizeof(*shell_ver));
7760 shell_ver->flg_export = 1;
7761 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007762 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007763 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007764 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007765 /* Create shell local variables from the values
7766 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007767 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007768 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007769 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007770 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007771 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007772 if (e) while (*e) {
7773 char *value = strchr(*e, '=');
7774 if (value) { /* paranoia */
7775 cur_var->next = xzalloc(sizeof(*cur_var));
7776 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007777 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007778 cur_var->max_len = strlen(*e);
7779 cur_var->flg_export = 1;
7780 }
7781 e++;
7782 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007783 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007784 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7785 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007786
7787 /* Export PWD */
7788 set_pwd_var(/*exp:*/ 1);
7789 /* bash also exports SHLVL and _,
7790 * and sets (but doesn't export) the following variables:
7791 * BASH=/bin/bash
7792 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7793 * BASH_VERSION='3.2.0(1)-release'
7794 * HOSTTYPE=i386
7795 * MACHTYPE=i386-pc-linux-gnu
7796 * OSTYPE=linux-gnu
7797 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007798 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007799 * EUID=<NNNNN>
7800 * UID=<NNNNN>
7801 * GROUPS=()
7802 * LINES=<NNN>
7803 * COLUMNS=<NNN>
7804 * BASH_ARGC=()
7805 * BASH_ARGV=()
7806 * BASH_LINENO=()
7807 * BASH_SOURCE=()
7808 * DIRSTACK=()
7809 * PIPESTATUS=([0]="0")
7810 * HISTFILE=/<xxx>/.bash_history
7811 * HISTFILESIZE=500
7812 * HISTSIZE=500
7813 * MAILCHECK=60
7814 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7815 * SHELL=/bin/bash
7816 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7817 * TERM=dumb
7818 * OPTERR=1
7819 * OPTIND=1
7820 * IFS=$' \t\n'
7821 * PS1='\s-\v\$ '
7822 * PS2='> '
7823 * PS4='+ '
7824 */
7825
Denis Vlasenko38f63192007-01-22 09:03:07 +00007826#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02007827 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007828#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007829
Eric Andersen94ac2442001-05-22 19:05:18 +00007830 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007831 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007832
Denis Vlasenkoed782372009-04-10 00:45:02 +00007833 if (setjmp(die_jmp)) {
7834 /* xfunc has failed! die die die */
7835 /* no EXIT traps, this is an escape hatch! */
7836 G.exiting = 1;
7837 hush_exit(xfunc_error_retval);
7838 }
7839
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007840 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007841 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007842 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007843 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007844 * in order to intercept (more) signals.
7845 */
7846
7847 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007848 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007849 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007850 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007851 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007852 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007853#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007854 "<:$:R:V:"
7855# if ENABLE_HUSH_FUNCTIONS
7856 "F:"
7857# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007858#endif
7859 );
7860 if (opt <= 0)
7861 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007862 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007863 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007864 /* Possibilities:
7865 * sh ... -c 'script'
7866 * sh ... -c 'script' ARG0 [ARG1...]
7867 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007868 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007869 * "" needs to be replaced with NULL
7870 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007871 * Note: the form without ARG0 never happens:
7872 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007873 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007874 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007875 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007876 G.root_ppid = getppid();
7877 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007878 G.global_argv = argv + optind;
7879 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007880 if (builtin_argc) {
7881 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7882 const struct built_in_command *x;
7883
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007884 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007885 x = find_builtin(optarg);
7886 if (x) { /* paranoia */
7887 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7888 G.global_argv += builtin_argc;
7889 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007890 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007891 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007892 }
7893 goto final_return;
7894 }
7895 if (!G.global_argv[0]) {
7896 /* -c 'script' (no params): prevent empty $0 */
7897 G.global_argv--; /* points to argv[i] of 'script' */
7898 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007899 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007900 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007901 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007902 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007903 goto final_return;
7904 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007905 /* Well, we cannot just declare interactiveness,
7906 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007907 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007908 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007909 case 's':
7910 /* "-s" means "read from stdin", but this is how we always
7911 * operate, so simply do nothing here. */
7912 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007913 case 'l':
7914 flags |= OPT_login;
7915 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007916#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007917 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007918 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007919 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007920 case '$': {
7921 unsigned long long empty_trap_mask;
7922
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007923 G.root_pid = bb_strtou(optarg, &optarg, 16);
7924 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007925 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7926 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007927 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7928 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007929 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007930 optarg++;
7931 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007932 optarg++;
7933 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7934 if (empty_trap_mask != 0) {
7935 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007936 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007937 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7938 for (sig = 1; sig < NSIG; sig++) {
7939 if (empty_trap_mask & (1LL << sig)) {
7940 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007941 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007942 }
7943 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007944 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007945# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007946 optarg++;
7947 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007948# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007949 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007950 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007951 case 'R':
7952 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007953 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007954 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007955# if ENABLE_HUSH_FUNCTIONS
7956 case 'F': {
7957 struct function *funcp = new_function(optarg);
7958 /* funcp->name is already set to optarg */
7959 /* funcp->body is set to NULL. It's a special case. */
7960 funcp->body_as_string = argv[optind];
7961 optind++;
7962 break;
7963 }
7964# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007965#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007966 case 'n':
7967 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007968 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007969 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007970 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007971#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007972 fprintf(stderr, "Usage: sh [FILE]...\n"
7973 " or: sh -c command [args]...\n\n");
7974 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007975#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007976 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007977#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007978 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007979 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007980
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007981 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7982 G.global_argc = argc - (optind - 1);
7983 G.global_argv = argv + (optind - 1);
7984 G.global_argv[0] = argv[0];
7985
Denys Vlasenkodea47882009-10-09 15:40:49 +02007986 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007987 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007988 G.root_ppid = getppid();
7989 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007990
7991 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007992 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007993 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007994 debug_printf("sourcing /etc/profile\n");
7995 input = fopen_for_read("/etc/profile");
7996 if (input != NULL) {
7997 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007998 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007999 parse_and_run_file(input);
8000 fclose(input);
8001 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008002 /* bash: after sourcing /etc/profile,
8003 * tries to source (in the given order):
8004 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008005 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008006 * bash also sources ~/.bash_logout on exit.
8007 * If called as sh, skips .bash_XXX files.
8008 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008009 }
8010
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008011 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008012 FILE *input;
8013 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008014 * "bash <script>" (which is never interactive (unless -i?))
8015 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008016 * If called as sh, does the same but with $ENV.
8017 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008018 G.global_argc--;
8019 G.global_argv++;
8020 debug_printf("running script '%s'\n", G.global_argv[0]);
8021 input = xfopen_for_read(G.global_argv[0]);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008022 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008023 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008024 parse_and_run_file(input);
8025#if ENABLE_FEATURE_CLEAN_UP
8026 fclose(input);
8027#endif
8028 goto final_return;
8029 }
8030
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008031 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008032 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008033 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008034
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008035 /* A shell is interactive if the '-i' flag was given,
8036 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008037 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008038 * no arguments remaining or the -s flag given
8039 * standard input is a terminal
8040 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008041 * Refer to Posix.2, the description of the 'sh' utility.
8042 */
8043#if ENABLE_HUSH_JOB
8044 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008045 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8046 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8047 if (G_saved_tty_pgrp < 0)
8048 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008049
8050 /* try to dup stdin to high fd#, >= 255 */
8051 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8052 if (G_interactive_fd < 0) {
8053 /* try to dup to any fd */
8054 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008055 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008056 /* give up */
8057 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008058 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008059 }
8060 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008061// TODO: track & disallow any attempts of user
8062// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008063 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008064 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008065 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008066 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008067
Mike Frysinger38478a62009-05-20 04:48:06 -04008068 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008069 /* If we were run as 'hush &', sleep until we are
8070 * in the foreground (tty pgrp == our pgrp).
8071 * If we get started under a job aware app (like bash),
8072 * make sure we are now in charge so we don't fight over
8073 * who gets the foreground */
8074 while (1) {
8075 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008076 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8077 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008078 break;
8079 /* send TTIN to ourself (should stop us) */
8080 kill(- shell_pgrp, SIGTTIN);
8081 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008082 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008083
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008084 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008085 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008086
Mike Frysinger38478a62009-05-20 04:48:06 -04008087 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008088 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008089 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008090 /* Put ourselves in our own process group
8091 * (bash, too, does this only if ctty is available) */
8092 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8093 /* Grab control of the terminal */
8094 tcsetpgrp(G_interactive_fd, getpid());
8095 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00008096 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00008097 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00008098 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008099
8100# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8101 {
8102 const char *hp = get_local_var_value("HISTFILE");
8103 if (!hp) {
8104 hp = get_local_var_value("HOME");
8105 if (hp)
8106 hp = concat_path_file(hp, ".hush_history");
8107 } else {
8108 hp = xstrdup(hp);
8109 }
8110 if (hp) {
8111 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008112 //set_local_var(xasprintf("HISTFILE=%s", ...));
8113 }
8114# if ENABLE_FEATURE_SH_HISTFILESIZE
8115 hp = get_local_var_value("HISTFILESIZE");
8116 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8117# endif
8118 }
8119# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008120 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008121 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008122 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008123#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008124 /* No job control compiled in, only prompt/line editing */
8125 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008126 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8127 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008128 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008129 G_interactive_fd = dup(STDIN_FILENO);
8130 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008131 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008132 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008133 }
8134 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008135 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008136 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008137 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008138 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008139#else
8140 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008141 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008142#endif
8143 /* bash:
8144 * if interactive but not a login shell, sources ~/.bashrc
8145 * (--norc turns this off, --rcfile <file> overrides)
8146 */
8147
8148 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008149 /* note: ash and hush share this string */
8150 printf("\n\n%s %s\n"
8151 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8152 "\n",
8153 bb_banner,
8154 "hush - the humble shell"
8155 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008156 }
8157
Denis Vlasenkof9375282009-04-05 19:13:39 +00008158 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008159
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008160 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008161 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008162}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008163
8164
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008165#if ENABLE_MSH
8166int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8167int msh_main(int argc, char **argv)
8168{
8169 //bb_error_msg("msh is deprecated, please use hush instead");
8170 return hush_main(argc, argv);
8171}
8172#endif
8173
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008174
8175/*
8176 * Built-ins
8177 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008178static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008179{
8180 return 0;
8181}
8182
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008183static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008184{
8185 int argc = 0;
8186 while (*argv) {
8187 argc++;
8188 argv++;
8189 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008190 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008191}
8192
8193static int FAST_FUNC builtin_test(char **argv)
8194{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008195 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008196}
8197
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008198static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008199{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008200 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008201}
8202
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008203#if ENABLE_PRINTF
8204static int FAST_FUNC builtin_printf(char **argv)
8205{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008206 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008207}
8208#endif
8209
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008210static char **skip_dash_dash(char **argv)
8211{
8212 argv++;
8213 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8214 argv++;
8215 return argv;
8216}
8217
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008218static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008219{
8220 int rcode = EXIT_SUCCESS;
8221
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008222 argv = skip_dash_dash(argv);
8223 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008224 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008225 /* bash:
8226 * eval "echo Hi; done" ("done" is syntax error):
8227 * "echo Hi" will not execute too.
8228 */
8229 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008230 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008231 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008232 }
8233 return rcode;
8234}
8235
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008236static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008237{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008238 const char *newdir;
8239
8240 argv = skip_dash_dash(argv);
8241 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008242 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008243 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008244 * bash says "bash: cd: HOME not set" and does nothing
8245 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008246 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008247 const char *home = get_local_var_value("HOME");
8248 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008249 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008250 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008251 /* Mimic bash message exactly */
8252 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008253 return EXIT_FAILURE;
8254 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008255 /* Read current dir (get_cwd(1) is inside) and set PWD.
8256 * Note: do not enforce exporting. If PWD was unset or unexported,
8257 * set it again, but do not export. bash does the same.
8258 */
8259 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008260 return EXIT_SUCCESS;
8261}
8262
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008263static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008264{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008265 argv = skip_dash_dash(argv);
8266 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008267 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008268
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008269 /* Careful: we can end up here after [v]fork. Do not restore
8270 * tty pgrp then, only top-level shell process does that */
8271 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8272 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8273
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008274 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008275 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008276 * and tcsetpgrp, and this is inherently racy.
8277 */
8278 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008279}
8280
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008281static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008282{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008283 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008284
8285 /* interactive bash:
8286 * # trap "echo EEE" EXIT
8287 * # exit
8288 * exit
8289 * There are stopped jobs.
8290 * (if there are _stopped_ jobs, running ones don't count)
8291 * # exit
8292 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01008293 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00008294 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008295 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008296 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008297
8298 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008299 argv = skip_dash_dash(argv);
8300 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008301 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008302 /* mimic bash: exit 123abc == exit 255 + error msg */
8303 xfunc_error_retval = 255;
8304 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008305 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008306}
8307
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008308static void print_escaped(const char *s)
8309{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008310 if (*s == '\'')
8311 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008312 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008313 const char *p = strchrnul(s, '\'');
8314 /* print 'xxxx', possibly just '' */
8315 printf("'%.*s'", (int)(p - s), s);
8316 if (*p == '\0')
8317 break;
8318 s = p;
8319 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008320 /* s points to '; print "'''...'''" */
8321 putchar('"');
8322 do putchar('\''); while (*++s == '\'');
8323 putchar('"');
8324 } while (*s);
8325}
8326
Denys Vlasenko295fef82009-06-03 12:47:26 +02008327#if !ENABLE_HUSH_LOCAL
8328#define helper_export_local(argv, exp, lvl) \
8329 helper_export_local(argv, exp)
8330#endif
8331static void helper_export_local(char **argv, int exp, int lvl)
8332{
8333 do {
8334 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008335 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008336
8337 /* So far we do not check that name is valid (TODO?) */
8338
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008339 if (*name_end == '\0') {
8340 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008341
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008342 vpp = get_ptr_to_local_var(name, name_end - name);
8343 var = vpp ? *vpp : NULL;
8344
Denys Vlasenko295fef82009-06-03 12:47:26 +02008345 if (exp == -1) { /* unexporting? */
8346 /* export -n NAME (without =VALUE) */
8347 if (var) {
8348 var->flg_export = 0;
8349 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8350 unsetenv(name);
8351 } /* else: export -n NOT_EXISTING_VAR: no-op */
8352 continue;
8353 }
8354 if (exp == 1) { /* exporting? */
8355 /* export NAME (without =VALUE) */
8356 if (var) {
8357 var->flg_export = 1;
8358 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8359 putenv(var->varstr);
8360 continue;
8361 }
8362 }
8363 /* Exporting non-existing variable.
8364 * bash does not put it in environment,
8365 * but remembers that it is exported,
8366 * and does put it in env when it is set later.
8367 * We just set it to "" and export. */
8368 /* Or, it's "local NAME" (without =VALUE).
8369 * bash sets the value to "". */
8370 name = xasprintf("%s=", name);
8371 } else {
8372 /* (Un)exporting/making local NAME=VALUE */
8373 name = xstrdup(name);
8374 }
8375 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8376 } while (*++argv);
8377}
8378
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008379static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008380{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008381 unsigned opt_unexport;
8382
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008383#if ENABLE_HUSH_EXPORT_N
8384 /* "!": do not abort on errors */
8385 opt_unexport = getopt32(argv, "!n");
8386 if (opt_unexport == (uint32_t)-1)
8387 return EXIT_FAILURE;
8388 argv += optind;
8389#else
8390 opt_unexport = 0;
8391 argv++;
8392#endif
8393
8394 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008395 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008396 if (e) {
8397 while (*e) {
8398#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008399 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008400#else
8401 /* ash emits: export VAR='VAL'
8402 * bash: declare -x VAR="VAL"
8403 * we follow ash example */
8404 const char *s = *e++;
8405 const char *p = strchr(s, '=');
8406
8407 if (!p) /* wtf? take next variable */
8408 continue;
8409 /* export var= */
8410 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008411 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008412 putchar('\n');
8413#endif
8414 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008415 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008416 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008417 return EXIT_SUCCESS;
8418 }
8419
Denys Vlasenko295fef82009-06-03 12:47:26 +02008420 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008421
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008422 return EXIT_SUCCESS;
8423}
8424
Denys Vlasenko295fef82009-06-03 12:47:26 +02008425#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008426static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008427{
8428 if (G.func_nest_level == 0) {
8429 bb_error_msg("%s: not in a function", argv[0]);
8430 return EXIT_FAILURE; /* bash compat */
8431 }
8432 helper_export_local(argv, 0, G.func_nest_level);
8433 return EXIT_SUCCESS;
8434}
8435#endif
8436
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008437static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008438{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008439 int sig;
8440 char *new_cmd;
8441
8442 if (!G.traps)
8443 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8444
8445 argv++;
8446 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008447 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008448 /* No args: print all trapped */
8449 for (i = 0; i < NSIG; ++i) {
8450 if (G.traps[i]) {
8451 printf("trap -- ");
8452 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008453 /* note: bash adds "SIG", but only if invoked
8454 * as "bash". If called as "sh", or if set -o posix,
8455 * then it prints short signal names.
8456 * We are printing short names: */
8457 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008458 }
8459 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008460 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008461 return EXIT_SUCCESS;
8462 }
8463
8464 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008465 /* If first arg is a number: reset all specified signals */
8466 sig = bb_strtou(*argv, NULL, 10);
8467 if (errno == 0) {
8468 int ret;
8469 process_sig_list:
8470 ret = EXIT_SUCCESS;
8471 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008472 sighandler_t handler;
8473
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008474 sig = get_signum(*argv++);
8475 if (sig < 0 || sig >= NSIG) {
8476 ret = EXIT_FAILURE;
8477 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008478 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008479 continue;
8480 }
8481
8482 free(G.traps[sig]);
8483 G.traps[sig] = xstrdup(new_cmd);
8484
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008485 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008486 get_signame(sig), sig, G.traps[sig]);
8487
8488 /* There is no signal for 0 (EXIT) */
8489 if (sig == 0)
8490 continue;
8491
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008492 if (new_cmd)
8493 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8494 else
8495 /* We are removing trap handler */
8496 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02008497 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008498 }
8499 return ret;
8500 }
8501
8502 if (!argv[1]) { /* no second arg */
8503 bb_error_msg("trap: invalid arguments");
8504 return EXIT_FAILURE;
8505 }
8506
8507 /* First arg is "-": reset all specified to default */
8508 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8509 /* Everything else: set arg as signal handler
8510 * (includes "" case, which ignores signal) */
8511 if (argv[0][0] == '-') {
8512 if (argv[0][1] == '\0') { /* "-" */
8513 /* new_cmd remains NULL: "reset these sigs" */
8514 goto reset_traps;
8515 }
8516 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8517 argv++;
8518 }
8519 /* else: "-something", no special meaning */
8520 }
8521 new_cmd = *argv;
8522 reset_traps:
8523 argv++;
8524 goto process_sig_list;
8525}
8526
Mike Frysinger93cadc22009-05-27 17:06:25 -04008527/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008528static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008529{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008530 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008531
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008532 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008533 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008534 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008535
8536 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008537 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008538 type = "an alias";*/
8539#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008540 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008541 type = "a function";
8542#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008543 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008544 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008545 else if ((path = find_in_path(*argv)) != NULL)
8546 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008547 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008548 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008549 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008550 continue;
8551 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008552
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008553 printf("%s is %s\n", *argv, type);
8554 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008555 }
8556
8557 return ret;
8558}
8559
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008560#if ENABLE_HUSH_JOB
8561/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008562static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008563{
8564 int i, jobnum;
8565 struct pipe *pi;
8566
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008567 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008568 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008569
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008570 /* If they gave us no args, assume they want the last backgrounded task */
8571 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008572 for (pi = G.job_list; pi; pi = pi->next) {
8573 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008574 goto found;
8575 }
8576 }
8577 bb_error_msg("%s: no current job", argv[0]);
8578 return EXIT_FAILURE;
8579 }
8580 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8581 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8582 return EXIT_FAILURE;
8583 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008584 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008585 if (pi->jobid == jobnum) {
8586 goto found;
8587 }
8588 }
8589 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8590 return EXIT_FAILURE;
8591 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008592 /* TODO: bash prints a string representation
8593 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008594 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008595 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008596 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008597 }
8598
8599 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008600 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8601 for (i = 0; i < pi->num_cmds; i++) {
8602 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008603 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008604 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008605
8606 i = kill(- pi->pgrp, SIGCONT);
8607 if (i < 0) {
8608 if (errno == ESRCH) {
8609 delete_finished_bg_job(pi);
8610 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008611 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008612 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008613 }
8614
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008615 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008616 remove_bg_job(pi);
8617 return checkjobs_and_fg_shell(pi);
8618 }
8619 return EXIT_SUCCESS;
8620}
8621#endif
8622
8623#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008624static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008625{
8626 const struct built_in_command *x;
8627
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008628 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008629 "Built-in commands:\n"
8630 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008631 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008632 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008633 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008634 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008635 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008636 return EXIT_SUCCESS;
8637}
8638#endif
8639
Denys Vlasenkoff463a82013-05-12 02:45:23 +02008640#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02008641static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
8642{
8643 show_history(G.line_input_state);
8644 return EXIT_SUCCESS;
8645}
8646#endif
8647
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008648#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008649static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008650{
8651 struct pipe *job;
8652 const char *status_string;
8653
Denis Vlasenko87a86552008-07-29 19:43:10 +00008654 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008655 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008656 status_string = "Stopped";
8657 else
8658 status_string = "Running";
8659
8660 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8661 }
8662 return EXIT_SUCCESS;
8663}
8664#endif
8665
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008666#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008667static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008668{
8669 void *p;
8670 unsigned long l;
8671
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008672# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008673 /* Optional. Reduces probability of false positives */
8674 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008675# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008676 /* Crude attempt to find where "free memory" starts,
8677 * sans fragmentation. */
8678 p = malloc(240);
8679 l = (unsigned long)p;
8680 free(p);
8681 p = malloc(3400);
8682 if (l < (unsigned long)p) l = (unsigned long)p;
8683 free(p);
8684
8685 if (!G.memleak_value)
8686 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008687
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008688 l -= G.memleak_value;
8689 if ((long)l < 0)
8690 l = 0;
8691 l /= 1024;
8692 if (l > 127)
8693 l = 127;
8694
8695 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8696 return l;
8697}
8698#endif
8699
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008700static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008701{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008702 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008703 return EXIT_SUCCESS;
8704}
8705
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008706/* Interruptibility of read builtin in bash
8707 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8708 *
8709 * Empty trap makes read ignore corresponding signal, for any signal.
8710 *
8711 * SIGINT:
8712 * - terminates non-interactive shell;
8713 * - interrupts read in interactive shell;
8714 * if it has non-empty trap:
8715 * - executes trap and returns to command prompt in interactive shell;
8716 * - executes trap and returns to read in non-interactive shell;
8717 * SIGTERM:
8718 * - is ignored (does not interrupt) read in interactive shell;
8719 * - terminates non-interactive shell;
8720 * if it has non-empty trap:
8721 * - executes trap and returns to read;
8722 * SIGHUP:
8723 * - terminates shell (regardless of interactivity);
8724 * if it has non-empty trap:
8725 * - executes trap and returns to read;
8726 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008727static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008728{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008729 const char *r;
8730 char *opt_n = NULL;
8731 char *opt_p = NULL;
8732 char *opt_t = NULL;
8733 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008734 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01008735 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008736
Denys Vlasenko03dad222010-01-12 23:29:57 +01008737 /* "!": do not abort on errors.
8738 * Option string must start with "sr" to match BUILTIN_READ_xxx
8739 */
8740 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8741 if (read_flags == (uint32_t)-1)
8742 return EXIT_FAILURE;
8743 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008744 ifs = get_local_var_value("IFS"); /* can be NULL */
8745
8746 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01008747 r = shell_builtin_read(set_local_var_from_halves,
8748 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008749 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01008750 read_flags,
8751 opt_n,
8752 opt_p,
8753 opt_t,
8754 opt_u
8755 );
8756
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008757 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008758 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008759 if (sig && sig != SIGINT)
8760 goto again;
8761 }
8762
Denys Vlasenko03dad222010-01-12 23:29:57 +01008763 if ((uintptr_t)r > 1) {
8764 bb_error_msg("%s", r);
8765 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008766 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008767
Denys Vlasenko03dad222010-01-12 23:29:57 +01008768 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008769}
8770
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008771/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8772 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008773 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008774 * set [-abCefhmnuvx] [-o option] [argument...]
8775 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008776 * set -- [argument...]
8777 * set -o
8778 * set +o
8779 * Implementations shall support the options in both their hyphen and
8780 * plus-sign forms. These options can also be specified as options to sh.
8781 * Examples:
8782 * Write out all variables and their values: set
8783 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8784 * Turn on the -x and -v options: set -xv
8785 * Unset all positional parameters: set --
8786 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8787 * Set the positional parameters to the expansion of x, even if x expands
8788 * with a leading '-' or '+': set -- $x
8789 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008790 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008791 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008792static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008793{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008794 int n;
8795 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008796 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008797
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008798 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008799 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008800 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008801 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008802 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008803 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008804
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008805 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008806 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008807 ++argv;
8808 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008809 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008810 if (arg[0] != '+' && arg[0] != '-')
8811 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008812 for (n = 1; arg[n]; ++n) {
8813 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008814 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008815 if (arg[n] == 'o' && argv[1])
8816 argv++;
8817 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008818 } while ((arg = *++argv) != NULL);
8819 /* Now argv[0] is 1st argument */
8820
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008821 if (arg == NULL)
8822 return EXIT_SUCCESS;
8823 set_argv:
8824
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008825 /* NB: G.global_argv[0] ($0) is never freed/changed */
8826 g_argv = G.global_argv;
8827 if (G.global_args_malloced) {
8828 pp = g_argv;
8829 while (*++pp)
8830 free(*pp);
8831 g_argv[1] = NULL;
8832 } else {
8833 G.global_args_malloced = 1;
8834 pp = xzalloc(sizeof(pp[0]) * 2);
8835 pp[0] = g_argv[0]; /* retain $0 */
8836 g_argv = pp;
8837 }
8838 /* This realloc's G.global_argv */
8839 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8840
8841 n = 1;
8842 while (*++pp)
8843 n++;
8844 G.global_argc = n;
8845
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008846 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008847
8848 /* Nothing known, so abort */
8849 error:
8850 bb_error_msg("set: %s: invalid option", arg);
8851 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008852}
8853
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008854static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008855{
8856 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008857 argv = skip_dash_dash(argv);
8858 if (argv[0]) {
8859 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008860 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008861 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008862 if (G.global_args_malloced) {
8863 int m = 1;
8864 while (m <= n)
8865 free(G.global_argv[m++]);
8866 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008867 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008868 memmove(&G.global_argv[1], &G.global_argv[n+1],
8869 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008870 return EXIT_SUCCESS;
8871 }
8872 return EXIT_FAILURE;
8873}
8874
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008875static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008876{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008877 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008878 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008879 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008880#if ENABLE_HUSH_FUNCTIONS
8881 smallint sv_flg;
8882#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008883
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008884 argv = skip_dash_dash(argv);
8885 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008886 if (!filename) {
8887 /* bash says: "bash: .: filename argument required" */
8888 return 2; /* bash compat */
8889 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008890 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008891 if (!strchr(filename, '/')) {
8892 arg_path = find_in_path(filename);
8893 if (arg_path)
8894 filename = arg_path;
8895 }
8896 input = fopen_or_warn(filename, "r");
8897 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008898 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008899 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01008900 /* POSIX: non-interactive shell should abort here,
8901 * not merely fail. So far no one complained :)
8902 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008903 return EXIT_FAILURE;
8904 }
8905 close_on_exec_on(fileno(input));
8906
Mike Frysinger885b6f22009-04-18 21:04:25 +00008907#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008908 sv_flg = G.flag_return_in_progress;
8909 /* "we are inside sourced file, ok to use return" */
8910 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008911#endif
Denys Vlasenko88b532d2013-03-17 14:11:04 +01008912 if (argv[1])
8913 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008914
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008915 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008916 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008917
Denys Vlasenko88b532d2013-03-17 14:11:04 +01008918 if (argv[1])
8919 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008920#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008921 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008922#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008923
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008924 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008925}
8926
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008927static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008928{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008929 int rc;
8930 mode_t mask;
8931
8932 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008933 argv = skip_dash_dash(argv);
8934 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008935 mode_t old_mask = mask;
8936
8937 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008938 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008939 mask ^= 0777;
8940 if (rc == 0) {
8941 mask = old_mask;
8942 /* bash messages:
8943 * bash: umask: 'q': invalid symbolic mode operator
8944 * bash: umask: 999: octal number out of range
8945 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008946 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008947 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008948 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008949 rc = 1;
8950 /* Mimic bash */
8951 printf("%04o\n", (unsigned) mask);
8952 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008953 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008954 umask(mask);
8955
8956 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008957}
8958
Mike Frysingerd690f682009-03-30 06:50:54 +00008959/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008960static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008961{
Mike Frysingerd690f682009-03-30 06:50:54 +00008962 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008963 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008964
Denis Vlasenko28e67962009-04-26 23:22:40 +00008965 /* "!": do not abort on errors */
8966 /* "+": stop at 1st non-option */
8967 opts = getopt32(argv, "!+vf");
8968 if (opts == (unsigned)-1)
8969 return EXIT_FAILURE;
8970 if (opts == 3) {
8971 bb_error_msg("unset: -v and -f are exclusive");
8972 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008973 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008974 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008975
8976 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008977 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008978 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008979 if (unset_local_var(*argv)) {
8980 /* unset <nonexistent_var> doesn't fail.
8981 * Error is when one tries to unset RO var.
8982 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008983 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008984 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008985 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008986#if ENABLE_HUSH_FUNCTIONS
8987 else {
8988 unset_func(*argv);
8989 }
8990#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008991 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008992 }
8993 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008994}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008995
Mike Frysinger56bdea12009-03-28 20:01:58 +00008996/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008997static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008998{
8999 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009000 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009001
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009002 argv = skip_dash_dash(argv);
9003 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009004 /* Don't care about wait results */
9005 /* Note 1: must wait until there are no more children */
9006 /* Note 2: must be interruptible */
9007 /* Examples:
9008 * $ sleep 3 & sleep 6 & wait
9009 * [1] 30934 sleep 3
9010 * [2] 30935 sleep 6
9011 * [1] Done sleep 3
9012 * [2] Done sleep 6
9013 * $ sleep 3 & sleep 6 & wait
9014 * [1] 30936 sleep 3
9015 * [2] 30937 sleep 6
9016 * [1] Done sleep 3
9017 * ^C <-- after ~4 sec from keyboard
9018 * $
9019 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009020 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009021 int sig;
9022 sigset_t oldset, allsigs;
9023
9024 /* waitpid is not interruptible by SA_RESTARTed
9025 * signals which we use. Thus, this ugly dance:
9026 */
9027
9028 /* Make sure possible SIGCHLD is stored in kernel's
9029 * pending signal mask before we call waitpid.
9030 * Or else we may race with SIGCHLD, lose it,
9031 * and get stuck in sigwaitinfo...
9032 */
9033 sigfillset(&allsigs);
9034 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9035
9036 if (!sigisemptyset(&G.pending_set)) {
9037 /* Crap! we raced with some signal! */
9038 // sig = 0;
9039 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009040 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009041
9042 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9043 if (errno == ECHILD) {
9044 sigprocmask(SIG_SETMASK, &oldset, NULL);
9045 break;
9046 }
9047
9048 /* Wait for SIGCHLD or any other signal */
9049 //sig = sigwaitinfo(&allsigs, NULL);
9050 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9051 /* Note: sigsuspend invokes signal handler */
9052 sigsuspend(&oldset);
9053 restore:
9054 sigprocmask(SIG_SETMASK, &oldset, NULL);
9055
9056 /* So, did we get a signal? */
9057 //if (sig > 0)
9058 // raise(sig); /* run handler */
9059 sig = check_and_run_traps();
9060 if (sig /*&& sig != SIGCHLD - always true */) {
9061 /* see note 2 */
9062 ret = 128 + sig;
9063 break;
9064 }
9065 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009066 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009067 return ret;
9068 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009069
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009070 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009071 while (*argv) {
9072 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00009073 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009074 /* mimic bash message */
9075 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009076 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009077 }
9078 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00009079 if (WIFSIGNALED(status))
9080 ret = 128 + WTERMSIG(status);
9081 else if (WIFEXITED(status))
9082 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00009083 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00009084 ret = EXIT_FAILURE;
9085 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009086 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009087 ret = 127;
9088 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00009089 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009090 }
9091
9092 return ret;
9093}
9094
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009095#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9096static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9097{
9098 if (argv[1]) {
9099 def = bb_strtou(argv[1], NULL, 10);
9100 if (errno || def < def_min || argv[2]) {
9101 bb_error_msg("%s: bad arguments", argv[0]);
9102 def = UINT_MAX;
9103 }
9104 }
9105 return def;
9106}
9107#endif
9108
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009109#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009110static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009111{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009112 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009113 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009114 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009115 return EXIT_SUCCESS; /* bash compat */
9116 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009117 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009118
9119 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9120 if (depth == UINT_MAX)
9121 G.flag_break_continue = BC_BREAK;
9122 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009123 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009124
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009125 return EXIT_SUCCESS;
9126}
9127
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009128static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009129{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009130 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9131 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009132}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009133#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009134
9135#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009136static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009137{
9138 int rc;
9139
9140 if (G.flag_return_in_progress != -1) {
9141 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9142 return EXIT_FAILURE; /* bash compat */
9143 }
9144
9145 G.flag_return_in_progress = 1;
9146
9147 /* bash:
9148 * out of range: wraps around at 256, does not error out
9149 * non-numeric param:
9150 * f() { false; return qwe; }; f; echo $?
9151 * bash: return: qwe: numeric argument required <== we do this
9152 * 255 <== we also do this
9153 */
9154 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9155 return rc;
9156}
9157#endif