blob: 888be6e6eaf598351e8b3ba395f86a26e99c71bd [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 Vlasenko7e675362016-10-28 21:57:31 +020047 * kill %jobspec
Denys Vlasenko349ef962010-05-21 15:46:24 +020048 * follow IFS rules more precisely, including update semantics
49 * builtins mandated by standards we don't support:
50 * [un]alias, command, fc, getopts, newgrp, readonly, times
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020051 * make complex ${var%...} constructs support optional
52 * make here documents optional
Mike Frysinger25a6ca02009-03-28 13:59:26 +000053 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020054 * Bash compat TODO:
55 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020056 * reserved words: function select
57 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020058 * process substitution: <(list) and >(list)
59 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020060 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020061 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
62 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
63 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020064 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020065 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
66 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020067 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenkobbecd742010-10-03 17:22:52 +020068 *
69 * Won't do:
70 * In bash, export builtin is special, its arguments are assignments
Denys Vlasenko08218012009-06-03 14:43:56 +020071 * and therefore expansion of them should be "one-word" expansion:
72 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
73 * compare with:
74 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
75 * ls: cannot access i=a: No such file or directory
76 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020077 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020078 * Note2: bash 3.2.33(1) does this only if export word itself
79 * is not quoted:
80 * $ export i=`echo 'aaa bbb'`; echo "$i"
81 * aaa bbb
82 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
83 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000084 */
Denys Vlasenko8da415e2010-12-05 01:30:14 +010085#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
86 || defined(__APPLE__) \
87 )
88# include <malloc.h> /* for malloc_trim */
89#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +000090#include <glob.h>
91/* #include <dmalloc.h> */
92#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000093# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000094#endif
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020095#include <sys/utsname.h> /* for setting $HOSTNAME */
Denys Vlasenko03dad222010-01-12 23:29:57 +010096
Denys Vlasenko20704f02011-03-23 17:59:27 +010097#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
98#include "unicode.h"
Denys Vlasenko03dad222010-01-12 23:29:57 +010099#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +0000100#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +0000101#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +0200102#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200103# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +0200104#else
105# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200106#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200107#ifndef F_DUPFD_CLOEXEC
108# define F_DUPFD_CLOEXEC F_DUPFD
109#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000110#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200111# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000112#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000113
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200114//config:config HUSH
115//config: bool "hush"
116//config: default y
117//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200118//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200119//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
120//config: case/esac. Redirections, here documents, $((arithmetic))
121//config: and functions are supported.
122//config:
123//config: It will compile and work on no-mmu systems.
124//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +0200125//config: It does not handle select, aliases, tilde expansion,
126//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200127//config:
128//config:config HUSH_BASH_COMPAT
129//config: bool "bash-compatible extensions"
130//config: default y
131//config: depends on HUSH
132//config: help
133//config: Enable bash-compatible extensions.
134//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200135//config:config HUSH_BRACE_EXPANSION
136//config: bool "Brace expansion"
137//config: default y
138//config: depends on HUSH_BASH_COMPAT
139//config: help
140//config: Enable {abc,def} extension.
141//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:config HUSH_HELP
143//config: bool "help builtin"
144//config: default y
145//config: depends on HUSH
146//config: help
147//config: Enable help builtin in hush. Code size + ~1 kbyte.
148//config:
149//config:config HUSH_INTERACTIVE
150//config: bool "Interactive mode"
151//config: default y
152//config: depends on HUSH
153//config: help
154//config: Enable interactive mode (prompt and command editing).
155//config: Without this, hush simply reads and executes commands
156//config: from stdin just like a shell script from a file.
157//config: No prompt, no PS1/PS2 magic shell variables.
158//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200159//config:config HUSH_SAVEHISTORY
160//config: bool "Save command history to .hush_history"
161//config: default y
162//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
163//config: help
164//config: Enable history saving in hush.
165//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200166//config:config HUSH_JOB
167//config: bool "Job control"
168//config: default y
169//config: depends on HUSH_INTERACTIVE
170//config: help
171//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
172//config: command (not entire shell), fg/bg builtins work. Without this option,
173//config: "cmd &" still works by simply spawning a process and immediately
174//config: prompting for next command (or executing next command in a script),
175//config: but no separate process group is formed.
176//config:
177//config:config HUSH_TICK
178//config: bool "Process substitution"
179//config: default y
180//config: depends on HUSH
181//config: help
182//config: Enable process substitution `command` and $(command) in hush.
183//config:
184//config:config HUSH_IF
185//config: bool "Support if/then/elif/else/fi"
186//config: default y
187//config: depends on HUSH
188//config: help
189//config: Enable if/then/elif/else/fi in hush.
190//config:
191//config:config HUSH_LOOPS
192//config: bool "Support for, while and until loops"
193//config: default y
194//config: depends on HUSH
195//config: help
196//config: Enable for, while and until loops in hush.
197//config:
198//config:config HUSH_CASE
199//config: bool "Support case ... esac statement"
200//config: default y
201//config: depends on HUSH
202//config: help
203//config: Enable case ... esac statement in hush. +400 bytes.
204//config:
205//config:config HUSH_FUNCTIONS
206//config: bool "Support funcname() { commands; } syntax"
207//config: default y
208//config: depends on HUSH
209//config: help
210//config: Enable support for shell functions in hush. +800 bytes.
211//config:
212//config:config HUSH_LOCAL
213//config: bool "Support local builtin"
214//config: default y
215//config: depends on HUSH_FUNCTIONS
216//config: help
217//config: Enable support for local variables in functions.
218//config:
219//config:config HUSH_RANDOM_SUPPORT
220//config: bool "Pseudorandom generator and $RANDOM variable"
221//config: default y
222//config: depends on HUSH
223//config: help
224//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
225//config: Each read of "$RANDOM" will generate a new pseudorandom value.
226//config:
227//config:config HUSH_EXPORT_N
228//config: bool "Support 'export -n' option"
229//config: default y
230//config: depends on HUSH
231//config: help
232//config: export -n unexports variables. It is a bash extension.
233//config:
234//config:config HUSH_MODE_X
235//config: bool "Support 'hush -x' option and 'set -x' command"
236//config: default y
237//config: depends on HUSH
238//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200239//config: This instructs hush to print commands before execution.
240//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200241//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200242//config:config MSH
243//config: bool "msh (deprecated: aliased to hush)"
244//config: default n
245//config: select HUSH
246//config: help
247//config: msh is deprecated and will be removed, please migrate to hush.
248//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200249
Denys Vlasenko20704f02011-03-23 17:59:27 +0100250//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
251//applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
252//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
253//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
254
255//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
256//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
257
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100258/* -i (interactive) and -s (read stdin) are also accepted,
259 * but currently do nothing, therefore aren't shown in help.
260 * NOMMU-specific options are not meant to be used by users,
261 * therefore we don't show them either.
262 */
263//usage:#define hush_trivial_usage
Denys Vlasenkof58f7052011-05-12 02:10:33 +0200264//usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100265//usage:#define hush_full_usage "\n\n"
266//usage: "Unix shell interpreter"
267
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100268//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100269//usage:#define msh_full_usage hush_full_usage
270
271//usage:#if ENABLE_FEATURE_SH_IS_HUSH
272//usage:# define sh_trivial_usage hush_trivial_usage
273//usage:# define sh_full_usage hush_full_usage
274//usage:#endif
275//usage:#if ENABLE_FEATURE_BASH_IS_HUSH
276//usage:# define bash_trivial_usage hush_trivial_usage
277//usage:# define bash_full_usage hush_full_usage
278//usage:#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200279
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000280
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200281/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000282#define LEAK_HUNTING 0
283#define BUILD_AS_NOMMU 0
284/* Enable/disable sanity checks. Ok to enable in production,
285 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
286 * Keeping 1 for now even in released versions.
287 */
288#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200289/* Slightly bigger (+200 bytes), but faster hush.
290 * So far it only enables a trick with counting SIGCHLDs and forks,
291 * which allows us to do fewer waitpid's.
292 * (we can detect a case where neither forks were done nor SIGCHLDs happened
293 * and therefore waitpid will return the same result as last time)
294 */
295#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200296/* TODO: implement simplified code for users which do not need ${var%...} ops
297 * So far ${var%...} ops are always enabled:
298 */
299#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000300
301
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000302#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000303# undef BB_MMU
304# undef USE_FOR_NOMMU
305# undef USE_FOR_MMU
306# define BB_MMU 0
307# define USE_FOR_NOMMU(...) __VA_ARGS__
308# define USE_FOR_MMU(...)
309#endif
310
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200311#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100312#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000313/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000314# undef CONFIG_FEATURE_SH_STANDALONE
315# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000316# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100317# undef IF_NOT_FEATURE_SH_STANDALONE
318# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000319# define IF_FEATURE_SH_STANDALONE(...)
320# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000321#endif
322
Denis Vlasenko05743d72008-02-10 12:10:08 +0000323#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000324# undef ENABLE_FEATURE_EDITING
325# define ENABLE_FEATURE_EDITING 0
326# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
327# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200328# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
329# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000330#endif
331
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000332/* Do we support ANY keywords? */
333#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000334# define HAS_KEYWORDS 1
335# define IF_HAS_KEYWORDS(...) __VA_ARGS__
336# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000337#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000338# define HAS_KEYWORDS 0
339# define IF_HAS_KEYWORDS(...)
340# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000341#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000342
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000343/* If you comment out one of these below, it will be #defined later
344 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000345#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000346/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000347#define debug_printf_parse(...) do {} while (0)
348#define debug_print_tree(a, b) do {} while (0)
349#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000350#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000351#define debug_printf_jobs(...) do {} while (0)
352#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200353#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000354#define debug_printf_glob(...) do {} while (0)
355#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000356#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000357#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000358
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000359#define ERR_PTR ((void*)(long)1)
360
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200361#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000362
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200363#define _SPECIAL_VARS_STR "_*@$!?#"
364#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
365#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200366#if ENABLE_HUSH_BASH_COMPAT
367/* Support / and // replace ops */
368/* Note that // is stored as \ in "encoded" string representation */
369# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
370# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
371# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
372#else
373# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
374# define VAR_SUBST_OPS "%#:-=+?"
375# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
376#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200377
378#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000379
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200380struct variable;
381
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000382static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
383
384/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000385 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000386 */
387#if !BB_MMU
388typedef struct nommu_save_t {
389 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200390 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000391 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000392 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000393} nommu_save_t;
394#endif
395
Denys Vlasenko9b782552010-09-08 13:33:26 +0200396enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000397 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000398#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000399 RES_IF ,
400 RES_THEN ,
401 RES_ELIF ,
402 RES_ELSE ,
403 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000404#endif
405#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000406 RES_FOR ,
407 RES_WHILE ,
408 RES_UNTIL ,
409 RES_DO ,
410 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000411#endif
412#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000413 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000414#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000415#if ENABLE_HUSH_CASE
416 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200417 /* three pseudo-keywords support contrived "case" syntax: */
418 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
419 RES_MATCH , /* "word)" */
420 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000421 RES_ESAC ,
422#endif
423 RES_XXXX ,
424 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200425};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000426
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000427typedef struct o_string {
428 char *data;
429 int length; /* position where data is appended */
430 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200431 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000432 /* At least some part of the string was inside '' or "",
433 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200434 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000435 smallint has_empty_slot;
436 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
437} o_string;
438enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200439 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
440 EXP_FLAG_GLOB = 0x2,
441 /* Protect newly added chars against globbing
442 * by prepending \ to *, ?, [, \ */
443 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
444};
445enum {
446 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000447 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200448 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200449 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200450 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000451};
452/* Used for initialization: o_string foo = NULL_O_STRING; */
453#define NULL_O_STRING { NULL }
454
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200455#ifndef debug_printf_parse
456static const char *const assignment_flag[] = {
457 "MAYBE_ASSIGNMENT",
458 "DEFINITELY_ASSIGNMENT",
459 "NOT_ASSIGNMENT",
460 "WORD_IS_KEYWORD",
461};
462#endif
463
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000464typedef struct in_str {
465 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000466#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000467 smallint promptmode; /* 0: PS1, 1: PS2 */
468#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200469 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200470 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000471 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000472} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000473
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200474/* The descrip member of this structure is only used to make
475 * debugging output pretty */
476static const struct {
477 int mode;
478 signed char default_fd;
479 char descrip[3];
480} redir_table[] = {
481 { O_RDONLY, 0, "<" },
482 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
483 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
484 { O_CREAT|O_RDWR, 1, "<>" },
485 { O_RDONLY, 0, "<<" },
486/* Should not be needed. Bogus default_fd helps in debugging */
487/* { O_RDONLY, 77, "<<" }, */
488};
489
Eric Andersen25f27032001-04-26 23:22:31 +0000490struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000491 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000492 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000493 int rd_fd; /* fd to redirect */
494 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
495 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000496 smallint rd_type; /* (enum redir_type) */
497 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000498 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200499 * bit 0: do we need to trim leading tabs?
500 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000501 */
Eric Andersen25f27032001-04-26 23:22:31 +0000502};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000503typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200504 REDIRECT_INPUT = 0,
505 REDIRECT_OVERWRITE = 1,
506 REDIRECT_APPEND = 2,
507 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000508 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200509 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000510
511 REDIRFD_CLOSE = -3,
512 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000513 REDIRFD_TO_FILE = -1,
514 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000515
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000516 HEREDOC_SKIPTABS = 1,
517 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000518} redir_type;
519
Eric Andersen25f27032001-04-26 23:22:31 +0000520
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000521struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000522 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000523 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200524 smallint cmd_type; /* CMD_xxx */
525#define CMD_NORMAL 0
526#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200527#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200528/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200529# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000530#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200531#if ENABLE_HUSH_FUNCTIONS
532# define CMD_FUNCDEF 3
533#endif
534
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100535 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200536 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
537 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000538#if !BB_MMU
539 char *group_as_string;
540#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000541#if ENABLE_HUSH_FUNCTIONS
542 struct function *child_func;
543/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200544 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000545 * When we execute "f1() {a;}" cmd, we create new function and clear
546 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200547 * When we execute "f1() {b;}", we notice that f1 exists,
548 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000549 * we put those fields back into cmd->xxx
550 * (struct function has ->parent_cmd ptr to facilitate that).
551 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
552 * Without this trick, loop would execute a;b;b;b;...
553 * instead of correct sequence a;b;a;b;...
554 * When command is freed, it severs the link
555 * (sets ->child_func->parent_cmd to NULL).
556 */
557#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000558 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000559/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
560 * and on execution these are substituted with their values.
561 * Substitution can make _several_ words out of one argv[n]!
562 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000563 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000564 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000565 struct redir_struct *redirects; /* I/O redirections */
566};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000567/* Is there anything in this command at all? */
568#define IS_NULL_CMD(cmd) \
569 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
570
Eric Andersen25f27032001-04-26 23:22:31 +0000571struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000572 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000573 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000574 int alive_cmds; /* number of commands running (not exited) */
575 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000576#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000577 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000578 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000579 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000580#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000581 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000582 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000583 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
584 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000585};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000586typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100587 PIPE_SEQ = 0,
588 PIPE_AND = 1,
589 PIPE_OR = 2,
590 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000591} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000592/* Is there anything in this pipe at all? */
593#define IS_NULL_PIPE(pi) \
594 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000595
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000596/* This holds pointers to the various results of parsing */
597struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000598 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000599 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000600 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000601 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000602 /* last command in pipe (being constructed right now) */
603 struct command *command;
604 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000605 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000606#if !BB_MMU
607 o_string as_string;
608#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000609#if HAS_KEYWORDS
610 smallint ctx_res_w;
611 smallint ctx_inverted; /* "! cmd | cmd" */
612#if ENABLE_HUSH_CASE
613 smallint ctx_dsemicolon; /* ";;" seen */
614#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000615 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
616 int old_flag;
617 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000618 * example: "if pipe1; pipe2; then pipe3; fi"
619 * when we see "if" or "then", we malloc and copy current context,
620 * and make ->stack point to it. then we parse pipeN.
621 * when closing "then" / fi" / whatever is found,
622 * we move list_head into ->stack->command->group,
623 * copy ->stack into current context, and delete ->stack.
624 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000625 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000626 struct parse_context *stack;
627#endif
628};
629
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000630/* On program start, environ points to initial environment.
631 * putenv adds new pointers into it, unsetenv removes them.
632 * Neither of these (de)allocates the strings.
633 * setenv allocates new strings in malloc space and does putenv,
634 * and thus setenv is unusable (leaky) for shell's purposes */
635#define setenv(...) setenv_is_leaky_dont_use()
636struct variable {
637 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000638 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200639#if ENABLE_HUSH_LOCAL
640 unsigned func_nest_level;
641#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000642 int max_len; /* if > 0, name is part of initial env; else name is malloced */
643 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000644 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000645};
646
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000647enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000648 BC_BREAK = 1,
649 BC_CONTINUE = 2,
650};
651
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000652#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000653struct function {
654 struct function *next;
655 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000656 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000657 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200658# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000659 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200660# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000661};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000662#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000663
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000664
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100665/* set -/+o OPT support. (TODO: make it optional)
666 * bash supports the following opts:
667 * allexport off
668 * braceexpand on
669 * emacs on
670 * errexit off
671 * errtrace off
672 * functrace off
673 * hashall on
674 * histexpand off
675 * history on
676 * ignoreeof off
677 * interactive-comments on
678 * keyword off
679 * monitor on
680 * noclobber off
681 * noexec off
682 * noglob off
683 * nolog off
684 * notify off
685 * nounset off
686 * onecmd off
687 * physical off
688 * pipefail off
689 * posix off
690 * privileged off
691 * verbose off
692 * vi off
693 * xtrace off
694 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800695static const char o_opt_strings[] ALIGN1 =
696 "pipefail\0"
697 "noexec\0"
698#if ENABLE_HUSH_MODE_X
699 "xtrace\0"
700#endif
701 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100702enum {
703 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800704 OPT_O_NOEXEC,
705#if ENABLE_HUSH_MODE_X
706 OPT_O_XTRACE,
707#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100708 NUM_OPT_O
709};
710
711
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200712struct FILE_list {
713 struct FILE_list *next;
714 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200715 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200716};
717
718
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000719/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000720/* Sorted roughly by size (smaller offsets == smaller code) */
721struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000722 /* interactive_fd != 0 means we are an interactive shell.
723 * If we are, then saved_tty_pgrp can also be != 0, meaning
724 * that controlling tty is available. With saved_tty_pgrp == 0,
725 * job control still works, but terminal signals
726 * (^C, ^Z, ^Y, ^\) won't work at all, and background
727 * process groups can only be created with "cmd &".
728 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
729 * to give tty to the foreground process group,
730 * and will take it back when the group is stopped (^Z)
731 * or killed (^C).
732 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000733#if ENABLE_HUSH_INTERACTIVE
734 /* 'interactive_fd' is a fd# open to ctty, if we have one
735 * _AND_ if we decided to act interactively */
736 int interactive_fd;
737 const char *PS1;
738 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000739# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000740#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000741# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000742#endif
743#if ENABLE_FEATURE_EDITING
744 line_input_t *line_input_state;
745#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000746 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200747 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000748 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200749#if ENABLE_HUSH_RANDOM_SUPPORT
750 random_t random_gen;
751#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000752#if ENABLE_HUSH_JOB
753 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000754 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000755 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000756 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400757# define G_saved_tty_pgrp (G.saved_tty_pgrp)
758#else
759# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000760#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100761 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100762#if ENABLE_HUSH_MODE_X
763# define G_x_mode (G.o_opt[OPT_O_XTRACE])
764#else
765# define G_x_mode 0
766#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000767 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000768#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000769 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000770#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000771#if ENABLE_HUSH_FUNCTIONS
772 /* 0: outside of a function (or sourced file)
773 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000774 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000775 */
776 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200777# define G_flag_return_in_progress (G.flag_return_in_progress)
778#else
779# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000780#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000781 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000782 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000783 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000784 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000785 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000786 /* how many non-NULL argv's we have. NB: $# + 1 */
787 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000788 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000789#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000790 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000791#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000792#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000793 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000794 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000795#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000796 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000797 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200798 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200799 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000800#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000801 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200802# if ENABLE_HUSH_LOCAL
803 struct variable **shadowed_vars_pp;
804 unsigned func_nest_level;
805# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000806#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000807 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200808#if ENABLE_HUSH_FAST
809 unsigned count_SIGCHLD;
810 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200811 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200812#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200813 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200814 /* Which signals have non-DFL handler (even with no traps set)?
815 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200816 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200817 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200818 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200819 * Other than these two times, never modified.
820 */
821 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200822#if ENABLE_HUSH_JOB
823 unsigned fatal_sig_mask;
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200824# define G_fatal_sig_mask G.fatal_sig_mask
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200825#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200826# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200827#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000828 char **traps; /* char *traps[NSIG] */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200829 sigset_t pending_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000830#if HUSH_DEBUG
831 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000832 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000833#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200834 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200835#if ENABLE_FEATURE_EDITING
836 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
837#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000838};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000839#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000840/* Not #defining name to G.name - this quickly gets unwieldy
841 * (too many defines). Also, I actually prefer to see when a variable
842 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000843#define INIT_G() do { \
844 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200845 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
846 sigfillset(&G.sa.sa_mask); \
847 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000848} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000849
850
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000851/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200852static int builtin_cd(char **argv) FAST_FUNC;
853static int builtin_echo(char **argv) FAST_FUNC;
854static int builtin_eval(char **argv) FAST_FUNC;
855static int builtin_exec(char **argv) FAST_FUNC;
856static int builtin_exit(char **argv) FAST_FUNC;
857static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000858#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200859static int builtin_fg_bg(char **argv) FAST_FUNC;
860static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000861#endif
862#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200863static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000864#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200865#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200866static int builtin_history(char **argv) FAST_FUNC;
867#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200868#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200869static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200870#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000871#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200872static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000873#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400874#if ENABLE_PRINTF
875static int builtin_printf(char **argv) FAST_FUNC;
876#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200877static int builtin_pwd(char **argv) FAST_FUNC;
878static int builtin_read(char **argv) FAST_FUNC;
879static int builtin_set(char **argv) FAST_FUNC;
880static int builtin_shift(char **argv) FAST_FUNC;
881static int builtin_source(char **argv) FAST_FUNC;
882static int builtin_test(char **argv) FAST_FUNC;
883static int builtin_trap(char **argv) FAST_FUNC;
884static int builtin_type(char **argv) FAST_FUNC;
885static int builtin_true(char **argv) FAST_FUNC;
886static int builtin_umask(char **argv) FAST_FUNC;
887static int builtin_unset(char **argv) FAST_FUNC;
888static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000889#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200890static int builtin_break(char **argv) FAST_FUNC;
891static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000892#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000893#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200894static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000895#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000896
897/* Table of built-in functions. They can be forked or not, depending on
898 * context: within pipes, they fork. As simple commands, they do not.
899 * When used in non-forking context, they can change global variables
900 * in the parent shell process. If forked, of course they cannot.
901 * For example, 'unset foo | whatever' will parse and run, but foo will
902 * still be set at the end. */
903struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100904 const char *b_cmd;
905 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000906#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100907 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200908# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000909#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200910# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000911#endif
912};
913
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200914static const struct built_in_command bltins1[] = {
915 BLTIN("." , builtin_source , "Run commands in a file"),
916 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000917#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200918 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000919#endif
920#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200921 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000922#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200923 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000924#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200925 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000926#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200927 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
928 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
929 BLTIN("exit" , builtin_exit , "Exit"),
930 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000931#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200932 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000933#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000934#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200935 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000936#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200937#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200938 BLTIN("history" , builtin_history , "Show command history"),
939#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000940#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200941 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000942#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200943#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200944 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200945#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000946#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200947 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000948#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200949 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000950#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200951 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000952#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200953 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
954 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200955#if ENABLE_HUSH_BASH_COMPAT
956 BLTIN("source" , builtin_source , "Run commands in a file"),
957#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200958 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko2bba5912014-03-14 12:43:57 +0100959 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100960 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100961 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200962 BLTIN("umask" , builtin_umask , "Set file creation mask"),
963 BLTIN("unset" , builtin_unset , "Unset variables"),
964 BLTIN("wait" , builtin_wait , "Wait for process"),
965};
966/* For now, echo and test are unconditionally enabled.
967 * Maybe make it configurable? */
968static const struct built_in_command bltins2[] = {
969 BLTIN("[" , builtin_test , NULL),
970 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400971#if ENABLE_PRINTF
972 BLTIN("printf" , builtin_printf , NULL),
973#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200974 BLTIN("pwd" , builtin_pwd , NULL),
975 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000976};
977
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000978
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000979/* Debug printouts.
980 */
981#if HUSH_DEBUG
982/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100983# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000984# define debug_enter() (G.debug_indent++)
985# define debug_leave() (G.debug_indent--)
986#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200987# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000988# define debug_enter() ((void)0)
989# define debug_leave() ((void)0)
990#endif
991
992#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100993# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000994#endif
995
996#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100997# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000998#endif
999
1000#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001001#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001002#endif
1003
1004#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001005# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001006#endif
1007
1008#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001009# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001010# define DEBUG_JOBS 1
1011#else
1012# define DEBUG_JOBS 0
1013#endif
1014
1015#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001016# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001017# define DEBUG_EXPAND 1
1018#else
1019# define DEBUG_EXPAND 0
1020#endif
1021
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001022#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001023# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001024#endif
1025
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001026#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001027# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001028# define DEBUG_GLOB 1
1029#else
1030# define DEBUG_GLOB 0
1031#endif
1032
1033#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001034# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001035#endif
1036
1037#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001038# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001039#endif
1040
1041#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001042# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001043# define DEBUG_CLEAN 1
1044#else
1045# define DEBUG_CLEAN 0
1046#endif
1047
1048#if DEBUG_EXPAND
1049static void debug_print_strings(const char *prefix, char **vv)
1050{
1051 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001052 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001053 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001054 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001055}
1056#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001057# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001058#endif
1059
1060
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001061/* Leak hunting. Use hush_leaktool.sh for post-processing.
1062 */
1063#if LEAK_HUNTING
1064static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001065{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001066 void *ptr = xmalloc((size + 0xff) & ~0xff);
1067 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1068 return ptr;
1069}
1070static void *xxrealloc(int lineno, void *ptr, size_t size)
1071{
1072 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1073 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1074 return ptr;
1075}
1076static char *xxstrdup(int lineno, const char *str)
1077{
1078 char *ptr = xstrdup(str);
1079 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1080 return ptr;
1081}
1082static void xxfree(void *ptr)
1083{
1084 fdprintf(2, "free %p\n", ptr);
1085 free(ptr);
1086}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001087# define xmalloc(s) xxmalloc(__LINE__, s)
1088# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1089# define xstrdup(s) xxstrdup(__LINE__, s)
1090# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001091#endif
1092
1093
1094/* Syntax and runtime errors. They always abort scripts.
1095 * In interactive use they usually discard unparsed and/or unexecuted commands
1096 * and return to the prompt.
1097 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1098 */
1099#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001100# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001101# define syntax_error(lineno, msg) syntax_error(msg)
1102# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1103# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1104# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1105# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001106#endif
1107
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001108static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001109{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001110 va_list p;
1111
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001112#if HUSH_DEBUG >= 2
1113 bb_error_msg("hush.c:%u", lineno);
1114#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001115 va_start(p, fmt);
1116 bb_verror_msg(fmt, p, NULL);
1117 va_end(p);
1118 if (!G_interactive_fd)
1119 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001120}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001121
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001122static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001123{
1124 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001125 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001126 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001127 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001128}
1129
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001130static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001131{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001132 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001133}
1134
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001135static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001136{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001137 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001138}
1139
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001140static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001141{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001142 char msg[2] = { ch, '\0' };
1143 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001144}
1145
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001146static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001147{
1148 char msg[2];
1149 msg[0] = ch;
1150 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001151 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001152}
1153
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001154#if HUSH_DEBUG < 2
1155# undef die_if_script
1156# undef syntax_error
1157# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001158# undef syntax_error_unterm_ch
1159# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001160# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001161#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001162# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001163# define syntax_error(msg) syntax_error(__LINE__, msg)
1164# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1165# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1166# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1167# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001168#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001169
Denis Vlasenko552433b2009-04-04 19:29:21 +00001170
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001171#if ENABLE_HUSH_INTERACTIVE
1172static void cmdedit_update_prompt(void);
1173#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001174# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001175#endif
1176
1177
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001178/* Utility functions
1179 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001180/* Replace each \x with x in place, return ptr past NUL. */
1181static char *unbackslash(char *src)
1182{
Denys Vlasenko71885402009-09-24 01:44:13 +02001183 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001184 while (1) {
1185 if (*src == '\\')
1186 src++;
1187 if ((*dst++ = *src++) == '\0')
1188 break;
1189 }
1190 return dst;
1191}
1192
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001193static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001194{
1195 int i;
1196 unsigned count1;
1197 unsigned count2;
1198 char **v;
1199
1200 v = strings;
1201 count1 = 0;
1202 if (v) {
1203 while (*v) {
1204 count1++;
1205 v++;
1206 }
1207 }
1208 count2 = 0;
1209 v = add;
1210 while (*v) {
1211 count2++;
1212 v++;
1213 }
1214 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1215 v[count1 + count2] = NULL;
1216 i = count2;
1217 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001218 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001219 return v;
1220}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001221#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001222static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1223{
1224 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1225 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1226 return ptr;
1227}
1228#define add_strings_to_strings(strings, add, need_to_dup) \
1229 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1230#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001231
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001232/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001233static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001234{
1235 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001236 v[0] = add;
1237 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001238 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001239}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001240#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001241static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1242{
1243 char **ptr = add_string_to_strings(strings, add);
1244 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1245 return ptr;
1246}
1247#define add_string_to_strings(strings, add) \
1248 xx_add_string_to_strings(__LINE__, strings, add)
1249#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001250
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001251static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001252{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001253 char **v;
1254
1255 if (!strings)
1256 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001257 v = strings;
1258 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001259 free(*v);
1260 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001261 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001262 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001263}
1264
Denis Vlasenko76d50412008-06-10 16:19:39 +00001265
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001266static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1267{
1268 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1269 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1270 if (newfd < 0) {
1271 /* fd was not open? */
1272 if (errno == EBADF)
1273 return fd;
1274 xfunc_die();
1275 }
1276 close(fd);
1277 return newfd;
1278}
1279
1280
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001281/* Manipulating the list of open FILEs */
1282static FILE *remember_FILE(FILE *fp)
1283{
1284 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001285 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001286 n->next = G.FILE_list;
1287 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001288 n->fp = fp;
1289 n->fd = fileno(fp);
1290 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001291 }
1292 return fp;
1293}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001294static void fclose_and_forget(FILE *fp)
1295{
1296 struct FILE_list **pp = &G.FILE_list;
1297 while (*pp) {
1298 struct FILE_list *cur = *pp;
1299 if (cur->fp == fp) {
1300 *pp = cur->next;
1301 free(cur);
1302 break;
1303 }
1304 pp = &cur->next;
1305 }
1306 fclose(fp);
1307}
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001308static int save_FILEs_on_redirect(int fd)
1309{
1310 struct FILE_list *fl = G.FILE_list;
1311 while (fl) {
1312 if (fd == fl->fd) {
1313 /* We use it only on script files, they are all CLOEXEC */
1314 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1315 return 1;
1316 }
1317 fl = fl->next;
1318 }
1319 return 0;
1320}
1321static void restore_redirected_FILEs(void)
1322{
1323 struct FILE_list *fl = G.FILE_list;
1324 while (fl) {
1325 int should_be = fileno(fl->fp);
1326 if (fl->fd != should_be) {
1327 xmove_fd(fl->fd, should_be);
1328 fl->fd = should_be;
1329 }
1330 fl = fl->next;
1331 }
1332}
1333#if ENABLE_FEATURE_SH_STANDALONE
1334static void close_all_FILE_list(void)
1335{
1336 struct FILE_list *fl = G.FILE_list;
1337 while (fl) {
1338 /* fclose would also free FILE object.
1339 * It is disastrous if we share memory with a vforked parent.
1340 * I'm not sure we never come here after vfork.
1341 * Therefore just close fd, nothing more.
1342 */
1343 /*fclose(fl->fp); - unsafe */
1344 close(fl->fd);
1345 fl = fl->next;
1346 }
1347}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001348#endif
1349
1350
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001351/* Helpers for setting new $n and restoring them back
1352 */
1353typedef struct save_arg_t {
1354 char *sv_argv0;
1355 char **sv_g_argv;
1356 int sv_g_argc;
1357 smallint sv_g_malloced;
1358} save_arg_t;
1359
1360static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1361{
1362 int n;
1363
1364 sv->sv_argv0 = argv[0];
1365 sv->sv_g_argv = G.global_argv;
1366 sv->sv_g_argc = G.global_argc;
1367 sv->sv_g_malloced = G.global_args_malloced;
1368
1369 argv[0] = G.global_argv[0]; /* retain $0 */
1370 G.global_argv = argv;
1371 G.global_args_malloced = 0;
1372
1373 n = 1;
1374 while (*++argv)
1375 n++;
1376 G.global_argc = n;
1377}
1378
1379static void restore_G_args(save_arg_t *sv, char **argv)
1380{
1381 char **pp;
1382
1383 if (G.global_args_malloced) {
1384 /* someone ran "set -- arg1 arg2 ...", undo */
1385 pp = G.global_argv;
1386 while (*++pp) /* note: does not free $0 */
1387 free(*pp);
1388 free(G.global_argv);
1389 }
1390 argv[0] = sv->sv_argv0;
1391 G.global_argv = sv->sv_g_argv;
1392 G.global_argc = sv->sv_g_argc;
1393 G.global_args_malloced = sv->sv_g_malloced;
1394}
1395
1396
Denis Vlasenkod5762932009-03-31 11:22:57 +00001397/* Basic theory of signal handling in shell
1398 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001399 * This does not describe what hush does, rather, it is current understanding
1400 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001401 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1402 *
1403 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1404 * is finished or backgrounded. It is the same in interactive and
1405 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001406 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001407 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001408 * backgrounds (i.e. stops) or kills all members of currently running
1409 * pipe.
1410 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001411 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001412 * or by SIGINT in interactive shell.
1413 *
1414 * Trap handlers will execute even within trap handlers. (right?)
1415 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001416 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1417 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001418 *
1419 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001420 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001421 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001422 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001423 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001424 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001425 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001426 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001427 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001428 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001429 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001430 *
1431 * SIGQUIT: ignore
1432 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001433 * SIGHUP (interactive):
1434 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001435 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001436 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1437 * that all pipe members are stopped. Try this in bash:
1438 * while :; do :; done - ^Z does not background it
1439 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001440 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001441 * of the command line, show prompt. NB: ^C does not send SIGINT
1442 * to interactive shell while shell is waiting for a pipe,
1443 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001444 * Example 1: this waits 5 sec, but does not execute ls:
1445 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1446 * Example 2: this does not wait and does not execute ls:
1447 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1448 * Example 3: this does not wait 5 sec, but executes ls:
1449 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001450 * Example 4: this does not wait and does not execute ls:
1451 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001452 *
1453 * (What happens to signals which are IGN on shell start?)
1454 * (What happens with signal mask on shell start?)
1455 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001456 * Old implementation
1457 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001458 * We use in-kernel pending signal mask to determine which signals were sent.
1459 * We block all signals which we don't want to take action immediately,
1460 * i.e. we block all signals which need to have special handling as described
1461 * above, and all signals which have traps set.
1462 * After each pipe execution, we extract any pending signals via sigtimedwait()
1463 * and act on them.
1464 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001465 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001466 * sigset_t blocked_set: current blocked signal set
1467 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001468 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001469 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001470 * "trap 'cmd' SIGxxx":
1471 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001472 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001473 * unblock signals with special interactive handling
1474 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001475 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001476 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001477 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001478 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001479 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001480 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001481 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001482 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001483 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001484 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001485 * Standard says "When a subshell is entered, traps that are not being ignored
1486 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001487 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001488 *
1489 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001490 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001491 * masked signals are not visible!
1492 *
1493 * New implementation
1494 * ==================
1495 * We record each signal we are interested in by installing signal handler
1496 * for them - a bit like emulating kernel pending signal mask in userspace.
1497 * We are interested in: signals which need to have special handling
1498 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001499 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001500 * After each pipe execution, we extract any pending signals
1501 * and act on them.
1502 *
1503 * unsigned special_sig_mask: a mask of shell-special signals.
1504 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1505 * char *traps[sig] if trap for sig is set (even if it's '').
1506 * sigset_t pending_set: set of sigs we received.
1507 *
1508 * "trap - SIGxxx":
1509 * if sig is in special_sig_mask, set handler back to:
1510 * record_pending_signo, or to IGN if it's a tty stop signal
1511 * if sig is in fatal_sig_mask, set handler back to sigexit.
1512 * else: set handler back to SIG_DFL
1513 * "trap 'cmd' SIGxxx":
1514 * set handler to record_pending_signo.
1515 * "trap '' SIGxxx":
1516 * set handler to SIG_IGN.
1517 * after [v]fork, if we plan to be a shell:
1518 * set signals with special interactive handling to SIG_DFL
1519 * (because child shell is not interactive),
1520 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1521 * after [v]fork, if we plan to exec:
1522 * POSIX says fork clears pending signal mask in child - no need to clear it.
1523 *
1524 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1525 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1526 *
1527 * Note (compat):
1528 * Standard says "When a subshell is entered, traps that are not being ignored
1529 * are set to the default actions". bash interprets it so that traps which
1530 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001531 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001532enum {
1533 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001534 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001535 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001536 | (1 << SIGHUP)
1537 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001538 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001539#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001540 | (1 << SIGTTIN)
1541 | (1 << SIGTTOU)
1542 | (1 << SIGTSTP)
1543#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001544 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001545};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001546
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001547static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001548{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001549 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001550#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001551 if (sig == SIGCHLD) {
1552 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001553//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 +02001554 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001555#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001556}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001557
Denys Vlasenko0806e402011-05-12 23:06:20 +02001558static sighandler_t install_sighandler(int sig, sighandler_t handler)
1559{
1560 struct sigaction old_sa;
1561
1562 /* We could use signal() to install handlers... almost:
1563 * except that we need to mask ALL signals while handlers run.
1564 * I saw signal nesting in strace, race window isn't small.
1565 * SA_RESTART is also needed, but in Linux, signal()
1566 * sets SA_RESTART too.
1567 */
1568 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1569 /* sigfillset(&G.sa.sa_mask); - already done */
1570 /* G.sa.sa_flags = SA_RESTART; - already done */
1571 G.sa.sa_handler = handler;
1572 sigaction(sig, &G.sa, &old_sa);
1573 return old_sa.sa_handler;
1574}
1575
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001576static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001577
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001578static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001579static void restore_ttypgrp_and__exit(void)
1580{
1581 /* xfunc has failed! die die die */
1582 /* no EXIT traps, this is an escape hatch! */
1583 G.exiting = 1;
1584 hush_exit(xfunc_error_retval);
1585}
1586
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001587#if ENABLE_HUSH_JOB
1588
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001589/* Needed only on some libc:
1590 * It was observed that on exit(), fgetc'ed buffered data
1591 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1592 * With the net effect that even after fork(), not vfork(),
1593 * exit() in NOEXECed applet in "sh SCRIPT":
1594 * noexec_applet_here
1595 * echo END_OF_SCRIPT
1596 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1597 * This makes "echo END_OF_SCRIPT" executed twice.
1598 * Similar problems can be seen with die_if_script() -> xfunc_die()
1599 * and in `cmd` handling.
1600 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1601 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001602static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001603static void fflush_and__exit(void)
1604{
1605 fflush_all();
1606 _exit(xfunc_error_retval);
1607}
1608
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001609/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001610# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001611/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001612# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001613
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001614/* Restores tty foreground process group, and exits.
1615 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001616 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001617 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001618 * We also call it if xfunc is exiting.
1619 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001620static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001621static void sigexit(int sig)
1622{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001623 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001624 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001625 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1626 /* Disable all signals: job control, SIGPIPE, etc.
1627 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1628 */
1629 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001630 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001631 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001632
1633 /* Not a signal, just exit */
1634 if (sig <= 0)
1635 _exit(- sig);
1636
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001637 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001638}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001639#else
1640
Denys Vlasenko8391c482010-05-22 17:50:43 +02001641# define disable_restore_tty_pgrp_on_exit() ((void)0)
1642# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001643
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001644#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001645
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001646static sighandler_t pick_sighandler(unsigned sig)
1647{
1648 sighandler_t handler = SIG_DFL;
1649 if (sig < sizeof(unsigned)*8) {
1650 unsigned sigmask = (1 << sig);
1651
1652#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001653 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001654 if (G_fatal_sig_mask & sigmask)
1655 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001656 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001657#endif
1658 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001659 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001660 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001661 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001662 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001663 * in an endless loop when we try to do some
1664 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001665 */
1666 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1667 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001668 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001669 }
1670 return handler;
1671}
1672
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001673/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001674static void hush_exit(int exitcode)
1675{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001676#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1677 save_history(G.line_input_state);
1678#endif
1679
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001680 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001681 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001682 char *argv[3];
1683 /* argv[0] is unused */
1684 argv[1] = G.traps[0];
1685 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001686 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001687 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001688 * "trap" will still show it, if executed
1689 * in the handler */
1690 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001691 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001692
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001693#if ENABLE_FEATURE_CLEAN_UP
1694 {
1695 struct variable *cur_var;
1696 if (G.cwd != bb_msg_unknown)
1697 free((char*)G.cwd);
1698 cur_var = G.top_var;
1699 while (cur_var) {
1700 struct variable *tmp = cur_var;
1701 if (!cur_var->max_len)
1702 free(cur_var->varstr);
1703 cur_var = cur_var->next;
1704 free(tmp);
1705 }
1706 }
1707#endif
1708
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001709 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001710#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001711 sigexit(- (exitcode & 0xff));
1712#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001713 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001714#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001715}
1716
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001717
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001718//TODO: return a mask of ALL handled sigs?
1719static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001720{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001721 int last_sig = 0;
1722
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001723 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001724 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001725
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001726 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001727 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001728 sig = 0;
1729 do {
1730 sig++;
1731 if (sigismember(&G.pending_set, sig)) {
1732 sigdelset(&G.pending_set, sig);
1733 goto got_sig;
1734 }
1735 } while (sig < NSIG);
1736 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001737 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001738 if (G.traps && G.traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001739 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001740 if (G.traps[sig][0]) {
1741 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001742 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001743 char *argv[3];
1744 /* argv[0] is unused */
1745 argv[1] = G.traps[sig];
1746 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001747 save_rcode = G.last_exitcode;
1748 builtin_eval(argv);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01001749//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001750 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001751 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001752 } /* else: "" trap, ignoring signal */
1753 continue;
1754 }
1755 /* not a trap: special action */
1756 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001757 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001758 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001759 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001760 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001761 break;
1762#if ENABLE_HUSH_JOB
1763 case SIGHUP: {
1764 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001765 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001766 /* bash is observed to signal whole process groups,
1767 * not individual processes */
1768 for (job = G.job_list; job; job = job->next) {
1769 if (job->pgrp <= 0)
1770 continue;
1771 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1772 if (kill(- job->pgrp, SIGHUP) == 0)
1773 kill(- job->pgrp, SIGCONT);
1774 }
1775 sigexit(SIGHUP);
1776 }
1777#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001778#if ENABLE_HUSH_FAST
1779 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001780 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001781 G.count_SIGCHLD++;
1782//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1783 /* Note:
1784 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1785 * This simplifies wait builtin a bit.
1786 */
1787 break;
1788#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001789 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001790 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001791 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001792 /* Note:
1793 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1794 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001795 * in interactive shell, because TERM is ignored.
1796 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001797 break;
1798 }
1799 }
1800 return last_sig;
1801}
1802
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001803
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001804static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001805{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001806 if (force || G.cwd == NULL) {
1807 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1808 * we must not try to free(bb_msg_unknown) */
1809 if (G.cwd == bb_msg_unknown)
1810 G.cwd = NULL;
1811 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1812 if (!G.cwd)
1813 G.cwd = bb_msg_unknown;
1814 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001815 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001816}
1817
Denis Vlasenko83506862007-11-23 13:11:42 +00001818
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001819/*
1820 * Shell and environment variable support
1821 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001822static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001823{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001824 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001825 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001826
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001827 pp = &G.top_var;
1828 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001829 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001830 return pp;
1831 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001832 }
1833 return NULL;
1834}
1835
Denys Vlasenko03dad222010-01-12 23:29:57 +01001836static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001837{
Denys Vlasenko29082232010-07-16 13:52:32 +02001838 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001839 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001840
1841 if (G.expanded_assignments) {
1842 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001843 while (*cpp) {
1844 char *cp = *cpp;
1845 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1846 return cp + len + 1;
1847 cpp++;
1848 }
1849 }
1850
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001851 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001852 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001853 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001854
Denys Vlasenkodea47882009-10-09 15:40:49 +02001855 if (strcmp(name, "PPID") == 0)
1856 return utoa(G.root_ppid);
1857 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001858#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001859 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001860 return utoa(next_random(&G.random_gen));
1861#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001862 return NULL;
1863}
1864
1865/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001866 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001867 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001868 * 0: do not change export flag
1869 * (if creating new variable, flag will be 0)
1870 * 1: set export flag and putenv the variable
1871 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001872 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001873 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001874#if !BB_MMU && ENABLE_HUSH_LOCAL
1875/* all params are used */
1876#elif BB_MMU && ENABLE_HUSH_LOCAL
1877#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1878 set_local_var(str, flg_export, local_lvl)
1879#elif BB_MMU && !ENABLE_HUSH_LOCAL
1880#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001881 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001882#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1883#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1884 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001885#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001886static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001887{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001888 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001889 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001890 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001891 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001892 int name_len;
1893
Denis Vlasenko950bd722009-04-21 11:23:56 +00001894 eq_sign = strchr(str, '=');
1895 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001896 free(str);
1897 return -1;
1898 }
1899
Denis Vlasenko950bd722009-04-21 11:23:56 +00001900 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001901 var_pp = &G.top_var;
1902 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001903 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001904 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001905 continue;
1906 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001907
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001908 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001909 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001910#if !BB_MMU
1911 if (!flg_read_only)
1912#endif
1913 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001914 free(str);
1915 return -1;
1916 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001917 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001918 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1919 *eq_sign = '\0';
1920 unsetenv(str);
1921 *eq_sign = '=';
1922 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001923#if ENABLE_HUSH_LOCAL
1924 if (cur->func_nest_level < local_lvl) {
1925 /* New variable is declared as local,
1926 * and existing one is global, or local
1927 * from enclosing function.
1928 * Remove and save old one: */
1929 *var_pp = cur->next;
1930 cur->next = *G.shadowed_vars_pp;
1931 *G.shadowed_vars_pp = cur;
1932 /* bash 3.2.33(1) and exported vars:
1933 * # export z=z
1934 * # f() { local z=a; env | grep ^z; }
1935 * # f
1936 * z=a
1937 * # env | grep ^z
1938 * z=z
1939 */
1940 if (cur->flg_export)
1941 flg_export = 1;
1942 break;
1943 }
1944#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001945 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001946 free_and_exp:
1947 free(str);
1948 goto exp;
1949 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001950 if (cur->max_len != 0) {
1951 if (cur->max_len >= strlen(str)) {
1952 /* This one is from startup env, reuse space */
1953 strcpy(cur->varstr, str);
1954 goto free_and_exp;
1955 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001956 /* Can't reuse */
1957 cur->max_len = 0;
1958 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001959 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001960 /* max_len == 0 signifies "malloced" var, which we can
1961 * (and have to) free. But we can't free(cur->varstr) here:
1962 * if cur->flg_export is 1, it is in the environment.
1963 * We should either unsetenv+free, or wait until putenv,
1964 * then putenv(new)+free(old).
1965 */
1966 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001967 goto set_str_and_exp;
1968 }
1969
Denys Vlasenko295fef82009-06-03 12:47:26 +02001970 /* Not found - create new variable struct */
1971 cur = xzalloc(sizeof(*cur));
1972#if ENABLE_HUSH_LOCAL
1973 cur->func_nest_level = local_lvl;
1974#endif
1975 cur->next = *var_pp;
1976 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001977
1978 set_str_and_exp:
1979 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001980#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001981 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001982#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001983 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001984 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001985 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001986 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1987 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001988 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001989 if (flg_export == -1) {
1990 cur->flg_export = 0;
1991 /* unsetenv was already done */
1992 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001993 int i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001994 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001995 i = putenv(cur->varstr);
1996 /* only now we can free old exported malloced string */
1997 free(free_me);
1998 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001999 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002000 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002001 free(free_me);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002002 return 0;
2003}
2004
Denys Vlasenko6db47842009-09-05 20:15:17 +02002005/* Used at startup and after each cd */
2006static void set_pwd_var(int exp)
2007{
2008 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2009 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2010}
2011
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002012static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002013{
2014 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002015 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002016
2017 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002018 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002019 var_pp = &G.top_var;
2020 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002021 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2022 if (cur->flg_read_only) {
2023 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002024 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002025 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002026 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002027 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2028 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002029 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2030 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002031 if (!cur->max_len)
2032 free(cur->varstr);
2033 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002034 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002035 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002036 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002037 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002038 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002039}
2040
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002041static int unset_local_var(const char *name)
2042{
2043 return unset_local_var_len(name, strlen(name));
2044}
2045
2046static void unset_vars(char **strings)
2047{
2048 char **v;
2049
2050 if (!strings)
2051 return;
2052 v = strings;
2053 while (*v) {
2054 const char *eq = strchrnul(*v, '=');
2055 unset_local_var_len(*v, (int)(eq - *v));
2056 v++;
2057 }
2058 free(strings);
2059}
2060
Denys Vlasenko03dad222010-01-12 23:29:57 +01002061static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002062{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002063 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01002064 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002065}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002066
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002067
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002068/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002069 * Helpers for "var1=val1 var2=val2 cmd" feature
2070 */
2071static void add_vars(struct variable *var)
2072{
2073 struct variable *next;
2074
2075 while (var) {
2076 next = var->next;
2077 var->next = G.top_var;
2078 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002079 if (var->flg_export) {
2080 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002081 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002082 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002083 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002084 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002085 var = next;
2086 }
2087}
2088
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002089static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002090{
2091 char **s;
2092 struct variable *old = NULL;
2093
2094 if (!strings)
2095 return old;
2096 s = strings;
2097 while (*s) {
2098 struct variable *var_p;
2099 struct variable **var_pp;
2100 char *eq;
2101
2102 eq = strchr(*s, '=');
2103 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002104 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002105 if (var_pp) {
2106 /* Remove variable from global linked list */
2107 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002108 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002109 *var_pp = var_p->next;
2110 /* Add it to returned list */
2111 var_p->next = old;
2112 old = var_p;
2113 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002114 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002115 }
2116 s++;
2117 }
2118 return old;
2119}
2120
2121
2122/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002123 * Unicode helper
2124 */
2125static void reinit_unicode_for_hush(void)
2126{
2127 /* Unicode support should be activated even if LANG is set
2128 * _during_ shell execution, not only if it was set when
2129 * shell was started. Therefore, re-check LANG every time:
2130 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002131 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2132 || ENABLE_UNICODE_USING_LOCALE
2133 ) {
2134 const char *s = get_local_var_value("LC_ALL");
2135 if (!s) s = get_local_var_value("LC_CTYPE");
2136 if (!s) s = get_local_var_value("LANG");
2137 reinit_unicode(s);
2138 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002139}
2140
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002141/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002142 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002143 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002144
2145#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002146/* To test correct lineedit/interactive behavior, type from command line:
2147 * echo $P\
2148 * \
2149 * AT\
2150 * H\
2151 * \
2152 * It excercises a lot of corner cases.
2153 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002154static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002155{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002156 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002157 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002158 if (G.PS1 == NULL)
2159 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002160 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002161 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002162 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002163 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002164 if (G.PS2 == NULL)
2165 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002166}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002167static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002168{
2169 const char *prompt_str;
2170 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002171 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2172 /* Set up the prompt */
2173 if (promptmode == 0) { /* PS1 */
2174 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002175 /* bash uses $PWD value, even if it is set by user.
2176 * It uses current dir only if PWD is unset.
2177 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002178 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002179 prompt_str = G.PS1;
2180 } else
2181 prompt_str = G.PS2;
2182 } else
2183 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002184 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002185 return prompt_str;
2186}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002187static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002188{
2189 int r;
2190 const char *prompt_str;
2191
2192 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002193# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002194 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002195 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002196 if (G.flag_SIGINT) {
2197 /* There was ^C'ed, make it look prettier: */
2198 bb_putchar('\n');
2199 G.flag_SIGINT = 0;
2200 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002201 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002202 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002203 r = read_line_input(G.line_input_state, prompt_str,
2204 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2205 /*timeout*/ -1
2206 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002207 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2208 if (r == 0) {
2209 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002210 raise(SIGINT);
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002211 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002212 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002213 if (r != 0 && !G.flag_SIGINT)
2214 break;
2215 /* ^C or SIGINT: repeat */
2216 G.last_exitcode = 128 + SIGINT;
2217 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002218 if (r < 0) {
2219 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002220 i->p = NULL;
2221 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002222 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002223 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002224 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002225 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002226# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002227 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002228 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002229 if (i->last_char == '\0' || i->last_char == '\n') {
2230 /* Why check_and_run_traps here? Try this interactively:
2231 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2232 * $ <[enter], repeatedly...>
2233 * Without check_and_run_traps, handler never runs.
2234 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002235 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002236 fputs(prompt_str, stdout);
2237 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002238 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002239//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002240 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002241 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2242 * no ^C masking happens during fgetc, no special code for ^C:
2243 * it generates SIGINT as usual.
2244 */
2245 check_and_run_traps();
2246 if (G.flag_SIGINT)
2247 G.last_exitcode = 128 + SIGINT;
2248 if (r != '\0')
2249 break;
2250 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002251 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002252# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002253}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002254/* This is the magic location that prints prompts
2255 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002256static int fgetc_interactive(struct in_str *i)
2257{
2258 int ch;
2259 /* If it's interactive stdin, get new line. */
2260 if (G_interactive_fd && i->file == stdin) {
2261 /* Returns first char (or EOF), the rest is in i->p[] */
2262 ch = get_user_input(i);
2263 i->promptmode = 1; /* PS2 */
2264 } else {
2265 /* Not stdin: script file, sourced file, etc */
2266 do ch = fgetc(i->file); while (ch == '\0');
2267 }
2268 return ch;
2269}
2270#else
2271static inline int fgetc_interactive(struct in_str *i)
2272{
2273 int ch;
2274 do ch = fgetc(i->file); while (ch == '\0');
2275 return ch;
2276}
2277#endif /* INTERACTIVE */
2278
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002279static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002280{
2281 int ch;
2282
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002283 if (!i->file) {
2284 /* string-based in_str */
2285 ch = (unsigned char)*i->p;
2286 if (ch != '\0') {
2287 i->p++;
2288 i->last_char = ch;
2289 return ch;
2290 }
2291 return EOF;
2292 }
2293
2294 /* FILE-based in_str */
2295
Denys Vlasenko4074d492016-09-30 01:49:53 +02002296#if ENABLE_FEATURE_EDITING
2297 /* This can be stdin, check line editing char[] buffer */
2298 if (i->p && *i->p != '\0') {
2299 ch = (unsigned char)*i->p++;
2300 goto out;
2301 }
2302#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002303 /* peek_buf[] is an int array, not char. Can contain EOF. */
2304 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002305 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002306 int ch2 = i->peek_buf[1];
2307 i->peek_buf[0] = ch2;
2308 if (ch2 == 0) /* very likely, avoid redundant write */
2309 goto out;
2310 i->peek_buf[1] = 0;
2311 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002312 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002313
Denys Vlasenko4074d492016-09-30 01:49:53 +02002314 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002315 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002316 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002317 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002318 return ch;
2319}
2320
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002321static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002322{
2323 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002324
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002325 if (!i->file) {
2326 /* string-based in_str */
2327 /* Doesn't report EOF on NUL. None of the callers care. */
2328 return (unsigned char)*i->p;
2329 }
2330
2331 /* FILE-based in_str */
2332
Denys Vlasenko4074d492016-09-30 01:49:53 +02002333#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002334 /* This can be stdin, check line editing char[] buffer */
2335 if (i->p && *i->p != '\0')
2336 return (unsigned char)*i->p;
2337#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002338 /* peek_buf[] is an int array, not char. Can contain EOF. */
2339 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002340 if (ch != 0)
2341 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002342
Denys Vlasenko4074d492016-09-30 01:49:53 +02002343 /* Need to get a new char */
2344 ch = fgetc_interactive(i);
2345 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2346
2347 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2348#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2349 if (i->p) {
2350 i->p -= 1;
2351 return ch;
2352 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002353#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002354 i->peek_buf[0] = ch;
2355 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002356 return ch;
2357}
2358
Denys Vlasenko4074d492016-09-30 01:49:53 +02002359/* Only ever called if i_peek() was called, and did not return EOF.
2360 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2361 * not end-of-line. Therefore we never need to read a new editing line here.
2362 */
2363static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002364{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002365 int ch;
2366
2367 /* There are two cases when i->p[] buffer exists.
2368 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002369 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002370 * In both cases, we know that i->p[0] exists and not NUL, and
2371 * the peek2 result is in i->p[1].
2372 */
2373 if (i->p)
2374 return (unsigned char)i->p[1];
2375
2376 /* Now we know it is a file-based in_str. */
2377
2378 /* peek_buf[] is an int array, not char. Can contain EOF. */
2379 /* Is there 2nd char? */
2380 ch = i->peek_buf[1];
2381 if (ch == 0) {
2382 /* We did not read it yet, get it now */
2383 do ch = fgetc(i->file); while (ch == '\0');
2384 i->peek_buf[1] = ch;
2385 }
2386
2387 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2388 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002389}
2390
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002391static void setup_file_in_str(struct in_str *i, FILE *f)
2392{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002393 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002394 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002395 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002396 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002397}
2398
2399static void setup_string_in_str(struct in_str *i, const char *s)
2400{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002401 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002402 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002403 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002404 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002405}
2406
2407
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002408/*
2409 * o_string support
2410 */
2411#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002412
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002413static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002414{
2415 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002416 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002417 if (o->data)
2418 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002419}
2420
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002421static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002422{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002423 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002424 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002425}
2426
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002427static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2428{
2429 free(o->data);
2430}
2431
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002432static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002433{
2434 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002435 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002436 o->data = xrealloc(o->data, 1 + o->maxlen);
2437 }
2438}
2439
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002440static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002441{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002442 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002443 if (o->length < o->maxlen) {
2444 /* likely. avoid o_grow_by() call */
2445 add:
2446 o->data[o->length] = ch;
2447 o->length++;
2448 o->data[o->length] = '\0';
2449 return;
2450 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002451 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002452 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002453}
2454
Denys Vlasenko657086a2016-09-29 18:07:42 +02002455#if 0
2456/* Valid only if we know o_string is not empty */
2457static void o_delchr(o_string *o)
2458{
2459 o->length--;
2460 o->data[o->length] = '\0';
2461}
2462#endif
2463
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002464static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002465{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002466 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002467 memcpy(&o->data[o->length], str, len);
2468 o->length += len;
2469 o->data[o->length] = '\0';
2470}
2471
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002472static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002473{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002474 o_addblock(o, str, strlen(str));
2475}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002476
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002477#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002478static void nommu_addchr(o_string *o, int ch)
2479{
2480 if (o)
2481 o_addchr(o, ch);
2482}
2483#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002484# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002485#endif
2486
2487static void o_addstr_with_NUL(o_string *o, const char *str)
2488{
2489 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002490}
2491
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002492/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002493 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002494 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2495 * Apparently, on unquoted $v bash still does globbing
2496 * ("v='*.txt'; echo $v" prints all .txt files),
2497 * but NOT brace expansion! Thus, there should be TWO independent
2498 * quoting mechanisms on $v expansion side: one protects
2499 * $v from brace expansion, and other additionally protects "$v" against globbing.
2500 * We have only second one.
2501 */
2502
Denys Vlasenko9e800222010-10-03 14:28:04 +02002503#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002504# define MAYBE_BRACES "{}"
2505#else
2506# define MAYBE_BRACES ""
2507#endif
2508
Eric Andersen25f27032001-04-26 23:22:31 +00002509/* My analysis of quoting semantics tells me that state information
2510 * is associated with a destination, not a source.
2511 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002512static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002513{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002514 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002515 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002516 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002517 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002518 o_grow_by(o, sz);
2519 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002520 o->data[o->length] = '\\';
2521 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002522 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002523 o->data[o->length] = ch;
2524 o->length++;
2525 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002526}
2527
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002528static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002529{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002530 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002531 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2532 && strchr("*?[\\" MAYBE_BRACES, ch)
2533 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002534 sz++;
2535 o->data[o->length] = '\\';
2536 o->length++;
2537 }
2538 o_grow_by(o, sz);
2539 o->data[o->length] = ch;
2540 o->length++;
2541 o->data[o->length] = '\0';
2542}
2543
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002544static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002545{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002546 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002547 char ch;
2548 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002549 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002550 if (ordinary_cnt > len) /* paranoia */
2551 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002552 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002553 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002554 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002555 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002556 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002557
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002558 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002559 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002560 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002561 sz++;
2562 o->data[o->length] = '\\';
2563 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002564 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002565 o_grow_by(o, sz);
2566 o->data[o->length] = ch;
2567 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002568 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002569 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002570}
2571
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002572static void o_addQblock(o_string *o, const char *str, int len)
2573{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002574 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002575 o_addblock(o, str, len);
2576 return;
2577 }
2578 o_addqblock(o, str, len);
2579}
2580
Denys Vlasenko38292b62010-09-05 14:49:40 +02002581static void o_addQstr(o_string *o, const char *str)
2582{
2583 o_addQblock(o, str, strlen(str));
2584}
2585
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002586/* A special kind of o_string for $VAR and `cmd` expansion.
2587 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002588 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002589 * list[i] contains an INDEX (int!) into this string data.
2590 * It means that if list[] needs to grow, data needs to be moved higher up
2591 * but list[i]'s need not be modified.
2592 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002593 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002594 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2595 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002596#if DEBUG_EXPAND || DEBUG_GLOB
2597static void debug_print_list(const char *prefix, o_string *o, int n)
2598{
2599 char **list = (char**)o->data;
2600 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2601 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002602
2603 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002604 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 +02002605 prefix, list, n, string_start, o->length, o->maxlen,
2606 !!(o->o_expflags & EXP_FLAG_GLOB),
2607 o->has_quoted_part,
2608 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002609 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002610 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002611 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2612 o->data + (int)(uintptr_t)list[i] + string_start,
2613 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002614 i++;
2615 }
2616 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002617 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002618 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002619 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002620 }
2621}
2622#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002623# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002624#endif
2625
2626/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2627 * in list[n] so that it points past last stored byte so far.
2628 * It returns n+1. */
2629static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002630{
2631 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002632 int string_start;
2633 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002634
2635 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002636 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2637 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002638 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002639 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002640 /* list[n] points to string_start, make space for 16 more pointers */
2641 o->maxlen += 0x10 * sizeof(list[0]);
2642 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002643 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002644 memmove(list + n + 0x10, list + n, string_len);
2645 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002646 } else {
2647 debug_printf_list("list[%d]=%d string_start=%d\n",
2648 n, string_len, string_start);
2649 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002650 } else {
2651 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002652 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2653 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002654 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2655 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002656 o->has_empty_slot = 0;
2657 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002658 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002659 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002660 return n + 1;
2661}
2662
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002663/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002664static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002665{
2666 char **list = (char**)o->data;
2667 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2668
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002669 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002670}
2671
Denys Vlasenko9e800222010-10-03 14:28:04 +02002672#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002673/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2674 * first, it processes even {a} (no commas), second,
2675 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002676 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002677 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002678
2679/* Helper */
2680static int glob_needed(const char *s)
2681{
2682 while (*s) {
2683 if (*s == '\\') {
2684 if (!s[1])
2685 return 0;
2686 s += 2;
2687 continue;
2688 }
2689 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2690 return 1;
2691 s++;
2692 }
2693 return 0;
2694}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002695/* Return pointer to next closing brace or to comma */
2696static const char *next_brace_sub(const char *cp)
2697{
2698 unsigned depth = 0;
2699 cp++;
2700 while (*cp != '\0') {
2701 if (*cp == '\\') {
2702 if (*++cp == '\0')
2703 break;
2704 cp++;
2705 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002706 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002707 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002708 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002709 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002710 depth++;
2711 }
2712
2713 return *cp != '\0' ? cp : NULL;
2714}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002715/* Recursive brace globber. Note: may garble pattern[]. */
2716static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002717{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002718 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002719 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002720 const char *next;
2721 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002722 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002723 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002724
2725 debug_printf_glob("glob_brace('%s')\n", pattern);
2726
2727 begin = pattern;
2728 while (1) {
2729 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002730 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002731 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002732 /* Find the first sub-pattern and at the same time
2733 * find the rest after the closing brace */
2734 next = next_brace_sub(begin);
2735 if (next == NULL) {
2736 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002737 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002738 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002739 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002740 /* "{abc}" with no commas - illegal
2741 * brace expr, disregard and skip it */
2742 begin = next + 1;
2743 continue;
2744 }
2745 break;
2746 }
2747 if (*begin == '\\' && begin[1] != '\0')
2748 begin++;
2749 begin++;
2750 }
2751 debug_printf_glob("begin:%s\n", begin);
2752 debug_printf_glob("next:%s\n", next);
2753
2754 /* Now find the end of the whole brace expression */
2755 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002756 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002757 rest = next_brace_sub(rest);
2758 if (rest == NULL) {
2759 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002760 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002761 }
2762 debug_printf_glob("rest:%s\n", rest);
2763 }
2764 rest_len = strlen(++rest) + 1;
2765
2766 /* We are sure the brace expression is well-formed */
2767
2768 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002769 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002770
2771 /* We have a brace expression. BEGIN points to the opening {,
2772 * NEXT points past the terminator of the first element, and REST
2773 * points past the final }. We will accumulate result names from
2774 * recursive runs for each brace alternative in the buffer using
2775 * GLOB_APPEND. */
2776
2777 p = begin + 1;
2778 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002779 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002780 memcpy(
2781 mempcpy(
2782 mempcpy(new_pattern_buf,
2783 /* We know the prefix for all sub-patterns */
2784 pattern, begin - pattern),
2785 p, next - p),
2786 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002787
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002788 /* Note: glob_brace() may garble new_pattern_buf[].
2789 * That's why we re-copy prefix every time (1st memcpy above).
2790 */
2791 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002792 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002793 /* We saw the last entry */
2794 break;
2795 }
2796 p = next + 1;
2797 next = next_brace_sub(next);
2798 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002799 free(new_pattern_buf);
2800 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002801
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002802 simple_glob:
2803 {
2804 int gr;
2805 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002806
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002807 memset(&globdata, 0, sizeof(globdata));
2808 gr = glob(pattern, 0, NULL, &globdata);
2809 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2810 if (gr != 0) {
2811 if (gr == GLOB_NOMATCH) {
2812 globfree(&globdata);
2813 /* NB: garbles parameter */
2814 unbackslash(pattern);
2815 o_addstr_with_NUL(o, pattern);
2816 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2817 return o_save_ptr_helper(o, n);
2818 }
2819 if (gr == GLOB_NOSPACE)
2820 bb_error_msg_and_die(bb_msg_memory_exhausted);
2821 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2822 * but we didn't specify it. Paranoia again. */
2823 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2824 }
2825 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2826 char **argv = globdata.gl_pathv;
2827 while (1) {
2828 o_addstr_with_NUL(o, *argv);
2829 n = o_save_ptr_helper(o, n);
2830 argv++;
2831 if (!*argv)
2832 break;
2833 }
2834 }
2835 globfree(&globdata);
2836 }
2837 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002838}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002839/* Performs globbing on last list[],
2840 * saving each result as a new list[].
2841 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002842static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002843{
2844 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002845
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002846 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002847 if (!o->data)
2848 return o_save_ptr_helper(o, n);
2849 pattern = o->data + o_get_last_ptr(o, n);
2850 debug_printf_glob("glob pattern '%s'\n", pattern);
2851 if (!glob_needed(pattern)) {
2852 /* unbackslash last string in o in place, fix length */
2853 o->length = unbackslash(pattern) - o->data;
2854 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2855 return o_save_ptr_helper(o, n);
2856 }
2857
2858 copy = xstrdup(pattern);
2859 /* "forget" pattern in o */
2860 o->length = pattern - o->data;
2861 n = glob_brace(copy, o, n);
2862 free(copy);
2863 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002864 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002865 return n;
2866}
2867
Denys Vlasenko238081f2010-10-03 14:26:26 +02002868#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002869
2870/* Helper */
2871static int glob_needed(const char *s)
2872{
2873 while (*s) {
2874 if (*s == '\\') {
2875 if (!s[1])
2876 return 0;
2877 s += 2;
2878 continue;
2879 }
2880 if (*s == '*' || *s == '[' || *s == '?')
2881 return 1;
2882 s++;
2883 }
2884 return 0;
2885}
2886/* Performs globbing on last list[],
2887 * saving each result as a new list[].
2888 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002889static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002890{
2891 glob_t globdata;
2892 int gr;
2893 char *pattern;
2894
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002895 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002896 if (!o->data)
2897 return o_save_ptr_helper(o, n);
2898 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002899 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002900 if (!glob_needed(pattern)) {
2901 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002902 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002903 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002904 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002905 return o_save_ptr_helper(o, n);
2906 }
2907
2908 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002909 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2910 * If we glob "*.\*" and don't find anything, we need
2911 * to fall back to using literal "*.*", but GLOB_NOCHECK
2912 * will return "*.\*"!
2913 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002914 gr = glob(pattern, 0, NULL, &globdata);
2915 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002916 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002917 if (gr == GLOB_NOMATCH) {
2918 globfree(&globdata);
2919 goto literal;
2920 }
2921 if (gr == GLOB_NOSPACE)
2922 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002923 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2924 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002925 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002926 }
2927 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2928 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002929 /* "forget" pattern in o */
2930 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002931 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002932 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002933 n = o_save_ptr_helper(o, n);
2934 argv++;
2935 if (!*argv)
2936 break;
2937 }
2938 }
2939 globfree(&globdata);
2940 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002941 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002942 return n;
2943}
2944
Denys Vlasenko238081f2010-10-03 14:26:26 +02002945#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002946
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002947/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002948 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002949static int o_save_ptr(o_string *o, int n)
2950{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002951 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002952 /* If o->has_empty_slot, list[n] was already globbed
2953 * (if it was requested back then when it was filled)
2954 * so don't do that again! */
2955 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002956 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002957 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002958 return o_save_ptr_helper(o, n);
2959}
2960
2961/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002962static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002963{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002964 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002965 int string_start;
2966
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002967 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2968 if (DEBUG_EXPAND)
2969 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002970 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002971 list = (char**)o->data;
2972 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2973 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002974 while (n) {
2975 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002976 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002977 }
2978 return list;
2979}
2980
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002981static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002982
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002983/* Returns pi->next - next pipe in the list */
2984static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002985{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002986 struct pipe *next;
2987 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002988
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002989 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002990 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002991 struct command *command;
2992 struct redir_struct *r, *rnext;
2993
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002994 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002995 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002996 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002997 if (DEBUG_CLEAN) {
2998 int a;
2999 char **p;
3000 for (a = 0, p = command->argv; *p; a++, p++) {
3001 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3002 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003003 }
3004 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003005 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003006 }
3007 /* not "else if": on syntax error, we may have both! */
3008 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003009 debug_printf_clean(" begin group (cmd_type:%d)\n",
3010 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003011 free_pipe_list(command->group);
3012 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003013 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003014 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003015 /* else is crucial here.
3016 * If group != NULL, child_func is meaningless */
3017#if ENABLE_HUSH_FUNCTIONS
3018 else if (command->child_func) {
3019 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3020 command->child_func->parent_cmd = NULL;
3021 }
3022#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003023#if !BB_MMU
3024 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003025 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003026#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003027 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003028 debug_printf_clean(" redirect %d%s",
3029 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003030 /* guard against the case >$FOO, where foo is unset or blank */
3031 if (r->rd_filename) {
3032 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3033 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003034 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003035 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003036 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003037 rnext = r->next;
3038 free(r);
3039 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003040 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003041 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003042 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003043 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003044#if ENABLE_HUSH_JOB
3045 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003046 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003047#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003048
3049 next = pi->next;
3050 free(pi);
3051 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003052}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003053
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003054static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003055{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003056 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003057#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003058 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003059#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003060 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003061 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003062 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003063}
3064
3065
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003066/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003067
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003068#ifndef debug_print_tree
3069static void debug_print_tree(struct pipe *pi, int lvl)
3070{
3071 static const char *const PIPE[] = {
3072 [PIPE_SEQ] = "SEQ",
3073 [PIPE_AND] = "AND",
3074 [PIPE_OR ] = "OR" ,
3075 [PIPE_BG ] = "BG" ,
3076 };
3077 static const char *RES[] = {
3078 [RES_NONE ] = "NONE" ,
3079# if ENABLE_HUSH_IF
3080 [RES_IF ] = "IF" ,
3081 [RES_THEN ] = "THEN" ,
3082 [RES_ELIF ] = "ELIF" ,
3083 [RES_ELSE ] = "ELSE" ,
3084 [RES_FI ] = "FI" ,
3085# endif
3086# if ENABLE_HUSH_LOOPS
3087 [RES_FOR ] = "FOR" ,
3088 [RES_WHILE] = "WHILE",
3089 [RES_UNTIL] = "UNTIL",
3090 [RES_DO ] = "DO" ,
3091 [RES_DONE ] = "DONE" ,
3092# endif
3093# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3094 [RES_IN ] = "IN" ,
3095# endif
3096# if ENABLE_HUSH_CASE
3097 [RES_CASE ] = "CASE" ,
3098 [RES_CASE_IN ] = "CASE_IN" ,
3099 [RES_MATCH] = "MATCH",
3100 [RES_CASE_BODY] = "CASE_BODY",
3101 [RES_ESAC ] = "ESAC" ,
3102# endif
3103 [RES_XXXX ] = "XXXX" ,
3104 [RES_SNTX ] = "SNTX" ,
3105 };
3106 static const char *const CMDTYPE[] = {
3107 "{}",
3108 "()",
3109 "[noglob]",
3110# if ENABLE_HUSH_FUNCTIONS
3111 "func()",
3112# endif
3113 };
3114
3115 int pin, prn;
3116
3117 pin = 0;
3118 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003119 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003120 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3121 prn = 0;
3122 while (prn < pi->num_cmds) {
3123 struct command *command = &pi->cmds[prn];
3124 char **argv = command->argv;
3125
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003126 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003127 lvl*2, "", prn,
3128 command->assignment_cnt);
3129 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003130 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003131 CMDTYPE[command->cmd_type],
3132 argv
3133# if !BB_MMU
3134 , " group_as_string:", command->group_as_string
3135# else
3136 , "", ""
3137# endif
3138 );
3139 debug_print_tree(command->group, lvl+1);
3140 prn++;
3141 continue;
3142 }
3143 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003144 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003145 argv++;
3146 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003147 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003148 prn++;
3149 }
3150 pi = pi->next;
3151 pin++;
3152 }
3153}
3154#endif /* debug_print_tree */
3155
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003156static struct pipe *new_pipe(void)
3157{
Eric Andersen25f27032001-04-26 23:22:31 +00003158 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003159 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003160 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003161 return pi;
3162}
3163
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003164/* Command (member of a pipe) is complete, or we start a new pipe
3165 * if ctx->command is NULL.
3166 * No errors possible here.
3167 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003168static int done_command(struct parse_context *ctx)
3169{
3170 /* The command is really already in the pipe structure, so
3171 * advance the pipe counter and make a new, null command. */
3172 struct pipe *pi = ctx->pipe;
3173 struct command *command = ctx->command;
3174
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003175#if 0 /* Instead we emit error message at run time */
3176 if (ctx->pending_redirect) {
3177 /* For example, "cmd >" (no filename to redirect to) */
3178 die_if_script("syntax error: %s", "invalid redirect");
3179 ctx->pending_redirect = NULL;
3180 }
3181#endif
3182
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003183 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003184 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003185 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003186 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003187 }
3188 pi->num_cmds++;
3189 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003190 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003191 } else {
3192 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3193 }
3194
3195 /* Only real trickiness here is that the uncommitted
3196 * command structure is not counted in pi->num_cmds. */
3197 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003198 ctx->command = command = &pi->cmds[pi->num_cmds];
3199 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003200 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003201 return pi->num_cmds; /* used only for 0/nonzero check */
3202}
3203
3204static void done_pipe(struct parse_context *ctx, pipe_style type)
3205{
3206 int not_null;
3207
3208 debug_printf_parse("done_pipe entered, followup %d\n", type);
3209 /* Close previous command */
3210 not_null = done_command(ctx);
3211 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003212#if HAS_KEYWORDS
3213 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3214 ctx->ctx_inverted = 0;
3215 ctx->pipe->res_word = ctx->ctx_res_w;
3216#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003217
3218 /* Without this check, even just <enter> on command line generates
3219 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003220 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003221 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003222#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003223 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003224#endif
3225#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003226 || ctx->ctx_res_w == RES_DONE
3227 || ctx->ctx_res_w == RES_FOR
3228 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003229#endif
3230#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003231 || ctx->ctx_res_w == RES_ESAC
3232#endif
3233 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003234 struct pipe *new_p;
3235 debug_printf_parse("done_pipe: adding new pipe: "
3236 "not_null:%d ctx->ctx_res_w:%d\n",
3237 not_null, ctx->ctx_res_w);
3238 new_p = new_pipe();
3239 ctx->pipe->next = new_p;
3240 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003241 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003242 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003243 * This is used to control execution.
3244 * RES_FOR and RES_IN are NOT sticky (needed to support
3245 * cases where variable or value happens to match a keyword):
3246 */
3247#if ENABLE_HUSH_LOOPS
3248 if (ctx->ctx_res_w == RES_FOR
3249 || ctx->ctx_res_w == RES_IN)
3250 ctx->ctx_res_w = RES_NONE;
3251#endif
3252#if ENABLE_HUSH_CASE
3253 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003254 ctx->ctx_res_w = RES_CASE_BODY;
3255 if (ctx->ctx_res_w == RES_CASE)
3256 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003257#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003258 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003259 /* Create the memory for command, roughly:
3260 * ctx->pipe->cmds = new struct command;
3261 * ctx->command = &ctx->pipe->cmds[0];
3262 */
3263 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003264 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003265 }
3266 debug_printf_parse("done_pipe return\n");
3267}
3268
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003269static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003270{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003271 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003272 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003273 /* Create the memory for command, roughly:
3274 * ctx->pipe->cmds = new struct command;
3275 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003276 */
3277 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003278}
3279
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003280/* If a reserved word is found and processed, parse context is modified
3281 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003282 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003283#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003284struct reserved_combo {
3285 char literal[6];
3286 unsigned char res;
3287 unsigned char assignment_flag;
3288 int flag;
3289};
3290enum {
3291 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003292# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003293 FLAG_IF = (1 << RES_IF ),
3294 FLAG_THEN = (1 << RES_THEN ),
3295 FLAG_ELIF = (1 << RES_ELIF ),
3296 FLAG_ELSE = (1 << RES_ELSE ),
3297 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003298# endif
3299# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003300 FLAG_FOR = (1 << RES_FOR ),
3301 FLAG_WHILE = (1 << RES_WHILE),
3302 FLAG_UNTIL = (1 << RES_UNTIL),
3303 FLAG_DO = (1 << RES_DO ),
3304 FLAG_DONE = (1 << RES_DONE ),
3305 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003306# endif
3307# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003308 FLAG_MATCH = (1 << RES_MATCH),
3309 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003310# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003311 FLAG_START = (1 << RES_XXXX ),
3312};
3313
3314static const struct reserved_combo* match_reserved_word(o_string *word)
3315{
Eric Andersen25f27032001-04-26 23:22:31 +00003316 /* Mostly a list of accepted follow-up reserved words.
3317 * FLAG_END means we are done with the sequence, and are ready
3318 * to turn the compound list into a command.
3319 * FLAG_START means the word must start a new compound list.
3320 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003321 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003322# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003323 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3324 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3325 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3326 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3327 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3328 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003329# endif
3330# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003331 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3332 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3333 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3334 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3335 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3336 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003337# endif
3338# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003339 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3340 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003341# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003342 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003343 const struct reserved_combo *r;
3344
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003345 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003346 if (strcmp(word->data, r->literal) == 0)
3347 return r;
3348 }
3349 return NULL;
3350}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003351/* Return 0: not a keyword, 1: keyword
3352 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003353static int reserved_word(o_string *word, struct parse_context *ctx)
3354{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003355# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003356 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003357 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003358 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003359# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003360 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003361
Denys Vlasenko38292b62010-09-05 14:49:40 +02003362 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003363 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003364 r = match_reserved_word(word);
3365 if (!r)
3366 return 0;
3367
3368 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003369# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003370 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3371 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003372 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003373 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003374# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003375 if (r->flag == 0) { /* '!' */
3376 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003377 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003378 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003379 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003380 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003381 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003382 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003383 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003384 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003385
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003386 old = xmalloc(sizeof(*old));
3387 debug_printf_parse("push stack %p\n", old);
3388 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003389 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003390 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003391 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003392 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003393 ctx->ctx_res_w = RES_SNTX;
3394 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003395 } else {
3396 /* "{...} fi" is ok. "{...} if" is not
3397 * Example:
3398 * if { echo foo; } then { echo bar; } fi */
3399 if (ctx->command->group)
3400 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003401 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003402
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003403 ctx->ctx_res_w = r->res;
3404 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003405 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003406 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003407
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003408 if (ctx->old_flag & FLAG_END) {
3409 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003410
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003411 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003412 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003413 old = ctx->stack;
3414 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003415 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003416# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003417 /* At this point, the compound command's string is in
3418 * ctx->as_string... except for the leading keyword!
3419 * Consider this example: "echo a | if true; then echo a; fi"
3420 * ctx->as_string will contain "true; then echo a; fi",
3421 * with "if " remaining in old->as_string!
3422 */
3423 {
3424 char *str;
3425 int len = old->as_string.length;
3426 /* Concatenate halves */
3427 o_addstr(&old->as_string, ctx->as_string.data);
3428 o_free_unsafe(&ctx->as_string);
3429 /* Find where leading keyword starts in first half */
3430 str = old->as_string.data + len;
3431 if (str > old->as_string.data)
3432 str--; /* skip whitespace after keyword */
3433 while (str > old->as_string.data && isalpha(str[-1]))
3434 str--;
3435 /* Ugh, we're done with this horrid hack */
3436 old->command->group_as_string = xstrdup(str);
3437 debug_printf_parse("pop, remembering as:'%s'\n",
3438 old->command->group_as_string);
3439 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003440# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003441 *ctx = *old; /* physical copy */
3442 free(old);
3443 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003444 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003445}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003446#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003447
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003448/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003449 * Normal return is 0. Syntax errors return 1.
3450 * Note: on return, word is reset, but not o_free'd!
3451 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003452static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003453{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003454 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003455
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003456 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003457 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003458 debug_printf_parse("done_word return 0: true null, ignored\n");
3459 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003460 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003461
Eric Andersen25f27032001-04-26 23:22:31 +00003462 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003463 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3464 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003465 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3466 * "2.7 Redirection
3467 * ...the word that follows the redirection operator
3468 * shall be subjected to tilde expansion, parameter expansion,
3469 * command substitution, arithmetic expansion, and quote
3470 * removal. Pathname expansion shall not be performed
3471 * on the word by a non-interactive shell; an interactive
3472 * shell may perform it, but shall do so only when
3473 * the expansion would result in one word."
3474 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003475 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003476 /* Cater for >\file case:
3477 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3478 * Same with heredocs:
3479 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3480 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003481 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3482 unbackslash(ctx->pending_redirect->rd_filename);
3483 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003484 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003485 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3486 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003487 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003488 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003489 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003490 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003491#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003492# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003493 if (ctx->ctx_dsemicolon
3494 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3495 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003496 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003497 /* ctx->ctx_res_w = RES_MATCH; */
3498 ctx->ctx_dsemicolon = 0;
3499 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003500# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003501 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003502# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003503 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3504 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003505# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003506# if ENABLE_HUSH_CASE
3507 && ctx->ctx_res_w != RES_CASE
3508# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003509 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003510 int reserved = reserved_word(word, ctx);
3511 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3512 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003513 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003514 debug_printf_parse("done_word return %d\n",
3515 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003516 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003517 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003518# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003519 if (strcmp(word->data, "[[") == 0) {
3520 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3521 }
3522 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003523# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003524 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003525#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003526 if (command->group) {
3527 /* "{ echo foo; } echo bar" - bad */
3528 syntax_error_at(word->data);
3529 debug_printf_parse("done_word return 1: syntax error, "
3530 "groups and arglists don't mix\n");
3531 return 1;
3532 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003533
3534 /* If this word wasn't an assignment, next ones definitely
3535 * can't be assignments. Even if they look like ones. */
3536 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3537 && word->o_assignment != WORD_IS_KEYWORD
3538 ) {
3539 word->o_assignment = NOT_ASSIGNMENT;
3540 } else {
3541 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3542 command->assignment_cnt++;
3543 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3544 }
3545 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3546 word->o_assignment = MAYBE_ASSIGNMENT;
3547 }
3548 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3549
Denys Vlasenko38292b62010-09-05 14:49:40 +02003550 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003551 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3552 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003553 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003554 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003555 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003556 char *p = word->data;
3557 while (p[0] == SPECIAL_VAR_SYMBOL
3558 && (p[1] & 0x7f) == '@'
3559 && p[2] == SPECIAL_VAR_SYMBOL
3560 ) {
3561 p += 3;
3562 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003563 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003564 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003565 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003566 }
Eric Andersen25f27032001-04-26 23:22:31 +00003567
Denis Vlasenko06810332007-05-21 23:30:54 +00003568#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003569 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003570 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003571 || !is_well_formed_var_name(command->argv[0], '\0')
3572 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003573 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003574 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003575 return 1;
3576 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003577 /* Force FOR to have just one word (variable name) */
3578 /* NB: basically, this makes hush see "for v in ..."
3579 * syntax as if it is "for v; in ...". FOR and IN become
3580 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003581 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003582 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003583#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003584#if ENABLE_HUSH_CASE
3585 /* Force CASE to have just one word */
3586 if (ctx->ctx_res_w == RES_CASE) {
3587 done_pipe(ctx, PIPE_SEQ);
3588 }
3589#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003590
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003591 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003592
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003593 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003594 return 0;
3595}
3596
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003597
3598/* Peek ahead in the input to find out if we have a "&n" construct,
3599 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003600 * Return:
3601 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3602 * REDIRFD_SYNTAX_ERR if syntax error,
3603 * REDIRFD_TO_FILE if no & was seen,
3604 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003605 */
3606#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003607#define parse_redir_right_fd(as_string, input) \
3608 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003609#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003610static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003611{
3612 int ch, d, ok;
3613
3614 ch = i_peek(input);
3615 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003616 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003617
3618 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003619 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003620 ch = i_peek(input);
3621 if (ch == '-') {
3622 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003623 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003624 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003625 }
3626 d = 0;
3627 ok = 0;
3628 while (ch != EOF && isdigit(ch)) {
3629 d = d*10 + (ch-'0');
3630 ok = 1;
3631 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003632 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003633 ch = i_peek(input);
3634 }
3635 if (ok) return d;
3636
3637//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3638
3639 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003640 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003641}
3642
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003643/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003644 */
3645static int parse_redirect(struct parse_context *ctx,
3646 int fd,
3647 redir_type style,
3648 struct in_str *input)
3649{
3650 struct command *command = ctx->command;
3651 struct redir_struct *redir;
3652 struct redir_struct **redirp;
3653 int dup_num;
3654
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003655 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003656 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003657 /* Check for a '>&1' type redirect */
3658 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3659 if (dup_num == REDIRFD_SYNTAX_ERR)
3660 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003661 } else {
3662 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003663 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003664 if (dup_num) { /* <<-... */
3665 ch = i_getch(input);
3666 nommu_addchr(&ctx->as_string, ch);
3667 ch = i_peek(input);
3668 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003669 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003670
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003671 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003672 int ch = i_peek(input);
3673 if (ch == '|') {
3674 /* >|FILE redirect ("clobbering" >).
3675 * Since we do not support "set -o noclobber" yet,
3676 * >| and > are the same for now. Just eat |.
3677 */
3678 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003679 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003680 }
3681 }
3682
3683 /* Create a new redir_struct and append it to the linked list */
3684 redirp = &command->redirects;
3685 while ((redir = *redirp) != NULL) {
3686 redirp = &(redir->next);
3687 }
3688 *redirp = redir = xzalloc(sizeof(*redir));
3689 /* redir->next = NULL; */
3690 /* redir->rd_filename = NULL; */
3691 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003692 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003693
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003694 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3695 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003696
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003697 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003698 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003699 /* Erik had a check here that the file descriptor in question
3700 * is legit; I postpone that to "run time"
3701 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003702 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3703 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003704 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003705#if 0 /* Instead we emit error message at run time */
3706 if (ctx->pending_redirect) {
3707 /* For example, "cmd > <file" */
3708 die_if_script("syntax error: %s", "invalid redirect");
3709 }
3710#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003711 /* Set ctx->pending_redirect, so we know what to do at the
3712 * end of the next parsed word. */
3713 ctx->pending_redirect = redir;
3714 }
3715 return 0;
3716}
3717
Eric Andersen25f27032001-04-26 23:22:31 +00003718/* If a redirect is immediately preceded by a number, that number is
3719 * supposed to tell which file descriptor to redirect. This routine
3720 * looks for such preceding numbers. In an ideal world this routine
3721 * needs to handle all the following classes of redirects...
3722 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3723 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3724 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3725 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003726 *
3727 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3728 * "2.7 Redirection
3729 * ... If n is quoted, the number shall not be recognized as part of
3730 * the redirection expression. For example:
3731 * echo \2>a
3732 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003733 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003734 *
3735 * A -1 return means no valid number was found,
3736 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003737 */
3738static int redirect_opt_num(o_string *o)
3739{
3740 int num;
3741
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003742 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003743 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003744 num = bb_strtou(o->data, NULL, 10);
3745 if (errno || num < 0)
3746 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003747 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003748 return num;
3749}
3750
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003751#if BB_MMU
3752#define fetch_till_str(as_string, input, word, skip_tabs) \
3753 fetch_till_str(input, word, skip_tabs)
3754#endif
3755static char *fetch_till_str(o_string *as_string,
3756 struct in_str *input,
3757 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003758 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003759{
3760 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003761 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003762 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003763 int ch;
3764
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003765 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003766
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003767 while (1) {
3768 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003769 if (ch != EOF)
3770 nommu_addchr(as_string, ch);
3771 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003772 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3773 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003774 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3775 heredoc.data[past_EOL] = '\0';
3776 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3777 return heredoc.data;
3778 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003779 while (ch == '\n') {
3780 o_addchr(&heredoc, ch);
3781 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003782 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003783 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003784 do {
3785 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003786 if (ch != EOF)
3787 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003788 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003789 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003790 }
3791 if (ch == EOF) {
3792 o_free_unsafe(&heredoc);
3793 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003794 }
3795 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003796 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003797 if (prev == '\\' && ch == '\\')
3798 /* Correctly handle foo\\<eol> (not a line cont.) */
3799 prev = 0; /* not \ */
3800 else
3801 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003802 }
3803}
3804
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003805/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3806 * and load them all. There should be exactly heredoc_cnt of them.
3807 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003808static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3809{
3810 struct pipe *pi = ctx->list_head;
3811
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003812 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003813 int i;
3814 struct command *cmd = pi->cmds;
3815
3816 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3817 pi->num_cmds,
3818 cmd->argv ? cmd->argv[0] : "NONE");
3819 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003820 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003821
3822 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3823 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003824 while (redir) {
3825 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003826 char *p;
3827
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003828 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003829 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003830 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003831 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003832 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003833 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003834 return 1;
3835 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003836 free(redir->rd_filename);
3837 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003838 heredoc_cnt--;
3839 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003840 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003841 }
3842 cmd++;
3843 }
3844 pi = pi->next;
3845 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003846#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003847 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003848 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003849 bb_error_msg_and_die("heredoc BUG 2");
3850#endif
3851 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003852}
3853
3854
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003855static int run_list(struct pipe *pi);
3856#if BB_MMU
3857#define parse_stream(pstring, input, end_trigger) \
3858 parse_stream(input, end_trigger)
3859#endif
3860static struct pipe *parse_stream(char **pstring,
3861 struct in_str *input,
3862 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003863
Eric Andersen25f27032001-04-26 23:22:31 +00003864
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003865#if !ENABLE_HUSH_FUNCTIONS
3866#define parse_group(dest, ctx, input, ch) \
3867 parse_group(ctx, input, ch)
3868#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003869static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003870 struct in_str *input, int ch)
3871{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003872 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003873 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003874 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003875 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003876 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003877 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003878
3879 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003880#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003881 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003882 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003883 if (done_word(dest, ctx))
3884 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003885 if (!command->argv)
3886 goto skip; /* (... */
3887 if (command->argv[1]) { /* word word ... (... */
3888 syntax_error_unexpected_ch('(');
3889 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003890 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003891 /* it is "word(..." or "word (..." */
3892 do
3893 ch = i_getch(input);
3894 while (ch == ' ' || ch == '\t');
3895 if (ch != ')') {
3896 syntax_error_unexpected_ch(ch);
3897 return 1;
3898 }
3899 nommu_addchr(&ctx->as_string, ch);
3900 do
3901 ch = i_getch(input);
3902 while (ch == ' ' || ch == '\t' || ch == '\n');
3903 if (ch != '{') {
3904 syntax_error_unexpected_ch(ch);
3905 return 1;
3906 }
3907 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003908 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003909 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003910 }
3911#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003912
3913#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003914 if (command->argv /* word [word]{... */
3915 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003916 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003917 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003918 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003919 debug_printf_parse("parse_group return 1: "
3920 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003921 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003922 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003923#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003924
3925#if ENABLE_HUSH_FUNCTIONS
3926 skip:
3927#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003928 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003929 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003930 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003931 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003932 } else {
3933 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01003934 ch = i_peek(input);
3935 if (ch != ' ' && ch != '\t' && ch != '\n'
3936 && ch != '(' /* but "{(..." is allowed (without whitespace) */
3937 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003938 syntax_error_unexpected_ch(ch);
3939 return 1;
3940 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01003941 if (ch != '(') {
3942 ch = i_getch(input);
3943 nommu_addchr(&ctx->as_string, ch);
3944 }
Eric Andersen25f27032001-04-26 23:22:31 +00003945 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003946
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003947 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003948#if BB_MMU
3949# define as_string NULL
3950#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003951 char *as_string = NULL;
3952#endif
3953 pipe_list = parse_stream(&as_string, input, endch);
3954#if !BB_MMU
3955 if (as_string)
3956 o_addstr(&ctx->as_string, as_string);
3957#endif
3958 /* empty ()/{} or parse error? */
3959 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003960 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003961 if (!BB_MMU)
3962 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003963 debug_printf_parse("parse_group return 1: "
3964 "parse_stream returned %p\n", pipe_list);
3965 return 1;
3966 }
3967 command->group = pipe_list;
3968#if !BB_MMU
3969 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3970 command->group_as_string = as_string;
3971 debug_printf_parse("end of group, remembering as:'%s'\n",
3972 command->group_as_string);
3973#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003974#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003975 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003976 debug_printf_parse("parse_group return 0\n");
3977 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003978 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003979}
3980
Denys Vlasenko46e64982016-09-29 19:50:55 +02003981static int i_getch_and_eat_bkslash_nl(struct in_str *input)
3982{
3983 for (;;) {
3984 int ch, ch2;
3985
3986 ch = i_getch(input);
3987 if (ch != '\\')
3988 return ch;
3989 ch2 = i_peek(input);
3990 if (ch2 != '\n')
3991 return ch;
3992 /* backslash+newline, skip it */
3993 i_getch(input);
3994 }
3995}
3996
Denys Vlasenko657086a2016-09-29 18:07:42 +02003997static int i_peek_and_eat_bkslash_nl(struct in_str *input)
3998{
3999 for (;;) {
4000 int ch, ch2;
4001
4002 ch = i_peek(input);
4003 if (ch != '\\')
4004 return ch;
4005 ch2 = i_peek2(input);
4006 if (ch2 != '\n')
4007 return ch;
4008 /* backslash+newline, skip it */
4009 i_getch(input);
4010 i_getch(input);
4011 }
4012}
4013
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004014#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004015/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004016static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004017/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004018static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004019{
4020 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004021 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004022 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004023 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004024 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004025 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004026 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004027 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004028 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004029 }
4030}
4031/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004032static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004033{
4034 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004035 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004036 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004037 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004038 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004039 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004040 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004041 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004042 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004043 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004044 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004045 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004046 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004047 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004048 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4049 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004050 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004051 continue;
4052 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004053 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004054 }
4055}
4056/* Process `cmd` - copy contents until "`" is seen. Complicated by
4057 * \` quoting.
4058 * "Within the backquoted style of command substitution, backslash
4059 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4060 * The search for the matching backquote shall be satisfied by the first
4061 * backquote found without a preceding backslash; during this search,
4062 * if a non-escaped backquote is encountered within a shell comment,
4063 * a here-document, an embedded command substitution of the $(command)
4064 * form, or a quoted string, undefined results occur. A single-quoted
4065 * or double-quoted string that begins, but does not end, within the
4066 * "`...`" sequence produces undefined results."
4067 * Example Output
4068 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4069 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004070static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004071{
4072 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004073 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004074 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004075 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004076 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004077 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4078 ch = i_getch(input);
4079 if (ch != '`'
4080 && ch != '$'
4081 && ch != '\\'
4082 && (!in_dquote || ch != '"')
4083 ) {
4084 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004085 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004086 }
4087 if (ch == EOF) {
4088 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004089 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004090 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004091 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004092 }
4093}
4094/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4095 * quoting and nested ()s.
4096 * "With the $(command) style of command substitution, all characters
4097 * following the open parenthesis to the matching closing parenthesis
4098 * constitute the command. Any valid shell script can be used for command,
4099 * except a script consisting solely of redirections which produces
4100 * unspecified results."
4101 * Example Output
4102 * echo $(echo '(TEST)' BEST) (TEST) BEST
4103 * echo $(echo 'TEST)' BEST) TEST) BEST
4104 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004105 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004106 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004107 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004108 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4109 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004110 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004111#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004112static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004113{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004114 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004115 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004116# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004117 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004118# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004119 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4120
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004121 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004122 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004123 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004124 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004125 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004126 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004127 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004128 if (!dbl)
4129 break;
4130 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004131 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004132 i_getch(input); /* eat second ')' */
4133 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004134 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004135 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004136 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004137 if (ch == '(' || ch == '{') {
4138 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004139 if (!add_till_closing_bracket(dest, input, ch))
4140 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004141 o_addchr(dest, ch);
4142 continue;
4143 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004144 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004145 if (!add_till_single_quote(dest, input))
4146 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004147 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004148 continue;
4149 }
4150 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004151 if (!add_till_double_quote(dest, input))
4152 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004153 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004154 continue;
4155 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004156 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004157 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4158 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004159 o_addchr(dest, ch);
4160 continue;
4161 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004162 if (ch == '\\') {
4163 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004164 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004165 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004166 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004167 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004168 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004169#if 0
4170 if (ch == '\n') {
4171 /* "backslash+newline", ignore both */
4172 o_delchr(dest); /* undo insertion of '\' */
4173 continue;
4174 }
4175#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004176 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004177 continue;
4178 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004179 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004180 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004181}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004182#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004183
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004184/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004185#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004186#define parse_dollar(as_string, dest, input, quote_mask) \
4187 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004188#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004189#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004190static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004191 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004192 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004193{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004194 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004195
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004196 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004197 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004198 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004199 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004200 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004201 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004202 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004203 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004204 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004205 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004206 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004207 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004208 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004209 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004210 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004211 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004212 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004213 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004214 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004215 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004216 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004217 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004218 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004219 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004220 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004221 o_addchr(dest, ch | quote_mask);
4222 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004223 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004224 case '$': /* pid */
4225 case '!': /* last bg pid */
4226 case '?': /* last exit code */
4227 case '#': /* number of args */
4228 case '*': /* args */
4229 case '@': /* args */
4230 goto make_one_char_var;
4231 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004232 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4233
Denys Vlasenko74369502010-05-21 19:52:01 +02004234 ch = i_getch(input); /* eat '{' */
4235 nommu_addchr(as_string, ch);
4236
Denys Vlasenko46e64982016-09-29 19:50:55 +02004237 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004238 /* It should be ${?}, or ${#var},
4239 * or even ${?+subst} - operator acting on a special variable,
4240 * or the beginning of variable name.
4241 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004242 if (ch == EOF
4243 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4244 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004245 bad_dollar_syntax:
4246 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004247 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4248 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004249 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004250 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004251 ch |= quote_mask;
4252
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004253 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004254 * However, this regresses some of our testsuite cases
4255 * which check invalid constructs like ${%}.
4256 * Oh well... let's check that the var name part is fine... */
4257
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004258 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004259 unsigned pos;
4260
Denys Vlasenko74369502010-05-21 19:52:01 +02004261 o_addchr(dest, ch);
4262 debug_printf_parse(": '%c'\n", ch);
4263
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004264 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004265 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004266 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004267 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004268
Denys Vlasenko74369502010-05-21 19:52:01 +02004269 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004270 unsigned end_ch;
4271 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004272 /* handle parameter expansions
4273 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4274 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004275 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02004276 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004277
4278 /* Eat everything until closing '}' (or ':') */
4279 end_ch = '}';
4280 if (ENABLE_HUSH_BASH_COMPAT
4281 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004282 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004283 ) {
4284 /* It's ${var:N[:M]} thing */
4285 end_ch = '}' * 0x100 + ':';
4286 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004287 if (ENABLE_HUSH_BASH_COMPAT
4288 && ch == '/'
4289 ) {
4290 /* It's ${var/[/]pattern[/repl]} thing */
4291 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4292 i_getch(input);
4293 nommu_addchr(as_string, '/');
4294 ch = '\\';
4295 }
4296 end_ch = '}' * 0x100 + '/';
4297 }
4298 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004299 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004300 if (!BB_MMU)
4301 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004302#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004303 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004304 if (last_ch == 0) /* error? */
4305 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004306#else
4307#error Simple code to only allow ${var} is not implemented
4308#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004309 if (as_string) {
4310 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004311 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004312 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004313
4314 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4315 /* close the first block: */
4316 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004317 /* while parsing N from ${var:N[:M]}
4318 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004319 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004320 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004321 end_ch = '}';
4322 goto again;
4323 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004324 /* got '}' */
4325 if (end_ch == '}' * 0x100 + ':') {
4326 /* it's ${var:N} - emulate :999999999 */
4327 o_addstr(dest, "999999999");
4328 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004329 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004330 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004331 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004332 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004333 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4334 break;
4335 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004336#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004337 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004338 unsigned pos;
4339
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004340 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004341 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004342# if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko657086a2016-09-29 18:07:42 +02004343 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004344 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004345 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004346 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4347 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004348 if (!BB_MMU)
4349 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004350 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4351 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004352 if (as_string) {
4353 o_addstr(as_string, dest->data + pos);
4354 o_addchr(as_string, ')');
4355 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004356 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004357 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004358 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004359 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004360# endif
4361# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004362 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4363 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004364 if (!BB_MMU)
4365 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004366 if (!add_till_closing_bracket(dest, input, ')'))
4367 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004368 if (as_string) {
4369 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004370 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004371 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004372 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004373# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004374 break;
4375 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004376#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004377 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004378 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004379 nommu_addchr(as_string, ch);
Denys Vlasenko657086a2016-09-29 18:07:42 +02004380 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004381 if (isalnum(ch)) { /* it's $_name or $_123 */
4382 ch = '_';
4383 goto make_var;
4384 }
4385 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004386 /* TODO: $_ and $-: */
4387 /* $_ Shell or shell script name; or last argument of last command
4388 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4389 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004390 /* $- Option flags set by set builtin or shell options (-i etc) */
4391 default:
4392 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004393 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004394 debug_printf_parse("parse_dollar return 1 (ok)\n");
4395 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004396#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004397}
4398
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004399#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004400# if ENABLE_HUSH_BASH_COMPAT
4401#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4402 encode_string(dest, input, dquote_end, process_bkslash)
4403# else
4404/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4405#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4406 encode_string(dest, input, dquote_end)
4407# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004408#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004409
4410#else /* !MMU */
4411
4412# if ENABLE_HUSH_BASH_COMPAT
4413/* all parameters are needed, no macro tricks */
4414# else
4415#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4416 encode_string(as_string, dest, input, dquote_end)
4417# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004418#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004419static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004420 o_string *dest,
4421 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004422 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004423 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004424{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004425#if !ENABLE_HUSH_BASH_COMPAT
4426 const int process_bkslash = 1;
4427#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004428 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004429 int next;
4430
4431 again:
4432 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004433 if (ch != EOF)
4434 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004435 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004436 debug_printf_parse("encode_string return 1 (ok)\n");
4437 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004438 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004439 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004440 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004441 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004442 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004443 }
4444 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004445 if (ch != '\n') {
4446 next = i_peek(input);
4447 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004448 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004449 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004450 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004451 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004452 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004453 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004454 }
4455 /* bash:
4456 * "The backslash retains its special meaning [in "..."]
4457 * only when followed by one of the following characters:
4458 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004459 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004460 * NB: in (unquoted) heredoc, above does not apply to ",
4461 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004462 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004463 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004464 ch = i_getch(input); /* eat next */
4465 if (ch == '\n')
4466 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004467 } /* else: ch remains == '\\', and we double it below: */
4468 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004469 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004470 goto again;
4471 }
4472 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004473 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4474 debug_printf_parse("encode_string return 0: "
4475 "parse_dollar returned 0 (error)\n");
4476 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004477 }
4478 goto again;
4479 }
4480#if ENABLE_HUSH_TICK
4481 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004482 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004483 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4484 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004485 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4486 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004487 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4488 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004489 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004490 }
4491#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004492 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004493 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004494#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004495}
4496
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004497/*
4498 * Scan input until EOF or end_trigger char.
4499 * Return a list of pipes to execute, or NULL on EOF
4500 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004501 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004502 * reset parsing machinery and start parsing anew,
4503 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004504 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004505static struct pipe *parse_stream(char **pstring,
4506 struct in_str *input,
4507 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004508{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004509 struct parse_context ctx;
4510 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004511 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004512
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004513 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004514 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004515 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004516 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004517 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004518 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004519
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004520 /* If very first arg is "" or '', dest.data may end up NULL.
4521 * Preventing this: */
4522 o_addchr(&dest, '\0');
4523 dest.length = 0;
4524
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004525 /* We used to separate words on $IFS here. This was wrong.
4526 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004527 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004528 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004529
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004530 if (MAYBE_ASSIGNMENT != 0)
4531 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004532 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004533 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004534 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004535 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004536 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004537 int ch;
4538 int next;
4539 int redir_fd;
4540 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004541
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004542 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004543 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004544 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004545 if (ch == EOF) {
4546 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004547
4548 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004549 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004550 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004551 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004552 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004553 syntax_error_unterm_ch('(');
4554 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004555 }
Denys Vlasenko42246472016-11-07 16:22:35 +01004556 if (end_trigger == '}') {
4557 syntax_error_unterm_ch('{');
4558 goto parse_error;
4559 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004560
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004561 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004562 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004563 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004564 o_free(&dest);
4565 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004566 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004567 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004568 /* (this makes bare "&" cmd a no-op.
4569 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004570 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004571 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004572 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004573 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004574 pi = NULL;
4575 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004576#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004577 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004578 if (pstring)
4579 *pstring = ctx.as_string.data;
4580 else
4581 o_free_unsafe(&ctx.as_string);
4582#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004583 debug_leave();
4584 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004585 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004586 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004587 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004588
4589 next = '\0';
4590 if (ch != '\n')
4591 next = i_peek(input);
4592
4593 is_special = "{}<>;&|()#'" /* special outside of "str" */
4594 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4595 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004596 if (ctx.command->argv /* word [word]{... - non-special */
4597 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004598 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004599 || (next != ';' /* }; - special */
4600 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004601 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004602 && next != '&' /* }& and }&& ... - special */
4603 && next != '|' /* }|| ... - special */
4604 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004605 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004606 ) {
4607 /* They are not special, skip "{}" */
4608 is_special += 2;
4609 }
4610 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004611 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004612
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004613 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004614 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004615 o_addQchr(&dest, ch);
4616 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4617 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004618 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004619 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004620 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004621 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004622 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004623 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004624 continue;
4625 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004626
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004627 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004628 if (done_word(&dest, &ctx)) {
4629 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004630 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004631 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004632 /* Is this a case when newline is simply ignored?
4633 * Some examples:
4634 * "cmd | <newline> cmd ..."
4635 * "case ... in <newline> word) ..."
4636 */
4637 if (IS_NULL_CMD(ctx.command)
4638 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004639 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004640 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004641 * Without check #1, interactive shell
4642 * ignores even bare <newline>,
4643 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004644 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004645 * ps2> _ <=== wrong, should be ps1
4646 * Without check #2, "cmd & <newline>"
4647 * is similarly mistreated.
4648 * (BTW, this makes "cmd & cmd"
4649 * and "cmd && cmd" non-orthogonal.
4650 * Really, ask yourself, why
4651 * "cmd && <newline>" doesn't start
4652 * cmd but waits for more input?
4653 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004654 */
4655 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004656 if (pi->num_cmds != 0 /* check #1 */
4657 && pi->followup != PIPE_BG /* check #2 */
4658 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004659 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004660 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004661 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004662 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004663 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004664 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4665 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004666 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004667 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004668 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004669 heredoc_cnt = 0;
4670 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004671 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004672 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004673 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004674 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004675 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004676 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004677 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004678
4679 /* "cmd}" or "cmd }..." without semicolon or &:
4680 * } is an ordinary char in this case, even inside { cmd; }
4681 * Pathological example: { ""}; } should exec "}" cmd
4682 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004683 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004684 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004685 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004686 ) {
4687 goto ordinary_char;
4688 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004689 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4690 /* Generally, there should be semicolon: "cmd; }"
4691 * However, bash allows to omit it if "cmd" is
4692 * a group. Examples:
4693 * { { echo 1; } }
4694 * {(echo 1)}
4695 * { echo 0 >&2 | { echo 1; } }
4696 * { while false; do :; done }
4697 * { case a in b) ;; esac }
4698 */
4699 if (ctx.command->group)
4700 goto term_group;
4701 goto ordinary_char;
4702 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004703 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004704 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004705 goto skip_end_trigger;
4706 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004707 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004708 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004709 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004710 && (ch != ';' || heredoc_cnt == 0)
4711#if ENABLE_HUSH_CASE
4712 && (ch != ')'
4713 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004714 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004715 )
4716#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004717 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004718 if (heredoc_cnt) {
4719 /* This is technically valid:
4720 * { cat <<HERE; }; echo Ok
4721 * heredoc
4722 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004723 * HERE
4724 * but we don't support this.
4725 * We require heredoc to be in enclosing {}/(),
4726 * if any.
4727 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004728 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004729 goto parse_error;
4730 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004731 if (done_word(&dest, &ctx)) {
4732 goto parse_error;
4733 }
4734 done_pipe(&ctx, PIPE_SEQ);
4735 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004736 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004737 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004738 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004739 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004740 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004741 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004742#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004743 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004744 if (pstring)
4745 *pstring = ctx.as_string.data;
4746 else
4747 o_free_unsafe(&ctx.as_string);
4748#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004749 debug_leave();
4750 debug_printf_parse("parse_stream return %p: "
4751 "end_trigger char found\n",
4752 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004753 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004754 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004755 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004756 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004757 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004758 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004759
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004760 /* Catch <, > before deciding whether this word is
4761 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4762 switch (ch) {
4763 case '>':
4764 redir_fd = redirect_opt_num(&dest);
4765 if (done_word(&dest, &ctx)) {
4766 goto parse_error;
4767 }
4768 redir_style = REDIRECT_OVERWRITE;
4769 if (next == '>') {
4770 redir_style = REDIRECT_APPEND;
4771 ch = i_getch(input);
4772 nommu_addchr(&ctx.as_string, ch);
4773 }
4774#if 0
4775 else if (next == '(') {
4776 syntax_error(">(process) not supported");
4777 goto parse_error;
4778 }
4779#endif
4780 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4781 goto parse_error;
4782 continue; /* back to top of while (1) */
4783 case '<':
4784 redir_fd = redirect_opt_num(&dest);
4785 if (done_word(&dest, &ctx)) {
4786 goto parse_error;
4787 }
4788 redir_style = REDIRECT_INPUT;
4789 if (next == '<') {
4790 redir_style = REDIRECT_HEREDOC;
4791 heredoc_cnt++;
4792 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4793 ch = i_getch(input);
4794 nommu_addchr(&ctx.as_string, ch);
4795 } else if (next == '>') {
4796 redir_style = REDIRECT_IO;
4797 ch = i_getch(input);
4798 nommu_addchr(&ctx.as_string, ch);
4799 }
4800#if 0
4801 else if (next == '(') {
4802 syntax_error("<(process) not supported");
4803 goto parse_error;
4804 }
4805#endif
4806 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4807 goto parse_error;
4808 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004809 case '#':
4810 if (dest.length == 0 && !dest.has_quoted_part) {
4811 /* skip "#comment" */
4812 while (1) {
4813 ch = i_peek(input);
4814 if (ch == EOF || ch == '\n')
4815 break;
4816 i_getch(input);
4817 /* note: we do not add it to &ctx.as_string */
4818 }
4819 nommu_addchr(&ctx.as_string, '\n');
4820 continue; /* back to top of while (1) */
4821 }
4822 break;
4823 case '\\':
4824 if (next == '\n') {
4825 /* It's "\<newline>" */
4826#if !BB_MMU
4827 /* Remove trailing '\' from ctx.as_string */
4828 ctx.as_string.data[--ctx.as_string.length] = '\0';
4829#endif
4830 ch = i_getch(input); /* eat it */
4831 continue; /* back to top of while (1) */
4832 }
4833 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004834 }
4835
4836 if (dest.o_assignment == MAYBE_ASSIGNMENT
4837 /* check that we are not in word in "a=1 2>word b=1": */
4838 && !ctx.pending_redirect
4839 ) {
4840 /* ch is a special char and thus this word
4841 * cannot be an assignment */
4842 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004843 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004844 }
4845
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004846 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4847
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004848 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004849 case '#': /* non-comment #: "echo a#b" etc */
4850 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004851 break;
4852 case '\\':
4853 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004854 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004855 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004856 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004857 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004858 /* note: ch != '\n' (that case does not reach this place) */
4859 o_addchr(&dest, '\\');
4860 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4861 o_addchr(&dest, ch);
4862 nommu_addchr(&ctx.as_string, ch);
4863 /* Example: echo Hello \2>file
4864 * we need to know that word 2 is quoted */
4865 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004866 break;
4867 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004868 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004869 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004870 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004871 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004872 }
Eric Andersen25f27032001-04-26 23:22:31 +00004873 break;
4874 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004875 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004876 if (next == '\'' && !ctx.pending_redirect) {
4877 insert_empty_quoted_str_marker:
4878 nommu_addchr(&ctx.as_string, next);
4879 i_getch(input); /* eat second ' */
4880 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4881 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4882 } else {
4883 while (1) {
4884 ch = i_getch(input);
4885 if (ch == EOF) {
4886 syntax_error_unterm_ch('\'');
4887 goto parse_error;
4888 }
4889 nommu_addchr(&ctx.as_string, ch);
4890 if (ch == '\'')
4891 break;
4892 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004893 }
Eric Andersen25f27032001-04-26 23:22:31 +00004894 }
Eric Andersen25f27032001-04-26 23:22:31 +00004895 break;
4896 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004897 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004898 if (next == '"' && !ctx.pending_redirect)
4899 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004900 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004901 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004902 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004903 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004904 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004905 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004906#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004907 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004908 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004909
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004910 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4911 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004912 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004913 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4914 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004915# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004916 o_addstr(&ctx.as_string, dest.data + pos);
4917 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004918# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004919 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4920 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004921 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004922 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004923#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004924 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004925#if ENABLE_HUSH_CASE
4926 case_semi:
4927#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004928 if (done_word(&dest, &ctx)) {
4929 goto parse_error;
4930 }
4931 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004932#if ENABLE_HUSH_CASE
4933 /* Eat multiple semicolons, detect
4934 * whether it means something special */
4935 while (1) {
4936 ch = i_peek(input);
4937 if (ch != ';')
4938 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004939 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004940 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004941 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004942 ctx.ctx_dsemicolon = 1;
4943 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004944 break;
4945 }
4946 }
4947#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004948 new_cmd:
4949 /* We just finished a cmd. New one may start
4950 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004951 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004952 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004953 break;
4954 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004955 if (done_word(&dest, &ctx)) {
4956 goto parse_error;
4957 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004958 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004959 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004960 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004961 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004962 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004963 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004964 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004965 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004966 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004967 if (done_word(&dest, &ctx)) {
4968 goto parse_error;
4969 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004970#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004971 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004972 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004973#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004974 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004975 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004976 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004977 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004978 } else {
4979 /* we could pick up a file descriptor choice here
4980 * with redirect_opt_num(), but bash doesn't do it.
4981 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004982 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004983 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004984 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004985 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004986#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004987 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004988 if (ctx.ctx_res_w == RES_MATCH
4989 && ctx.command->argv == NULL /* not (word|(... */
4990 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004991 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004992 ) {
4993 continue;
4994 }
4995#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004996 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004997 if (parse_group(&dest, &ctx, input, ch) != 0) {
4998 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004999 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005000 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005001 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005002#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005003 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005004 goto case_semi;
5005#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005006 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005007 /* proper use of this character is caught by end_trigger:
5008 * if we see {, we call parse_group(..., end_trigger='}')
5009 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005010 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005011 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005012 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005013 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005014 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005015 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005016 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005017
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005018 parse_error:
5019 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005020 struct parse_context *pctx;
5021 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005022
5023 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005024 * Sample for finding leaks on syntax error recovery path.
5025 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005026 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005027 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005028 * while if (true | { true;}); then echo ok; fi; do break; done
5029 * 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 +00005030 */
5031 pctx = &ctx;
5032 do {
5033 /* Update pipe/command counts,
5034 * otherwise freeing may miss some */
5035 done_pipe(pctx, PIPE_SEQ);
5036 debug_printf_clean("freeing list %p from ctx %p\n",
5037 pctx->list_head, pctx);
5038 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005039 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005040 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005041#if !BB_MMU
5042 o_free_unsafe(&pctx->as_string);
5043#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005044 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005045 if (pctx != &ctx) {
5046 free(pctx);
5047 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005048 IF_HAS_KEYWORDS(pctx = p2;)
5049 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005050
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005051 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005052 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005053#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005054 if (pstring)
5055 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005056#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005057 debug_leave();
5058 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005059 }
Eric Andersen25f27032001-04-26 23:22:31 +00005060}
5061
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005062
5063/*** Execution routines ***/
5064
5065/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005066#if !ENABLE_HUSH_BASH_COMPAT
5067/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5068#define expand_string_to_string(str, do_unbackslash) \
5069 expand_string_to_string(str)
5070#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005071static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005072#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005073static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005074#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005075
5076/* expand_strvec_to_strvec() takes a list of strings, expands
5077 * all variable references within and returns a pointer to
5078 * a list of expanded strings, possibly with larger number
5079 * of strings. (Think VAR="a b"; echo $VAR).
5080 * This new list is allocated as a single malloc block.
5081 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005082 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005083 * Caller can deallocate entire list by single free(list). */
5084
Denys Vlasenko238081f2010-10-03 14:26:26 +02005085/* A horde of its helpers come first: */
5086
5087static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5088{
5089 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005090 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005091
Denys Vlasenko9e800222010-10-03 14:28:04 +02005092#if ENABLE_HUSH_BRACE_EXPANSION
5093 if (c == '{' || c == '}') {
5094 /* { -> \{, } -> \} */
5095 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005096 /* And now we want to add { or } and continue:
5097 * o_addchr(o, c);
5098 * continue;
5099 * luckily, just falling throught achieves this.
5100 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005101 }
5102#endif
5103 o_addchr(o, c);
5104 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005105 /* \z -> \\\z; \<eol> -> \\<eol> */
5106 o_addchr(o, '\\');
5107 if (len) {
5108 len--;
5109 o_addchr(o, '\\');
5110 o_addchr(o, *str++);
5111 }
5112 }
5113 }
5114}
5115
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005116/* Store given string, finalizing the word and starting new one whenever
5117 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005118 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5119 * Return in *ended_with_ifs:
5120 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5121 */
5122static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005123{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005124 int last_is_ifs = 0;
5125
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005126 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005127 int word_len;
5128
5129 if (!*str) /* EOL - do not finalize word */
5130 break;
5131 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005132 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005133 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005134 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005135 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005136 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005137 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005138 * Example: "v='\*'; echo b$v" prints "b\*"
5139 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005140 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005141 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005142 /*/ Why can't we do it easier? */
5143 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5144 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5145 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005146 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005147 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005148 if (!*str) /* EOL - do not finalize word */
5149 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005150 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005151
5152 /* We know str here points to at least one IFS char */
5153 last_is_ifs = 1;
5154 str += strspn(str, G.ifs); /* skip IFS chars */
5155 if (!*str) /* EOL - do not finalize word */
5156 break;
5157
5158 /* Start new word... but not always! */
5159 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005160 if (output->has_quoted_part
5161 /* Case "v=' a'; echo $v":
5162 * here nothing precedes the space in $v expansion,
5163 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005164 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005165 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005166 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005167 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005168 o_addchr(output, '\0');
5169 debug_print_list("expand_on_ifs", output, n);
5170 n = o_save_ptr(output, n);
5171 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005172 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005173
5174 if (ended_with_ifs)
5175 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005176 debug_print_list("expand_on_ifs[1]", output, n);
5177 return n;
5178}
5179
5180/* Helper to expand $((...)) and heredoc body. These act as if
5181 * they are in double quotes, with the exception that they are not :).
5182 * Just the rules are similar: "expand only $var and `cmd`"
5183 *
5184 * Returns malloced string.
5185 * As an optimization, we return NULL if expansion is not needed.
5186 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005187#if !ENABLE_HUSH_BASH_COMPAT
5188/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5189#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5190 encode_then_expand_string(str)
5191#endif
5192static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005193{
5194 char *exp_str;
5195 struct in_str input;
5196 o_string dest = NULL_O_STRING;
5197
5198 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005199 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005200#if ENABLE_HUSH_TICK
5201 && !strchr(str, '`')
5202#endif
5203 ) {
5204 return NULL;
5205 }
5206
5207 /* We need to expand. Example:
5208 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5209 */
5210 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005211 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005212//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005213 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005214 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005215 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5216 o_free_unsafe(&dest);
5217 return exp_str;
5218}
5219
5220#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02005221static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005222{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005223 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005224 arith_t res;
5225 char *exp_str;
5226
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005227 math_state.lookupvar = get_local_var_value;
5228 math_state.setvar = set_local_var_from_halves;
5229 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005230 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005231 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005232 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005233 if (errmsg_p)
5234 *errmsg_p = math_state.errmsg;
5235 if (math_state.errmsg)
5236 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005237 return res;
5238}
5239#endif
5240
5241#if ENABLE_HUSH_BASH_COMPAT
5242/* ${var/[/]pattern[/repl]} helpers */
5243static char *strstr_pattern(char *val, const char *pattern, int *size)
5244{
5245 while (1) {
5246 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5247 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5248 if (end) {
5249 *size = end - val;
5250 return val;
5251 }
5252 if (*val == '\0')
5253 return NULL;
5254 /* Optimization: if "*pat" did not match the start of "string",
5255 * we know that "tring", "ring" etc will not match too:
5256 */
5257 if (pattern[0] == '*')
5258 return NULL;
5259 val++;
5260 }
5261}
5262static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5263{
5264 char *result = NULL;
5265 unsigned res_len = 0;
5266 unsigned repl_len = strlen(repl);
5267
5268 while (1) {
5269 int size;
5270 char *s = strstr_pattern(val, pattern, &size);
5271 if (!s)
5272 break;
5273
5274 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5275 memcpy(result + res_len, val, s - val);
5276 res_len += s - val;
5277 strcpy(result + res_len, repl);
5278 res_len += repl_len;
5279 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5280
5281 val = s + size;
5282 if (exp_op == '/')
5283 break;
5284 }
5285 if (val[0] && result) {
5286 result = xrealloc(result, res_len + strlen(val) + 1);
5287 strcpy(result + res_len, val);
5288 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5289 }
5290 debug_printf_varexp("result:'%s'\n", result);
5291 return result;
5292}
5293#endif
5294
5295/* Helper:
5296 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5297 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005298static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005299{
5300 const char *val = NULL;
5301 char *to_be_freed = NULL;
5302 char *p = *pp;
5303 char *var;
5304 char first_char;
5305 char exp_op;
5306 char exp_save = exp_save; /* for compiler */
5307 char *exp_saveptr; /* points to expansion operator */
5308 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005309 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005310
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005311 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005312 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005313 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005314 arg0 = arg[0];
5315 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005316 exp_op = 0;
5317
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005318 if (first_char == '#' /* ${#... */
5319 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5320 ) {
5321 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005322 var++;
5323 exp_op = 'L';
5324 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005325 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005326 if (exp_saveptr /* if 2nd char is one of expansion operators */
5327 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5328 ) {
5329 /* ${?:0}, ${#[:]%0} etc */
5330 exp_saveptr = var + 1;
5331 } else {
5332 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5333 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5334 }
5335 exp_op = exp_save = *exp_saveptr;
5336 if (exp_op) {
5337 exp_word = exp_saveptr + 1;
5338 if (exp_op == ':') {
5339 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005340//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005341 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005342 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005343 ) {
5344 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5345 exp_op = ':';
5346 exp_word--;
5347 }
5348 }
5349 *exp_saveptr = '\0';
5350 } /* else: it's not an expansion op, but bare ${var} */
5351 }
5352
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005353 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005354 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005355 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005356 int n = xatoi_positive(var);
5357 if (n < G.global_argc)
5358 val = G.global_argv[n];
5359 /* else val remains NULL: $N with too big N */
5360 } else {
5361 switch (var[0]) {
5362 case '$': /* pid */
5363 val = utoa(G.root_pid);
5364 break;
5365 case '!': /* bg pid */
5366 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5367 break;
5368 case '?': /* exitcode */
5369 val = utoa(G.last_exitcode);
5370 break;
5371 case '#': /* argc */
5372 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5373 break;
5374 default:
5375 val = get_local_var_value(var);
5376 }
5377 }
5378
5379 /* Handle any expansions */
5380 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005381 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005382 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005383 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005384 debug_printf_expand("%s\n", val);
5385 } else if (exp_op) {
5386 if (exp_op == '%' || exp_op == '#') {
5387 /* Standard-mandated substring removal ops:
5388 * ${parameter%word} - remove smallest suffix pattern
5389 * ${parameter%%word} - remove largest suffix pattern
5390 * ${parameter#word} - remove smallest prefix pattern
5391 * ${parameter##word} - remove largest prefix pattern
5392 *
5393 * Word is expanded to produce a glob pattern.
5394 * Then var's value is matched to it and matching part removed.
5395 */
5396 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005397 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005398 char *exp_exp_word;
5399 char *loc;
5400 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005401 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005402 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005403 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005404 if (exp_exp_word)
5405 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005406 /* HACK ALERT. We depend here on the fact that
5407 * G.global_argv and results of utoa and get_local_var_value
5408 * are actually in writable memory:
5409 * scan_and_match momentarily stores NULs there. */
5410 t = (char*)val;
5411 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005412 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005413 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005414 free(exp_exp_word);
5415 if (loc) { /* match was found */
5416 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005417 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005418 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005419 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005420 }
5421 }
5422 }
5423#if ENABLE_HUSH_BASH_COMPAT
5424 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005425 /* It's ${var/[/]pattern[/repl]} thing.
5426 * Note that in encoded form it has TWO parts:
5427 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005428 * and if // is used, it is encoded as \:
5429 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005430 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005431 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005432 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005433 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005434 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005435 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005436 * by the usual expansion rules:
5437 * >az; >bz;
5438 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5439 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5440 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5441 * v='a bz'; echo ${v/a*z/\z} prints "z"
5442 * (note that a*z _pattern_ is never globbed!)
5443 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005444 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005445 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005446 if (!pattern)
5447 pattern = xstrdup(exp_word);
5448 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5449 *p++ = SPECIAL_VAR_SYMBOL;
5450 exp_word = p;
5451 p = strchr(p, SPECIAL_VAR_SYMBOL);
5452 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005453 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005454 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5455 /* HACK ALERT. We depend here on the fact that
5456 * G.global_argv and results of utoa and get_local_var_value
5457 * are actually in writable memory:
5458 * replace_pattern momentarily stores NULs there. */
5459 t = (char*)val;
5460 to_be_freed = replace_pattern(t,
5461 pattern,
5462 (repl ? repl : exp_word),
5463 exp_op);
5464 if (to_be_freed) /* at least one replace happened */
5465 val = to_be_freed;
5466 free(pattern);
5467 free(repl);
5468 }
5469 }
5470#endif
5471 else if (exp_op == ':') {
5472#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5473 /* It's ${var:N[:M]} bashism.
5474 * Note that in encoded form it has TWO parts:
5475 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5476 */
5477 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005478 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005479
Denys Vlasenko063847d2010-09-15 13:33:02 +02005480 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5481 if (errmsg)
5482 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005483 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5484 *p++ = SPECIAL_VAR_SYMBOL;
5485 exp_word = p;
5486 p = strchr(p, SPECIAL_VAR_SYMBOL);
5487 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005488 len = expand_and_evaluate_arith(exp_word, &errmsg);
5489 if (errmsg)
5490 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005491 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005492 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005493 if (beg < 0) /* bash compat */
5494 beg = 0;
5495 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005496 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005497 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005498 val = NULL;
5499 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005500 /* Paranoia. What if user entered 9999999999999
5501 * which fits in arith_t but not int? */
5502 if (len >= INT_MAX)
5503 len = INT_MAX;
5504 val = to_be_freed = xstrndup(val + beg, len);
5505 }
5506 debug_printf_varexp("val:'%s'\n", val);
5507 } else
5508#endif
5509 {
5510 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005511 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005512 }
5513 } else { /* one of "-=+?" */
5514 /* Standard-mandated substitution ops:
5515 * ${var?word} - indicate error if unset
5516 * If var is unset, word (or a message indicating it is unset
5517 * if word is null) is written to standard error
5518 * and the shell exits with a non-zero exit status.
5519 * Otherwise, the value of var is substituted.
5520 * ${var-word} - use default value
5521 * If var is unset, word is substituted.
5522 * ${var=word} - assign and use default value
5523 * If var is unset, word is assigned to var.
5524 * In all cases, final value of var is substituted.
5525 * ${var+word} - use alternative value
5526 * If var is unset, null is substituted.
5527 * Otherwise, word is substituted.
5528 *
5529 * Word is subjected to tilde expansion, parameter expansion,
5530 * command substitution, and arithmetic expansion.
5531 * If word is not needed, it is not expanded.
5532 *
5533 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5534 * but also treat null var as if it is unset.
5535 */
5536 int use_word = (!val || ((exp_save == ':') && !val[0]));
5537 if (exp_op == '+')
5538 use_word = !use_word;
5539 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5540 (exp_save == ':') ? "true" : "false", use_word);
5541 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005542 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005543 if (to_be_freed)
5544 exp_word = to_be_freed;
5545 if (exp_op == '?') {
5546 /* mimic bash message */
5547 die_if_script("%s: %s",
5548 var,
5549 exp_word[0] ? exp_word : "parameter null or not set"
5550 );
5551//TODO: how interactive bash aborts expansion mid-command?
5552 } else {
5553 val = exp_word;
5554 }
5555
5556 if (exp_op == '=') {
5557 /* ${var=[word]} or ${var:=[word]} */
5558 if (isdigit(var[0]) || var[0] == '#') {
5559 /* mimic bash message */
5560 die_if_script("$%s: cannot assign in this way", var);
5561 val = NULL;
5562 } else {
5563 char *new_var = xasprintf("%s=%s", var, val);
5564 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5565 }
5566 }
5567 }
5568 } /* one of "-=+?" */
5569
5570 *exp_saveptr = exp_save;
5571 } /* if (exp_op) */
5572
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005573 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005574
5575 *pp = p;
5576 *to_be_freed_pp = to_be_freed;
5577 return val;
5578}
5579
5580/* Expand all variable references in given string, adding words to list[]
5581 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5582 * to be filled). This routine is extremely tricky: has to deal with
5583 * variables/parameters with whitespace, $* and $@, and constructs like
5584 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005585static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005586{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005587 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005588 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005589 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005590 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005591 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005592 char *p;
5593
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005594 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5595 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005596 debug_print_list("expand_vars_to_list", output, n);
5597 n = o_save_ptr(output, n);
5598 debug_print_list("expand_vars_to_list[0]", output, n);
5599
5600 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5601 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005602 char *to_be_freed = NULL;
5603 const char *val = NULL;
5604#if ENABLE_HUSH_TICK
5605 o_string subst_result = NULL_O_STRING;
5606#endif
5607#if ENABLE_SH_MATH_SUPPORT
5608 char arith_buf[sizeof(arith_t)*3 + 2];
5609#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005610
5611 if (ended_in_ifs) {
5612 o_addchr(output, '\0');
5613 n = o_save_ptr(output, n);
5614 ended_in_ifs = 0;
5615 }
5616
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005617 o_addblock(output, arg, p - arg);
5618 debug_print_list("expand_vars_to_list[1]", output, n);
5619 arg = ++p;
5620 p = strchr(p, SPECIAL_VAR_SYMBOL);
5621
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005622 /* Fetch special var name (if it is indeed one of them)
5623 * and quote bit, force the bit on if singleword expansion -
5624 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005625 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005626
5627 /* Is this variable quoted and thus expansion can't be null?
5628 * "$@" is special. Even if quoted, it can still
5629 * expand to nothing (not even an empty string),
5630 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005631 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005632 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005633
5634 switch (first_ch & 0x7f) {
5635 /* Highest bit in first_ch indicates that var is double-quoted */
5636 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005637 case '@': {
5638 int i;
5639 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005640 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005641 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005642 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005643 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005644 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005645 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005646 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5647 if (G.global_argv[i++][0] && G.global_argv[i]) {
5648 /* this argv[] is not empty and not last:
5649 * put terminating NUL, start new word */
5650 o_addchr(output, '\0');
5651 debug_print_list("expand_vars_to_list[2]", output, n);
5652 n = o_save_ptr(output, n);
5653 debug_print_list("expand_vars_to_list[3]", output, n);
5654 }
5655 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005656 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005657 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005658 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005659 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005660 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005661 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005662 while (1) {
5663 o_addQstr(output, G.global_argv[i]);
5664 if (++i >= G.global_argc)
5665 break;
5666 o_addchr(output, '\0');
5667 debug_print_list("expand_vars_to_list[4]", output, n);
5668 n = o_save_ptr(output, n);
5669 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005670 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005671 while (1) {
5672 o_addQstr(output, G.global_argv[i]);
5673 if (!G.global_argv[++i])
5674 break;
5675 if (G.ifs[0])
5676 o_addchr(output, G.ifs[0]);
5677 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005678 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005679 }
5680 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005681 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005682 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5683 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005684 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005685 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005686 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005687 break;
5688#if ENABLE_HUSH_TICK
5689 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005690 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005691 arg++;
5692 /* Can't just stuff it into output o_string,
5693 * expanded result may need to be globbed
5694 * and $IFS-splitted */
5695 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5696 G.last_exitcode = process_command_subs(&subst_result, arg);
5697 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5698 val = subst_result.data;
5699 goto store_val;
5700#endif
5701#if ENABLE_SH_MATH_SUPPORT
5702 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5703 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005704
5705 arg++; /* skip '+' */
5706 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5707 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005708 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005709 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5710 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005711 val = arith_buf;
5712 break;
5713 }
5714#endif
5715 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005716 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005717 IF_HUSH_TICK(store_val:)
5718 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005719 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5720 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005721 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005722 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005723 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005724 }
5725 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005726 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005727 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5728 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005729 }
5730 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005731 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5732
5733 if (val && val[0]) {
5734 o_addQstr(output, val);
5735 }
5736 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005737
5738 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5739 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005740 if (*p != SPECIAL_VAR_SYMBOL)
5741 *p = SPECIAL_VAR_SYMBOL;
5742
5743#if ENABLE_HUSH_TICK
5744 o_free(&subst_result);
5745#endif
5746 arg = ++p;
5747 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5748
5749 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005750 if (ended_in_ifs) {
5751 o_addchr(output, '\0');
5752 n = o_save_ptr(output, n);
5753 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005754 debug_print_list("expand_vars_to_list[a]", output, n);
5755 /* this part is literal, and it was already pre-quoted
5756 * if needed (much earlier), do not use o_addQstr here! */
5757 o_addstr_with_NUL(output, arg);
5758 debug_print_list("expand_vars_to_list[b]", output, n);
5759 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005760 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005761 ) {
5762 n--;
5763 /* allow to reuse list[n] later without re-growth */
5764 output->has_empty_slot = 1;
5765 } else {
5766 o_addchr(output, '\0');
5767 }
5768
5769 return n;
5770}
5771
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005772static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005773{
5774 int n;
5775 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005776 o_string output = NULL_O_STRING;
5777
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005778 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005779
5780 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005781 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005782 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005783 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005784 }
5785 debug_print_list("expand_variables", &output, n);
5786
5787 /* output.data (malloced in one block) gets returned in "list" */
5788 list = o_finalize_list(&output, n);
5789 debug_print_strings("expand_variables[1]", list);
5790 return list;
5791}
5792
5793static char **expand_strvec_to_strvec(char **argv)
5794{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005795 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005796}
5797
5798#if ENABLE_HUSH_BASH_COMPAT
5799static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5800{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005801 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005802}
5803#endif
5804
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005805/* Used for expansion of right hand of assignments,
5806 * $((...)), heredocs, variable espansion parts.
5807 *
5808 * NB: should NOT do globbing!
5809 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5810 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005811static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005812{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005813#if !ENABLE_HUSH_BASH_COMPAT
5814 const int do_unbackslash = 1;
5815#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005816 char *argv[2], **list;
5817
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005818 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005819 /* This is generally an optimization, but it also
5820 * handles "", which otherwise trips over !list[0] check below.
5821 * (is this ever happens that we actually get str="" here?)
5822 */
5823 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5824 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005825 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005826 return xstrdup(str);
5827 }
5828
5829 argv[0] = (char*)str;
5830 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005831 list = expand_variables(argv, do_unbackslash
5832 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5833 : EXP_FLAG_SINGLEWORD
5834 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005835 if (HUSH_DEBUG)
5836 if (!list[0] || list[1])
5837 bb_error_msg_and_die("BUG in varexp2");
5838 /* actually, just move string 2*sizeof(char*) bytes back */
5839 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005840 if (do_unbackslash)
5841 unbackslash((char*)list);
5842 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005843 return (char*)list;
5844}
5845
5846/* Used for "eval" builtin */
5847static char* expand_strvec_to_string(char **argv)
5848{
5849 char **list;
5850
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005851 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005852 /* Convert all NULs to spaces */
5853 if (list[0]) {
5854 int n = 1;
5855 while (list[n]) {
5856 if (HUSH_DEBUG)
5857 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5858 bb_error_msg_and_die("BUG in varexp3");
5859 /* bash uses ' ' regardless of $IFS contents */
5860 list[n][-1] = ' ';
5861 n++;
5862 }
5863 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02005864 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005865 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5866 return (char*)list;
5867}
5868
5869static char **expand_assignments(char **argv, int count)
5870{
5871 int i;
5872 char **p;
5873
5874 G.expanded_assignments = p = NULL;
5875 /* Expand assignments into one string each */
5876 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005877 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005878 }
5879 G.expanded_assignments = NULL;
5880 return p;
5881}
5882
5883
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005884static void switch_off_special_sigs(unsigned mask)
5885{
5886 unsigned sig = 0;
5887 while ((mask >>= 1) != 0) {
5888 sig++;
5889 if (!(mask & 1))
5890 continue;
5891 if (G.traps) {
5892 if (G.traps[sig] && !G.traps[sig][0])
5893 /* trap is '', has to remain SIG_IGN */
5894 continue;
5895 free(G.traps[sig]);
5896 G.traps[sig] = NULL;
5897 }
5898 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005899 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005900 }
5901}
5902
Denys Vlasenkob347df92011-08-09 22:49:15 +02005903#if BB_MMU
5904/* never called */
5905void re_execute_shell(char ***to_free, const char *s,
5906 char *g_argv0, char **g_argv,
5907 char **builtin_argv) NORETURN;
5908
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005909static void reset_traps_to_defaults(void)
5910{
5911 /* This function is always called in a child shell
5912 * after fork (not vfork, NOMMU doesn't use this function).
5913 */
5914 unsigned sig;
5915 unsigned mask;
5916
5917 /* Child shells are not interactive.
5918 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5919 * Testcase: (while :; do :; done) + ^Z should background.
5920 * Same goes for SIGTERM, SIGHUP, SIGINT.
5921 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005922 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5923 if (!G.traps && !mask)
5924 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005925
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005926 /* Switch off special sigs */
5927 switch_off_special_sigs(mask);
5928#if ENABLE_HUSH_JOB
5929 G_fatal_sig_mask = 0;
5930#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005931 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005932 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5933 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005934
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005935 if (!G.traps)
5936 return;
5937
5938 /* Reset all sigs to default except ones with empty traps */
5939 for (sig = 0; sig < NSIG; sig++) {
5940 if (!G.traps[sig])
5941 continue; /* no trap: nothing to do */
5942 if (!G.traps[sig][0])
5943 continue; /* empty trap: has to remain SIG_IGN */
5944 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005945 free(G.traps[sig]);
5946 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005947 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005948 if (sig == 0)
5949 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005950 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005951 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005952}
5953
5954#else /* !BB_MMU */
5955
5956static void re_execute_shell(char ***to_free, const char *s,
5957 char *g_argv0, char **g_argv,
5958 char **builtin_argv) NORETURN;
5959static void re_execute_shell(char ***to_free, const char *s,
5960 char *g_argv0, char **g_argv,
5961 char **builtin_argv)
5962{
5963# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5964 /* delims + 2 * (number of bytes in printed hex numbers) */
5965 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5966 char *heredoc_argv[4];
5967 struct variable *cur;
5968# if ENABLE_HUSH_FUNCTIONS
5969 struct function *funcp;
5970# endif
5971 char **argv, **pp;
5972 unsigned cnt;
5973 unsigned long long empty_trap_mask;
5974
5975 if (!g_argv0) { /* heredoc */
5976 argv = heredoc_argv;
5977 argv[0] = (char *) G.argv0_for_re_execing;
5978 argv[1] = (char *) "-<";
5979 argv[2] = (char *) s;
5980 argv[3] = NULL;
5981 pp = &argv[3]; /* used as pointer to empty environment */
5982 goto do_exec;
5983 }
5984
5985 cnt = 0;
5986 pp = builtin_argv;
5987 if (pp) while (*pp++)
5988 cnt++;
5989
5990 empty_trap_mask = 0;
5991 if (G.traps) {
5992 int sig;
5993 for (sig = 1; sig < NSIG; sig++) {
5994 if (G.traps[sig] && !G.traps[sig][0])
5995 empty_trap_mask |= 1LL << sig;
5996 }
5997 }
5998
5999 sprintf(param_buf, NOMMU_HACK_FMT
6000 , (unsigned) G.root_pid
6001 , (unsigned) G.root_ppid
6002 , (unsigned) G.last_bg_pid
6003 , (unsigned) G.last_exitcode
6004 , cnt
6005 , empty_trap_mask
6006 IF_HUSH_LOOPS(, G.depth_of_loop)
6007 );
6008# undef NOMMU_HACK_FMT
6009 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6010 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6011 */
6012 cnt += 6;
6013 for (cur = G.top_var; cur; cur = cur->next) {
6014 if (!cur->flg_export || cur->flg_read_only)
6015 cnt += 2;
6016 }
6017# if ENABLE_HUSH_FUNCTIONS
6018 for (funcp = G.top_func; funcp; funcp = funcp->next)
6019 cnt += 3;
6020# endif
6021 pp = g_argv;
6022 while (*pp++)
6023 cnt++;
6024 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6025 *pp++ = (char *) G.argv0_for_re_execing;
6026 *pp++ = param_buf;
6027 for (cur = G.top_var; cur; cur = cur->next) {
6028 if (strcmp(cur->varstr, hush_version_str) == 0)
6029 continue;
6030 if (cur->flg_read_only) {
6031 *pp++ = (char *) "-R";
6032 *pp++ = cur->varstr;
6033 } else if (!cur->flg_export) {
6034 *pp++ = (char *) "-V";
6035 *pp++ = cur->varstr;
6036 }
6037 }
6038# if ENABLE_HUSH_FUNCTIONS
6039 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6040 *pp++ = (char *) "-F";
6041 *pp++ = funcp->name;
6042 *pp++ = funcp->body_as_string;
6043 }
6044# endif
6045 /* We can pass activated traps here. Say, -Tnn:trap_string
6046 *
6047 * However, POSIX says that subshells reset signals with traps
6048 * to SIG_DFL.
6049 * I tested bash-3.2 and it not only does that with true subshells
6050 * of the form ( list ), but with any forked children shells.
6051 * I set trap "echo W" WINCH; and then tried:
6052 *
6053 * { echo 1; sleep 20; echo 2; } &
6054 * while true; do echo 1; sleep 20; echo 2; break; done &
6055 * true | { echo 1; sleep 20; echo 2; } | cat
6056 *
6057 * In all these cases sending SIGWINCH to the child shell
6058 * did not run the trap. If I add trap "echo V" WINCH;
6059 * _inside_ group (just before echo 1), it works.
6060 *
6061 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006062 */
6063 *pp++ = (char *) "-c";
6064 *pp++ = (char *) s;
6065 if (builtin_argv) {
6066 while (*++builtin_argv)
6067 *pp++ = *builtin_argv;
6068 *pp++ = (char *) "";
6069 }
6070 *pp++ = g_argv0;
6071 while (*g_argv)
6072 *pp++ = *g_argv++;
6073 /* *pp = NULL; - is already there */
6074 pp = environ;
6075
6076 do_exec:
6077 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006078 /* Don't propagate SIG_IGN to the child */
6079 if (SPECIAL_JOBSTOP_SIGS != 0)
6080 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006081 execve(bb_busybox_exec_path, argv, pp);
6082 /* Fallback. Useful for init=/bin/hush usage etc */
6083 if (argv[0][0] == '/')
6084 execve(argv[0], argv, pp);
6085 xfunc_error_retval = 127;
6086 bb_error_msg_and_die("can't re-execute the shell");
6087}
6088#endif /* !BB_MMU */
6089
6090
6091static int run_and_free_list(struct pipe *pi);
6092
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006093/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006094 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6095 * end_trigger controls how often we stop parsing
6096 * NUL: parse all, execute, return
6097 * ';': parse till ';' or newline, execute, repeat till EOF
6098 */
6099static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006100{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006101 /* Why we need empty flag?
6102 * An obscure corner case "false; ``; echo $?":
6103 * empty command in `` should still set $? to 0.
6104 * But we can't just set $? to 0 at the start,
6105 * this breaks "false; echo `echo $?`" case.
6106 */
6107 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006108 while (1) {
6109 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006110
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006111#if ENABLE_HUSH_INTERACTIVE
6112 if (end_trigger == ';')
6113 inp->promptmode = 0; /* PS1 */
6114#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006115 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006116 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6117 /* If we are in "big" script
6118 * (not in `cmd` or something similar)...
6119 */
6120 if (pipe_list == ERR_PTR && end_trigger == ';') {
6121 /* Discard cached input (rest of line) */
6122 int ch = inp->last_char;
6123 while (ch != EOF && ch != '\n') {
6124 //bb_error_msg("Discarded:'%c'", ch);
6125 ch = i_getch(inp);
6126 }
6127 /* Force prompt */
6128 inp->p = NULL;
6129 /* This stream isn't empty */
6130 empty = 0;
6131 continue;
6132 }
6133 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006134 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006135 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006136 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006137 debug_print_tree(pipe_list, 0);
6138 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6139 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006140 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006141 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006142 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006143 }
Eric Andersen25f27032001-04-26 23:22:31 +00006144}
6145
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006146static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006147{
6148 struct in_str input;
6149 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006150 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006151}
6152
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006153static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006154{
Eric Andersen25f27032001-04-26 23:22:31 +00006155 struct in_str input;
6156 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006157 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006158}
6159
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006160#if ENABLE_HUSH_TICK
6161static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6162{
6163 pid_t pid;
6164 int channel[2];
6165# if !BB_MMU
6166 char **to_free = NULL;
6167# endif
6168
6169 xpipe(channel);
6170 pid = BB_MMU ? xfork() : xvfork();
6171 if (pid == 0) { /* child */
6172 disable_restore_tty_pgrp_on_exit();
6173 /* Process substitution is not considered to be usual
6174 * 'command execution'.
6175 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6176 */
6177 bb_signals(0
6178 + (1 << SIGTSTP)
6179 + (1 << SIGTTIN)
6180 + (1 << SIGTTOU)
6181 , SIG_IGN);
6182 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6183 close(channel[0]); /* NB: close _first_, then move fd! */
6184 xmove_fd(channel[1], 1);
6185 /* Prevent it from trying to handle ctrl-z etc */
6186 IF_HUSH_JOB(G.run_list_level = 1;)
6187 /* Awful hack for `trap` or $(trap).
6188 *
6189 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6190 * contains an example where "trap" is executed in a subshell:
6191 *
6192 * save_traps=$(trap)
6193 * ...
6194 * eval "$save_traps"
6195 *
6196 * Standard does not say that "trap" in subshell shall print
6197 * parent shell's traps. It only says that its output
6198 * must have suitable form, but then, in the above example
6199 * (which is not supposed to be normative), it implies that.
6200 *
6201 * bash (and probably other shell) does implement it
6202 * (traps are reset to defaults, but "trap" still shows them),
6203 * but as a result, "trap" logic is hopelessly messed up:
6204 *
6205 * # trap
6206 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6207 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6208 * # true | trap <--- trap is in subshell - no output (ditto)
6209 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6210 * trap -- 'echo Ho' SIGWINCH
6211 * # echo `(trap)` <--- in subshell in subshell - output
6212 * trap -- 'echo Ho' SIGWINCH
6213 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6214 * trap -- 'echo Ho' SIGWINCH
6215 *
6216 * The rules when to forget and when to not forget traps
6217 * get really complex and nonsensical.
6218 *
6219 * Our solution: ONLY bare $(trap) or `trap` is special.
6220 */
6221 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006222 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006223 && skip_whitespace(s + 4)[0] == '\0'
6224 ) {
6225 static const char *const argv[] = { NULL, NULL };
6226 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006227 fflush_all(); /* important */
6228 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006229 }
6230# if BB_MMU
6231 reset_traps_to_defaults();
6232 parse_and_run_string(s);
6233 _exit(G.last_exitcode);
6234# else
6235 /* We re-execute after vfork on NOMMU. This makes this script safe:
6236 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6237 * huge=`cat BIG` # was blocking here forever
6238 * echo OK
6239 */
6240 re_execute_shell(&to_free,
6241 s,
6242 G.global_argv[0],
6243 G.global_argv + 1,
6244 NULL);
6245# endif
6246 }
6247
6248 /* parent */
6249 *pid_p = pid;
6250# if ENABLE_HUSH_FAST
6251 G.count_SIGCHLD++;
6252//bb_error_msg("[%d] fork in generate_stream_from_string:"
6253// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6254// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6255# endif
6256 enable_restore_tty_pgrp_on_exit();
6257# if !BB_MMU
6258 free(to_free);
6259# endif
6260 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006261 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006262}
6263
6264/* Return code is exit status of the process that is run. */
6265static int process_command_subs(o_string *dest, const char *s)
6266{
6267 FILE *fp;
6268 struct in_str pipe_str;
6269 pid_t pid;
6270 int status, ch, eol_cnt;
6271
6272 fp = generate_stream_from_string(s, &pid);
6273
6274 /* Now send results of command back into original context */
6275 setup_file_in_str(&pipe_str, fp);
6276 eol_cnt = 0;
6277 while ((ch = i_getch(&pipe_str)) != EOF) {
6278 if (ch == '\n') {
6279 eol_cnt++;
6280 continue;
6281 }
6282 while (eol_cnt) {
6283 o_addchr(dest, '\n');
6284 eol_cnt--;
6285 }
6286 o_addQchr(dest, ch);
6287 }
6288
6289 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006290 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006291 /* We need to extract exitcode. Test case
6292 * "true; echo `sleep 1; false` $?"
6293 * should print 1 */
6294 safe_waitpid(pid, &status, 0);
6295 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6296 return WEXITSTATUS(status);
6297}
6298#endif /* ENABLE_HUSH_TICK */
6299
6300
6301static void setup_heredoc(struct redir_struct *redir)
6302{
6303 struct fd_pair pair;
6304 pid_t pid;
6305 int len, written;
6306 /* the _body_ of heredoc (misleading field name) */
6307 const char *heredoc = redir->rd_filename;
6308 char *expanded;
6309#if !BB_MMU
6310 char **to_free;
6311#endif
6312
6313 expanded = NULL;
6314 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006315 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006316 if (expanded)
6317 heredoc = expanded;
6318 }
6319 len = strlen(heredoc);
6320
6321 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6322 xpiped_pair(pair);
6323 xmove_fd(pair.rd, redir->rd_fd);
6324
6325 /* Try writing without forking. Newer kernels have
6326 * dynamically growing pipes. Must use non-blocking write! */
6327 ndelay_on(pair.wr);
6328 while (1) {
6329 written = write(pair.wr, heredoc, len);
6330 if (written <= 0)
6331 break;
6332 len -= written;
6333 if (len == 0) {
6334 close(pair.wr);
6335 free(expanded);
6336 return;
6337 }
6338 heredoc += written;
6339 }
6340 ndelay_off(pair.wr);
6341
6342 /* Okay, pipe buffer was not big enough */
6343 /* Note: we must not create a stray child (bastard? :)
6344 * for the unsuspecting parent process. Child creates a grandchild
6345 * and exits before parent execs the process which consumes heredoc
6346 * (that exec happens after we return from this function) */
6347#if !BB_MMU
6348 to_free = NULL;
6349#endif
6350 pid = xvfork();
6351 if (pid == 0) {
6352 /* child */
6353 disable_restore_tty_pgrp_on_exit();
6354 pid = BB_MMU ? xfork() : xvfork();
6355 if (pid != 0)
6356 _exit(0);
6357 /* grandchild */
6358 close(redir->rd_fd); /* read side of the pipe */
6359#if BB_MMU
6360 full_write(pair.wr, heredoc, len); /* may loop or block */
6361 _exit(0);
6362#else
6363 /* Delegate blocking writes to another process */
6364 xmove_fd(pair.wr, STDOUT_FILENO);
6365 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6366#endif
6367 }
6368 /* parent */
6369#if ENABLE_HUSH_FAST
6370 G.count_SIGCHLD++;
6371//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6372#endif
6373 enable_restore_tty_pgrp_on_exit();
6374#if !BB_MMU
6375 free(to_free);
6376#endif
6377 close(pair.wr);
6378 free(expanded);
6379 wait(NULL); /* wait till child has died */
6380}
6381
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006382/* fd: redirect wants this fd to be used (e.g. 3>file).
6383 * Move all conflicting internally used fds,
6384 * and remember them so that we can restore them later.
6385 */
6386static int save_fds_on_redirect(int fd, int squirrel[3])
6387{
6388 if (squirrel) {
6389 /* Handle redirects of fds 0,1,2 */
6390
6391 /* If we collide with an already moved stdio fd... */
6392 if (fd == squirrel[0]) {
6393 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6394 return 1;
6395 }
6396 if (fd == squirrel[1]) {
6397 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6398 return 1;
6399 }
6400 if (fd == squirrel[2]) {
6401 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6402 return 1;
6403 }
6404 /* If we are about to redirect stdio fd, and did not yet move it... */
6405 if (fd <= 2 && squirrel[fd] < 0) {
6406 /* We avoid taking stdio fds */
6407 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6408 if (squirrel[fd] < 0 && errno != EBADF)
6409 xfunc_die();
6410 return 0; /* "we did not close fd" */
6411 }
6412 }
6413
6414#if ENABLE_HUSH_INTERACTIVE
6415 if (fd != 0 && fd == G.interactive_fd) {
6416 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6417 return 1;
6418 }
6419#endif
6420
6421 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6422 * (1) Redirect in a forked child. No need to save FILEs' fds,
6423 * we aren't going to use them anymore, ok to trash.
6424 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6425 * but how are we doing to use them?
6426 * "fileno(fd) = new_fd" can't be done.
6427 */
6428 if (!squirrel)
6429 return 0;
6430
6431 return save_FILEs_on_redirect(fd);
6432}
6433
6434static void restore_redirects(int squirrel[3])
6435{
6436 int i, fd;
6437 for (i = 0; i <= 2; i++) {
6438 fd = squirrel[i];
6439 if (fd != -1) {
6440 /* We simply die on error */
6441 xmove_fd(fd, i);
6442 }
6443 }
6444
6445 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6446
6447 restore_redirected_FILEs();
6448}
6449
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006450/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6451 * and stderr if they are redirected. */
6452static int setup_redirects(struct command *prog, int squirrel[])
6453{
6454 int openfd, mode;
6455 struct redir_struct *redir;
6456
6457 for (redir = prog->redirects; redir; redir = redir->next) {
6458 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006459 /* "rd_fd<<HERE" case */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006460 save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006461 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6462 * of the heredoc */
6463 debug_printf_parse("set heredoc '%s'\n",
6464 redir->rd_filename);
6465 setup_heredoc(redir);
6466 continue;
6467 }
6468
6469 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006470 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006471 char *p;
6472 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02006473 /*
6474 * Examples:
6475 * "cmd >" (no filename)
6476 * "cmd > <file" (2nd redirect starts too early)
6477 */
6478 die_if_script("syntax error: %s", "invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006479 continue;
6480 }
6481 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006482 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006483 openfd = open_or_warn(p, mode);
6484 free(p);
6485 if (openfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006486 /* Error message from open_or_warn can be lost
6487 * if stderr has been redirected, but bash
6488 * and ash both lose it as well
6489 * (though zsh doesn't!)
6490 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006491 return 1;
6492 }
6493 } else {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006494 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006495 openfd = redir->rd_dup;
6496 }
6497
6498 if (openfd != redir->rd_fd) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006499 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006500 if (openfd == REDIRFD_CLOSE) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006501 /* "rd_fd >&-" means "close me" */
6502 if (!closed) {
6503 /* ^^^ optimization: saving may already
6504 * have closed it. If not... */
6505 close(redir->rd_fd);
6506 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006507 } else {
6508 xdup2(openfd, redir->rd_fd);
6509 if (redir->rd_dup == REDIRFD_TO_FILE)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006510 /* "rd_fd > FILE" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006511 close(openfd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006512 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006513 }
6514 }
6515 }
6516 return 0;
6517}
6518
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006519static char *find_in_path(const char *arg)
6520{
6521 char *ret = NULL;
6522 const char *PATH = get_local_var_value("PATH");
6523
6524 if (!PATH)
6525 return NULL;
6526
6527 while (1) {
6528 const char *end = strchrnul(PATH, ':');
6529 int sz = end - PATH; /* must be int! */
6530
6531 free(ret);
6532 if (sz != 0) {
6533 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6534 } else {
6535 /* We have xxx::yyyy in $PATH,
6536 * it means "use current dir" */
6537 ret = xstrdup(arg);
6538 }
6539 if (access(ret, F_OK) == 0)
6540 break;
6541
6542 if (*end == '\0') {
6543 free(ret);
6544 return NULL;
6545 }
6546 PATH = end + 1;
6547 }
6548
6549 return ret;
6550}
6551
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006552static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006553 const struct built_in_command *x,
6554 const struct built_in_command *end)
6555{
6556 while (x != end) {
6557 if (strcmp(name, x->b_cmd) != 0) {
6558 x++;
6559 continue;
6560 }
6561 debug_printf_exec("found builtin '%s'\n", name);
6562 return x;
6563 }
6564 return NULL;
6565}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006566static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006567{
6568 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6569}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006570static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006571{
6572 const struct built_in_command *x = find_builtin1(name);
6573 if (x)
6574 return x;
6575 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6576}
6577
6578#if ENABLE_HUSH_FUNCTIONS
6579static struct function **find_function_slot(const char *name)
6580{
6581 struct function **funcpp = &G.top_func;
6582 while (*funcpp) {
6583 if (strcmp(name, (*funcpp)->name) == 0) {
6584 break;
6585 }
6586 funcpp = &(*funcpp)->next;
6587 }
6588 return funcpp;
6589}
6590
6591static const struct function *find_function(const char *name)
6592{
6593 const struct function *funcp = *find_function_slot(name);
6594 if (funcp)
6595 debug_printf_exec("found function '%s'\n", name);
6596 return funcp;
6597}
6598
6599/* Note: takes ownership on name ptr */
6600static struct function *new_function(char *name)
6601{
6602 struct function **funcpp = find_function_slot(name);
6603 struct function *funcp = *funcpp;
6604
6605 if (funcp != NULL) {
6606 struct command *cmd = funcp->parent_cmd;
6607 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6608 if (!cmd) {
6609 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6610 free(funcp->name);
6611 /* Note: if !funcp->body, do not free body_as_string!
6612 * This is a special case of "-F name body" function:
6613 * body_as_string was not malloced! */
6614 if (funcp->body) {
6615 free_pipe_list(funcp->body);
6616# if !BB_MMU
6617 free(funcp->body_as_string);
6618# endif
6619 }
6620 } else {
6621 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6622 cmd->argv[0] = funcp->name;
6623 cmd->group = funcp->body;
6624# if !BB_MMU
6625 cmd->group_as_string = funcp->body_as_string;
6626# endif
6627 }
6628 } else {
6629 debug_printf_exec("remembering new function '%s'\n", name);
6630 funcp = *funcpp = xzalloc(sizeof(*funcp));
6631 /*funcp->next = NULL;*/
6632 }
6633
6634 funcp->name = name;
6635 return funcp;
6636}
6637
6638static void unset_func(const char *name)
6639{
6640 struct function **funcpp = find_function_slot(name);
6641 struct function *funcp = *funcpp;
6642
6643 if (funcp != NULL) {
6644 debug_printf_exec("freeing function '%s'\n", funcp->name);
6645 *funcpp = funcp->next;
6646 /* funcp is unlinked now, deleting it.
6647 * Note: if !funcp->body, the function was created by
6648 * "-F name body", do not free ->body_as_string
6649 * and ->name as they were not malloced. */
6650 if (funcp->body) {
6651 free_pipe_list(funcp->body);
6652 free(funcp->name);
6653# if !BB_MMU
6654 free(funcp->body_as_string);
6655# endif
6656 }
6657 free(funcp);
6658 }
6659}
6660
6661# if BB_MMU
6662#define exec_function(to_free, funcp, argv) \
6663 exec_function(funcp, argv)
6664# endif
6665static void exec_function(char ***to_free,
6666 const struct function *funcp,
6667 char **argv) NORETURN;
6668static void exec_function(char ***to_free,
6669 const struct function *funcp,
6670 char **argv)
6671{
6672# if BB_MMU
6673 int n = 1;
6674
6675 argv[0] = G.global_argv[0];
6676 G.global_argv = argv;
6677 while (*++argv)
6678 n++;
6679 G.global_argc = n;
6680 /* On MMU, funcp->body is always non-NULL */
6681 n = run_list(funcp->body);
6682 fflush_all();
6683 _exit(n);
6684# else
6685 re_execute_shell(to_free,
6686 funcp->body_as_string,
6687 G.global_argv[0],
6688 argv + 1,
6689 NULL);
6690# endif
6691}
6692
6693static int run_function(const struct function *funcp, char **argv)
6694{
6695 int rc;
6696 save_arg_t sv;
6697 smallint sv_flg;
6698
6699 save_and_replace_G_args(&sv, argv);
6700
6701 /* "we are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006702 sv_flg = G_flag_return_in_progress;
6703 G_flag_return_in_progress = -1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006704# if ENABLE_HUSH_LOCAL
6705 G.func_nest_level++;
6706# endif
6707
6708 /* On MMU, funcp->body is always non-NULL */
6709# if !BB_MMU
6710 if (!funcp->body) {
6711 /* Function defined by -F */
6712 parse_and_run_string(funcp->body_as_string);
6713 rc = G.last_exitcode;
6714 } else
6715# endif
6716 {
6717 rc = run_list(funcp->body);
6718 }
6719
6720# if ENABLE_HUSH_LOCAL
6721 {
6722 struct variable *var;
6723 struct variable **var_pp;
6724
6725 var_pp = &G.top_var;
6726 while ((var = *var_pp) != NULL) {
6727 if (var->func_nest_level < G.func_nest_level) {
6728 var_pp = &var->next;
6729 continue;
6730 }
6731 /* Unexport */
6732 if (var->flg_export)
6733 bb_unsetenv(var->varstr);
6734 /* Remove from global list */
6735 *var_pp = var->next;
6736 /* Free */
6737 if (!var->max_len)
6738 free(var->varstr);
6739 free(var);
6740 }
6741 G.func_nest_level--;
6742 }
6743# endif
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006744 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006745
6746 restore_G_args(&sv, argv);
6747
6748 return rc;
6749}
6750#endif /* ENABLE_HUSH_FUNCTIONS */
6751
6752
6753#if BB_MMU
6754#define exec_builtin(to_free, x, argv) \
6755 exec_builtin(x, argv)
6756#else
6757#define exec_builtin(to_free, x, argv) \
6758 exec_builtin(to_free, argv)
6759#endif
6760static void exec_builtin(char ***to_free,
6761 const struct built_in_command *x,
6762 char **argv) NORETURN;
6763static void exec_builtin(char ***to_free,
6764 const struct built_in_command *x,
6765 char **argv)
6766{
6767#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006768 int rcode;
6769 fflush_all();
6770 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006771 fflush_all();
6772 _exit(rcode);
6773#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006774 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006775 /* On NOMMU, we must never block!
6776 * Example: { sleep 99 | read line; } & echo Ok
6777 */
6778 re_execute_shell(to_free,
6779 argv[0],
6780 G.global_argv[0],
6781 G.global_argv + 1,
6782 argv);
6783#endif
6784}
6785
6786
6787static void execvp_or_die(char **argv) NORETURN;
6788static void execvp_or_die(char **argv)
6789{
Denys Vlasenko04465da2016-10-03 01:01:15 +02006790 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006791 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006792 /* Don't propagate SIG_IGN to the child */
6793 if (SPECIAL_JOBSTOP_SIGS != 0)
6794 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006795 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02006796 e = 2;
6797 if (errno == EACCES) e = 126;
6798 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006799 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02006800 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006801}
6802
6803#if ENABLE_HUSH_MODE_X
6804static void dump_cmd_in_x_mode(char **argv)
6805{
6806 if (G_x_mode && argv) {
6807 /* We want to output the line in one write op */
6808 char *buf, *p;
6809 int len;
6810 int n;
6811
6812 len = 3;
6813 n = 0;
6814 while (argv[n])
6815 len += strlen(argv[n++]) + 1;
6816 buf = xmalloc(len);
6817 buf[0] = '+';
6818 p = buf + 1;
6819 n = 0;
6820 while (argv[n])
6821 p += sprintf(p, " %s", argv[n++]);
6822 *p++ = '\n';
6823 *p = '\0';
6824 fputs(buf, stderr);
6825 free(buf);
6826 }
6827}
6828#else
6829# define dump_cmd_in_x_mode(argv) ((void)0)
6830#endif
6831
6832#if BB_MMU
6833#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6834 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6835#define pseudo_exec(nommu_save, command, argv_expanded) \
6836 pseudo_exec(command, argv_expanded)
6837#endif
6838
6839/* Called after [v]fork() in run_pipe, or from builtin_exec.
6840 * Never returns.
6841 * Don't exit() here. If you don't exec, use _exit instead.
6842 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006843 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006844 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006845static void pseudo_exec_argv(nommu_save_t *nommu_save,
6846 char **argv, int assignment_cnt,
6847 char **argv_expanded) NORETURN;
6848static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6849 char **argv, int assignment_cnt,
6850 char **argv_expanded)
6851{
6852 char **new_env;
6853
6854 new_env = expand_assignments(argv, assignment_cnt);
6855 dump_cmd_in_x_mode(new_env);
6856
6857 if (!argv[assignment_cnt]) {
6858 /* Case when we are here: ... | var=val | ...
6859 * (note that we do not exit early, i.e., do not optimize out
6860 * expand_assignments(): think about ... | var=`sleep 1` | ...
6861 */
6862 free_strings(new_env);
6863 _exit(EXIT_SUCCESS);
6864 }
6865
6866#if BB_MMU
6867 set_vars_and_save_old(new_env);
6868 free(new_env); /* optional */
6869 /* we can also destroy set_vars_and_save_old's return value,
6870 * to save memory */
6871#else
6872 nommu_save->new_env = new_env;
6873 nommu_save->old_vars = set_vars_and_save_old(new_env);
6874#endif
6875
6876 if (argv_expanded) {
6877 argv = argv_expanded;
6878 } else {
6879 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6880#if !BB_MMU
6881 nommu_save->argv = argv;
6882#endif
6883 }
6884 dump_cmd_in_x_mode(argv);
6885
6886#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6887 if (strchr(argv[0], '/') != NULL)
6888 goto skip;
6889#endif
6890
6891 /* Check if the command matches any of the builtins.
6892 * Depending on context, this might be redundant. But it's
6893 * easier to waste a few CPU cycles than it is to figure out
6894 * if this is one of those cases.
6895 */
6896 {
6897 /* On NOMMU, it is more expensive to re-execute shell
6898 * just in order to run echo or test builtin.
6899 * It's better to skip it here and run corresponding
6900 * non-builtin later. */
6901 const struct built_in_command *x;
6902 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6903 if (x) {
6904 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6905 }
6906 }
6907#if ENABLE_HUSH_FUNCTIONS
6908 /* Check if the command matches any functions */
6909 {
6910 const struct function *funcp = find_function(argv[0]);
6911 if (funcp) {
6912 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6913 }
6914 }
6915#endif
6916
6917#if ENABLE_FEATURE_SH_STANDALONE
6918 /* Check if the command matches any busybox applets */
6919 {
6920 int a = find_applet_by_name(argv[0]);
6921 if (a >= 0) {
6922# if BB_MMU /* see above why on NOMMU it is not allowed */
6923 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006924 /* Do not leak open fds from opened script files etc */
6925 close_all_FILE_list();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006926 debug_printf_exec("running applet '%s'\n", argv[0]);
6927 run_applet_no_and_exit(a, argv);
6928 }
6929# endif
6930 /* Re-exec ourselves */
6931 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006932 /* Don't propagate SIG_IGN to the child */
6933 if (SPECIAL_JOBSTOP_SIGS != 0)
6934 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006935 execv(bb_busybox_exec_path, argv);
6936 /* If they called chroot or otherwise made the binary no longer
6937 * executable, fall through */
6938 }
6939 }
6940#endif
6941
6942#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6943 skip:
6944#endif
6945 execvp_or_die(argv);
6946}
6947
6948/* Called after [v]fork() in run_pipe
6949 */
6950static void pseudo_exec(nommu_save_t *nommu_save,
6951 struct command *command,
6952 char **argv_expanded) NORETURN;
6953static void pseudo_exec(nommu_save_t *nommu_save,
6954 struct command *command,
6955 char **argv_expanded)
6956{
6957 if (command->argv) {
6958 pseudo_exec_argv(nommu_save, command->argv,
6959 command->assignment_cnt, argv_expanded);
6960 }
6961
6962 if (command->group) {
6963 /* Cases when we are here:
6964 * ( list )
6965 * { list } &
6966 * ... | ( list ) | ...
6967 * ... | { list } | ...
6968 */
6969#if BB_MMU
6970 int rcode;
6971 debug_printf_exec("pseudo_exec: run_list\n");
6972 reset_traps_to_defaults();
6973 rcode = run_list(command->group);
6974 /* OK to leak memory by not calling free_pipe_list,
6975 * since this process is about to exit */
6976 _exit(rcode);
6977#else
6978 re_execute_shell(&nommu_save->argv_from_re_execing,
6979 command->group_as_string,
6980 G.global_argv[0],
6981 G.global_argv + 1,
6982 NULL);
6983#endif
6984 }
6985
6986 /* Case when we are here: ... | >file */
6987 debug_printf_exec("pseudo_exec'ed null command\n");
6988 _exit(EXIT_SUCCESS);
6989}
6990
6991#if ENABLE_HUSH_JOB
6992static const char *get_cmdtext(struct pipe *pi)
6993{
6994 char **argv;
6995 char *p;
6996 int len;
6997
6998 /* This is subtle. ->cmdtext is created only on first backgrounding.
6999 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7000 * On subsequent bg argv is trashed, but we won't use it */
7001 if (pi->cmdtext)
7002 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007003
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007004 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007005 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007006 pi->cmdtext = xzalloc(1);
7007 return pi->cmdtext;
7008 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007009 len = 0;
7010 do {
7011 len += strlen(*argv) + 1;
7012 } while (*++argv);
7013 p = xmalloc(len);
7014 pi->cmdtext = p;
7015 argv = pi->cmds[0].argv;
7016 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007017 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007018 *p++ = ' ';
7019 } while (*++argv);
7020 p[-1] = '\0';
7021 return pi->cmdtext;
7022}
7023
7024static void insert_bg_job(struct pipe *pi)
7025{
7026 struct pipe *job, **jobp;
7027 int i;
7028
7029 /* Linear search for the ID of the job to use */
7030 pi->jobid = 1;
7031 for (job = G.job_list; job; job = job->next)
7032 if (job->jobid >= pi->jobid)
7033 pi->jobid = job->jobid + 1;
7034
7035 /* Add job to the list of running jobs */
7036 jobp = &G.job_list;
7037 while ((job = *jobp) != NULL)
7038 jobp = &job->next;
7039 job = *jobp = xmalloc(sizeof(*job));
7040
7041 *job = *pi; /* physical copy */
7042 job->next = NULL;
7043 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7044 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7045 for (i = 0; i < pi->num_cmds; i++) {
7046 job->cmds[i].pid = pi->cmds[i].pid;
7047 /* all other fields are not used and stay zero */
7048 }
7049 job->cmdtext = xstrdup(get_cmdtext(pi));
7050
7051 if (G_interactive_fd)
7052 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
7053 G.last_jobid = job->jobid;
7054}
7055
7056static void remove_bg_job(struct pipe *pi)
7057{
7058 struct pipe *prev_pipe;
7059
7060 if (pi == G.job_list) {
7061 G.job_list = pi->next;
7062 } else {
7063 prev_pipe = G.job_list;
7064 while (prev_pipe->next != pi)
7065 prev_pipe = prev_pipe->next;
7066 prev_pipe->next = pi->next;
7067 }
7068 if (G.job_list)
7069 G.last_jobid = G.job_list->jobid;
7070 else
7071 G.last_jobid = 0;
7072}
7073
7074/* Remove a backgrounded job */
7075static void delete_finished_bg_job(struct pipe *pi)
7076{
7077 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007078 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007079}
7080#endif /* JOB */
7081
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007082static int job_exited_or_stopped(struct pipe *pi)
7083{
7084 int rcode, i;
7085
7086 if (pi->alive_cmds != pi->stopped_cmds)
7087 return -1;
7088
7089 /* All processes in fg pipe have exited or stopped */
7090 rcode = 0;
7091 i = pi->num_cmds;
7092 while (--i >= 0) {
7093 rcode = pi->cmds[i].cmd_exitcode;
7094 /* usually last process gives overall exitstatus,
7095 * but with "set -o pipefail", last *failed* process does */
7096 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7097 break;
7098 }
7099 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7100 return rcode;
7101}
7102
Denys Vlasenko7e675362016-10-28 21:57:31 +02007103static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007104{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007105#if ENABLE_HUSH_JOB
7106 struct pipe *pi;
7107#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007108 int i, dead;
7109
7110 dead = WIFEXITED(status) || WIFSIGNALED(status);
7111
7112#if DEBUG_JOBS
7113 if (WIFSTOPPED(status))
7114 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7115 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7116 if (WIFSIGNALED(status))
7117 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7118 childpid, WTERMSIG(status), WEXITSTATUS(status));
7119 if (WIFEXITED(status))
7120 debug_printf_jobs("pid %d exited, exitcode %d\n",
7121 childpid, WEXITSTATUS(status));
7122#endif
7123 /* Were we asked to wait for a fg pipe? */
7124 if (fg_pipe) {
7125 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007126
Denys Vlasenko7e675362016-10-28 21:57:31 +02007127 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007128 int rcode;
7129
Denys Vlasenko7e675362016-10-28 21:57:31 +02007130 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7131 if (fg_pipe->cmds[i].pid != childpid)
7132 continue;
7133 if (dead) {
7134 int ex;
7135 fg_pipe->cmds[i].pid = 0;
7136 fg_pipe->alive_cmds--;
7137 ex = WEXITSTATUS(status);
7138 /* bash prints killer signal's name for *last*
7139 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7140 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7141 */
7142 if (WIFSIGNALED(status)) {
7143 int sig = WTERMSIG(status);
7144 if (i == fg_pipe->num_cmds-1)
7145 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7146 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7147 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7148 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7149 * Maybe we need to use sig | 128? */
7150 ex = sig + 128;
7151 }
7152 fg_pipe->cmds[i].cmd_exitcode = ex;
7153 } else {
7154 fg_pipe->stopped_cmds++;
7155 }
7156 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7157 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007158 rcode = job_exited_or_stopped(fg_pipe);
7159 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007160/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7161 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7162 * and "killall -STOP cat" */
7163 if (G_interactive_fd) {
7164#if ENABLE_HUSH_JOB
7165 if (fg_pipe->alive_cmds != 0)
7166 insert_bg_job(fg_pipe);
7167#endif
7168 return rcode;
7169 }
7170 if (fg_pipe->alive_cmds == 0)
7171 return rcode;
7172 }
7173 /* There are still running processes in the fg_pipe */
7174 return -1;
7175 }
7176 /* It wasnt in fg_pipe, look for process in bg pipes */
7177 }
7178
7179#if ENABLE_HUSH_JOB
7180 /* We were asked to wait for bg or orphaned children */
7181 /* No need to remember exitcode in this case */
7182 for (pi = G.job_list; pi; pi = pi->next) {
7183 for (i = 0; i < pi->num_cmds; i++) {
7184 if (pi->cmds[i].pid == childpid)
7185 goto found_pi_and_prognum;
7186 }
7187 }
7188 /* Happens when shell is used as init process (init=/bin/sh) */
7189 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7190 return -1; /* this wasn't a process from fg_pipe */
7191
7192 found_pi_and_prognum:
7193 if (dead) {
7194 /* child exited */
7195 pi->cmds[i].pid = 0;
7196 pi->cmds[i].cmd_exitcode = WEXITSTATUS(status);
7197 if (WIFSIGNALED(status))
7198 pi->cmds[i].cmd_exitcode = 128 + WTERMSIG(status);
7199 pi->alive_cmds--;
7200 if (!pi->alive_cmds) {
7201 if (G_interactive_fd)
7202 printf(JOB_STATUS_FORMAT, pi->jobid,
7203 "Done", pi->cmdtext);
7204 delete_finished_bg_job(pi);
7205 }
7206 } else {
7207 /* child stopped */
7208 pi->stopped_cmds++;
7209 }
7210#endif
7211 return -1; /* this wasn't a process from fg_pipe */
7212}
7213
7214/* Check to see if any processes have exited -- if they have,
7215 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007216 *
7217 * If non-NULL fg_pipe: wait for its completion or stop.
7218 * Return its exitcode or zero if stopped.
7219 *
7220 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7221 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7222 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7223 * or 0 if no children changed status.
7224 *
7225 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7226 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7227 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02007228 */
7229static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7230{
7231 int attributes;
7232 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007233 int rcode = 0;
7234
7235 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7236
7237 attributes = WUNTRACED;
7238 if (fg_pipe == NULL)
7239 attributes |= WNOHANG;
7240
7241 errno = 0;
7242#if ENABLE_HUSH_FAST
7243 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7244//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7245//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7246 /* There was neither fork nor SIGCHLD since last waitpid */
7247 /* Avoid doing waitpid syscall if possible */
7248 if (!G.we_have_children) {
7249 errno = ECHILD;
7250 return -1;
7251 }
7252 if (fg_pipe == NULL) { /* is WNOHANG set? */
7253 /* We have children, but they did not exit
7254 * or stop yet (we saw no SIGCHLD) */
7255 return 0;
7256 }
7257 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7258 }
7259#endif
7260
7261/* Do we do this right?
7262 * bash-3.00# sleep 20 | false
7263 * <ctrl-Z pressed>
7264 * [3]+ Stopped sleep 20 | false
7265 * bash-3.00# echo $?
7266 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7267 * [hush 1.14.0: yes we do it right]
7268 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007269 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007270 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007271#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02007272 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007273 i = G.count_SIGCHLD;
7274#endif
7275 childpid = waitpid(-1, &status, attributes);
7276 if (childpid <= 0) {
7277 if (childpid && errno != ECHILD)
7278 bb_perror_msg("waitpid");
7279#if ENABLE_HUSH_FAST
7280 else { /* Until next SIGCHLD, waitpid's are useless */
7281 G.we_have_children = (childpid == 0);
7282 G.handled_SIGCHLD = i;
7283//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7284 }
7285#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007286 /* ECHILD (no children), or 0 (no change in children status) */
7287 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007288 break;
7289 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007290 rcode = process_wait_result(fg_pipe, childpid, status);
7291 if (rcode >= 0) {
7292 /* fg_pipe exited or stopped */
7293 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007294 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007295 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007296 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007297 rcode = WEXITSTATUS(status);
7298 if (WIFSIGNALED(status))
7299 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007300 if (WIFSTOPPED(status))
7301 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7302 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007303 rcode++;
7304 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007305 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007306 /* This wasn't one of our processes, or */
7307 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007308 } /* while (waitpid succeeds)... */
7309
7310 return rcode;
7311}
7312
7313#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007314static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007315{
7316 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007317 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007318 if (G_saved_tty_pgrp) {
7319 /* Job finished, move the shell to the foreground */
7320 p = getpgrp(); /* our process group id */
7321 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7322 tcsetpgrp(G_interactive_fd, p);
7323 }
7324 return rcode;
7325}
7326#endif
7327
7328/* Start all the jobs, but don't wait for anything to finish.
7329 * See checkjobs().
7330 *
7331 * Return code is normally -1, when the caller has to wait for children
7332 * to finish to determine the exit status of the pipe. If the pipe
7333 * is a simple builtin command, however, the action is done by the
7334 * time run_pipe returns, and the exit code is provided as the
7335 * return value.
7336 *
7337 * Returns -1 only if started some children. IOW: we have to
7338 * mask out retvals of builtins etc with 0xff!
7339 *
7340 * The only case when we do not need to [v]fork is when the pipe
7341 * is single, non-backgrounded, non-subshell command. Examples:
7342 * cmd ; ... { list } ; ...
7343 * cmd && ... { list } && ...
7344 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007345 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007346 * or (if SH_STANDALONE) an applet, and we can run the { list }
7347 * with run_list. If it isn't one of these, we fork and exec cmd.
7348 *
7349 * Cases when we must fork:
7350 * non-single: cmd | cmd
7351 * backgrounded: cmd & { list } &
7352 * subshell: ( list ) [&]
7353 */
7354#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01007355#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007356 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7357#endif
7358static int redirect_and_varexp_helper(char ***new_env_p,
7359 struct variable **old_vars_p,
7360 struct command *command,
7361 int squirrel[3],
7362 char **argv_expanded)
7363{
7364 /* setup_redirects acts on file descriptors, not FILEs.
7365 * This is perfect for work that comes after exec().
7366 * Is it really safe for inline use? Experimentally,
7367 * things seem to work. */
7368 int rcode = setup_redirects(command, squirrel);
7369 if (rcode == 0) {
7370 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7371 *new_env_p = new_env;
7372 dump_cmd_in_x_mode(new_env);
7373 dump_cmd_in_x_mode(argv_expanded);
7374 if (old_vars_p)
7375 *old_vars_p = set_vars_and_save_old(new_env);
7376 }
7377 return rcode;
7378}
7379static NOINLINE int run_pipe(struct pipe *pi)
7380{
7381 static const char *const null_ptr = NULL;
7382
7383 int cmd_no;
7384 int next_infd;
7385 struct command *command;
7386 char **argv_expanded;
7387 char **argv;
7388 /* it is not always needed, but we aim to smaller code */
7389 int squirrel[] = { -1, -1, -1 };
7390 int rcode;
7391
7392 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7393 debug_enter();
7394
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007395 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7396 * Result should be 3 lines: q w e, qwe, q w e
7397 */
7398 G.ifs = get_local_var_value("IFS");
7399 if (!G.ifs)
7400 G.ifs = defifs;
7401
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007402 IF_HUSH_JOB(pi->pgrp = -1;)
7403 pi->stopped_cmds = 0;
7404 command = &pi->cmds[0];
7405 argv_expanded = NULL;
7406
7407 if (pi->num_cmds != 1
7408 || pi->followup == PIPE_BG
7409 || command->cmd_type == CMD_SUBSHELL
7410 ) {
7411 goto must_fork;
7412 }
7413
7414 pi->alive_cmds = 1;
7415
7416 debug_printf_exec(": group:%p argv:'%s'\n",
7417 command->group, command->argv ? command->argv[0] : "NONE");
7418
7419 if (command->group) {
7420#if ENABLE_HUSH_FUNCTIONS
7421 if (command->cmd_type == CMD_FUNCDEF) {
7422 /* "executing" func () { list } */
7423 struct function *funcp;
7424
7425 funcp = new_function(command->argv[0]);
7426 /* funcp->name is already set to argv[0] */
7427 funcp->body = command->group;
7428# if !BB_MMU
7429 funcp->body_as_string = command->group_as_string;
7430 command->group_as_string = NULL;
7431# endif
7432 command->group = NULL;
7433 command->argv[0] = NULL;
7434 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7435 funcp->parent_cmd = command;
7436 command->child_func = funcp;
7437
7438 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7439 debug_leave();
7440 return EXIT_SUCCESS;
7441 }
7442#endif
7443 /* { list } */
7444 debug_printf("non-subshell group\n");
7445 rcode = 1; /* exitcode if redir failed */
7446 if (setup_redirects(command, squirrel) == 0) {
7447 debug_printf_exec(": run_list\n");
7448 rcode = run_list(command->group) & 0xff;
7449 }
7450 restore_redirects(squirrel);
7451 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7452 debug_leave();
7453 debug_printf_exec("run_pipe: return %d\n", rcode);
7454 return rcode;
7455 }
7456
7457 argv = command->argv ? command->argv : (char **) &null_ptr;
7458 {
7459 const struct built_in_command *x;
7460#if ENABLE_HUSH_FUNCTIONS
7461 const struct function *funcp;
7462#else
7463 enum { funcp = 0 };
7464#endif
7465 char **new_env = NULL;
7466 struct variable *old_vars = NULL;
7467
7468 if (argv[command->assignment_cnt] == NULL) {
7469 /* Assignments, but no command */
7470 /* Ensure redirects take effect (that is, create files).
7471 * Try "a=t >file" */
7472#if 0 /* A few cases in testsuite fail with this code. FIXME */
7473 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7474 /* Set shell variables */
7475 if (new_env) {
7476 argv = new_env;
7477 while (*argv) {
7478 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7479 /* Do we need to flag set_local_var() errors?
7480 * "assignment to readonly var" and "putenv error"
7481 */
7482 argv++;
7483 }
7484 }
7485 /* Redirect error sets $? to 1. Otherwise,
7486 * if evaluating assignment value set $?, retain it.
7487 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7488 if (rcode == 0)
7489 rcode = G.last_exitcode;
7490 /* Exit, _skipping_ variable restoring code: */
7491 goto clean_up_and_ret0;
7492
7493#else /* Older, bigger, but more correct code */
7494
7495 rcode = setup_redirects(command, squirrel);
7496 restore_redirects(squirrel);
7497 /* Set shell variables */
7498 if (G_x_mode)
7499 bb_putchar_stderr('+');
7500 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007501 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007502 if (G_x_mode)
7503 fprintf(stderr, " %s", p);
7504 debug_printf_exec("set shell var:'%s'->'%s'\n",
7505 *argv, p);
7506 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7507 /* Do we need to flag set_local_var() errors?
7508 * "assignment to readonly var" and "putenv error"
7509 */
7510 argv++;
7511 }
7512 if (G_x_mode)
7513 bb_putchar_stderr('\n');
7514 /* Redirect error sets $? to 1. Otherwise,
7515 * if evaluating assignment value set $?, retain it.
7516 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7517 if (rcode == 0)
7518 rcode = G.last_exitcode;
7519 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7520 debug_leave();
7521 debug_printf_exec("run_pipe: return %d\n", rcode);
7522 return rcode;
7523#endif
7524 }
7525
7526 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007527#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007528 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007529 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007530 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007531#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007532 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007533 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7534 }
7535
7536 /* if someone gives us an empty string: `cmd with empty output` */
7537 if (!argv_expanded[0]) {
7538 free(argv_expanded);
7539 debug_leave();
7540 return G.last_exitcode;
7541 }
7542
7543 x = find_builtin(argv_expanded[0]);
7544#if ENABLE_HUSH_FUNCTIONS
7545 funcp = NULL;
7546 if (!x)
7547 funcp = find_function(argv_expanded[0]);
7548#endif
7549 if (x || funcp) {
7550 if (!funcp) {
7551 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7552 debug_printf("exec with redirects only\n");
7553 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007554 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007555 goto clean_up_and_ret1;
7556 }
7557 }
7558 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7559 if (rcode == 0) {
7560 if (!funcp) {
7561 debug_printf_exec(": builtin '%s' '%s'...\n",
7562 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007563 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007564 rcode = x->b_function(argv_expanded) & 0xff;
7565 fflush_all();
7566 }
7567#if ENABLE_HUSH_FUNCTIONS
7568 else {
7569# if ENABLE_HUSH_LOCAL
7570 struct variable **sv;
7571 sv = G.shadowed_vars_pp;
7572 G.shadowed_vars_pp = &old_vars;
7573# endif
7574 debug_printf_exec(": function '%s' '%s'...\n",
7575 funcp->name, argv_expanded[1]);
7576 rcode = run_function(funcp, argv_expanded) & 0xff;
7577# if ENABLE_HUSH_LOCAL
7578 G.shadowed_vars_pp = sv;
7579# endif
7580 }
7581#endif
7582 }
7583 clean_up_and_ret:
7584 unset_vars(new_env);
7585 add_vars(old_vars);
7586/* clean_up_and_ret0: */
7587 restore_redirects(squirrel);
7588 clean_up_and_ret1:
7589 free(argv_expanded);
7590 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7591 debug_leave();
7592 debug_printf_exec("run_pipe return %d\n", rcode);
7593 return rcode;
7594 }
7595
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007596 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007597 int n = find_applet_by_name(argv_expanded[0]);
7598 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7599 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7600 if (rcode == 0) {
7601 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7602 argv_expanded[0], argv_expanded[1]);
7603 rcode = run_nofork_applet(n, argv_expanded);
7604 }
7605 goto clean_up_and_ret;
7606 }
7607 }
7608 /* It is neither builtin nor applet. We must fork. */
7609 }
7610
7611 must_fork:
7612 /* NB: argv_expanded may already be created, and that
7613 * might include `cmd` runs! Do not rerun it! We *must*
7614 * use argv_expanded if it's non-NULL */
7615
7616 /* Going to fork a child per each pipe member */
7617 pi->alive_cmds = 0;
7618 next_infd = 0;
7619
7620 cmd_no = 0;
7621 while (cmd_no < pi->num_cmds) {
7622 struct fd_pair pipefds;
7623#if !BB_MMU
7624 volatile nommu_save_t nommu_save;
7625 nommu_save.new_env = NULL;
7626 nommu_save.old_vars = NULL;
7627 nommu_save.argv = NULL;
7628 nommu_save.argv_from_re_execing = NULL;
7629#endif
7630 command = &pi->cmds[cmd_no];
7631 cmd_no++;
7632 if (command->argv) {
7633 debug_printf_exec(": pipe member '%s' '%s'...\n",
7634 command->argv[0], command->argv[1]);
7635 } else {
7636 debug_printf_exec(": pipe member with no argv\n");
7637 }
7638
7639 /* pipes are inserted between pairs of commands */
7640 pipefds.rd = 0;
7641 pipefds.wr = 1;
7642 if (cmd_no < pi->num_cmds)
7643 xpiped_pair(pipefds);
7644
7645 command->pid = BB_MMU ? fork() : vfork();
7646 if (!command->pid) { /* child */
7647#if ENABLE_HUSH_JOB
7648 disable_restore_tty_pgrp_on_exit();
7649 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7650
7651 /* Every child adds itself to new process group
7652 * with pgid == pid_of_first_child_in_pipe */
7653 if (G.run_list_level == 1 && G_interactive_fd) {
7654 pid_t pgrp;
7655 pgrp = pi->pgrp;
7656 if (pgrp < 0) /* true for 1st process only */
7657 pgrp = getpid();
7658 if (setpgid(0, pgrp) == 0
7659 && pi->followup != PIPE_BG
7660 && G_saved_tty_pgrp /* we have ctty */
7661 ) {
7662 /* We do it in *every* child, not just first,
7663 * to avoid races */
7664 tcsetpgrp(G_interactive_fd, pgrp);
7665 }
7666 }
7667#endif
7668 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7669 /* 1st cmd in backgrounded pipe
7670 * should have its stdin /dev/null'ed */
7671 close(0);
7672 if (open(bb_dev_null, O_RDONLY))
7673 xopen("/", O_RDONLY);
7674 } else {
7675 xmove_fd(next_infd, 0);
7676 }
7677 xmove_fd(pipefds.wr, 1);
7678 if (pipefds.rd > 1)
7679 close(pipefds.rd);
7680 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02007681 * and the pipe fd (fd#1) is available for dup'ing:
7682 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7683 * of cmd1 goes into pipe.
7684 */
7685 if (setup_redirects(command, NULL)) {
7686 /* Happens when redir file can't be opened:
7687 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7688 * FOO
7689 * hush: can't open '/qwe/rty': No such file or directory
7690 * BAZ
7691 * (echo BAR is not executed, it hits _exit(1) below)
7692 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007693 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007694 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007695
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007696 /* Stores to nommu_save list of env vars putenv'ed
7697 * (NOMMU, on MMU we don't need that) */
7698 /* cast away volatility... */
7699 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7700 /* pseudo_exec() does not return */
7701 }
7702
7703 /* parent or error */
7704#if ENABLE_HUSH_FAST
7705 G.count_SIGCHLD++;
7706//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7707#endif
7708 enable_restore_tty_pgrp_on_exit();
7709#if !BB_MMU
7710 /* Clean up after vforked child */
7711 free(nommu_save.argv);
7712 free(nommu_save.argv_from_re_execing);
7713 unset_vars(nommu_save.new_env);
7714 add_vars(nommu_save.old_vars);
7715#endif
7716 free(argv_expanded);
7717 argv_expanded = NULL;
7718 if (command->pid < 0) { /* [v]fork failed */
7719 /* Clearly indicate, was it fork or vfork */
7720 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7721 } else {
7722 pi->alive_cmds++;
7723#if ENABLE_HUSH_JOB
7724 /* Second and next children need to know pid of first one */
7725 if (pi->pgrp < 0)
7726 pi->pgrp = command->pid;
7727#endif
7728 }
7729
7730 if (cmd_no > 1)
7731 close(next_infd);
7732 if (cmd_no < pi->num_cmds)
7733 close(pipefds.wr);
7734 /* Pass read (output) pipe end to next iteration */
7735 next_infd = pipefds.rd;
7736 }
7737
7738 if (!pi->alive_cmds) {
7739 debug_leave();
7740 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7741 return 1;
7742 }
7743
7744 debug_leave();
7745 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7746 return -1;
7747}
7748
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007749/* NB: called by pseudo_exec, and therefore must not modify any
7750 * global data until exec/_exit (we can be a child after vfork!) */
7751static int run_list(struct pipe *pi)
7752{
7753#if ENABLE_HUSH_CASE
7754 char *case_word = NULL;
7755#endif
7756#if ENABLE_HUSH_LOOPS
7757 struct pipe *loop_top = NULL;
7758 char **for_lcur = NULL;
7759 char **for_list = NULL;
7760#endif
7761 smallint last_followup;
7762 smalluint rcode;
7763#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7764 smalluint cond_code = 0;
7765#else
7766 enum { cond_code = 0 };
7767#endif
7768#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007769 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007770 smallint last_rword; /* ditto */
7771#endif
7772
7773 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7774 debug_enter();
7775
7776#if ENABLE_HUSH_LOOPS
7777 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007778 {
7779 struct pipe *cpipe;
7780 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7781 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7782 continue;
7783 /* current word is FOR or IN (BOLD in comments below) */
7784 if (cpipe->next == NULL) {
7785 syntax_error("malformed for");
7786 debug_leave();
7787 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7788 return 1;
7789 }
7790 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7791 if (cpipe->next->res_word == RES_DO)
7792 continue;
7793 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7794 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7795 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7796 ) {
7797 syntax_error("malformed for");
7798 debug_leave();
7799 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7800 return 1;
7801 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007802 }
7803 }
7804#endif
7805
7806 /* Past this point, all code paths should jump to ret: label
7807 * in order to return, no direct "return" statements please.
7808 * This helps to ensure that no memory is leaked. */
7809
7810#if ENABLE_HUSH_JOB
7811 G.run_list_level++;
7812#endif
7813
7814#if HAS_KEYWORDS
7815 rword = RES_NONE;
7816 last_rword = RES_XXXX;
7817#endif
7818 last_followup = PIPE_SEQ;
7819 rcode = G.last_exitcode;
7820
7821 /* Go through list of pipes, (maybe) executing them. */
7822 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007823 int r;
7824
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007825 if (G.flag_SIGINT)
7826 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007827 if (G_flag_return_in_progress == 1)
7828 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007829
7830 IF_HAS_KEYWORDS(rword = pi->res_word;)
7831 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7832 rword, cond_code, last_rword);
7833#if ENABLE_HUSH_LOOPS
7834 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7835 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7836 ) {
7837 /* start of a loop: remember where loop starts */
7838 loop_top = pi;
7839 G.depth_of_loop++;
7840 }
7841#endif
7842 /* Still in the same "if...", "then..." or "do..." branch? */
7843 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7844 if ((rcode == 0 && last_followup == PIPE_OR)
7845 || (rcode != 0 && last_followup == PIPE_AND)
7846 ) {
7847 /* It is "<true> || CMD" or "<false> && CMD"
7848 * and we should not execute CMD */
7849 debug_printf_exec("skipped cmd because of || or &&\n");
7850 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02007851 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007852 }
7853 }
7854 last_followup = pi->followup;
7855 IF_HAS_KEYWORDS(last_rword = rword;)
7856#if ENABLE_HUSH_IF
7857 if (cond_code) {
7858 if (rword == RES_THEN) {
7859 /* if false; then ... fi has exitcode 0! */
7860 G.last_exitcode = rcode = EXIT_SUCCESS;
7861 /* "if <false> THEN cmd": skip cmd */
7862 continue;
7863 }
7864 } else {
7865 if (rword == RES_ELSE || rword == RES_ELIF) {
7866 /* "if <true> then ... ELSE/ELIF cmd":
7867 * skip cmd and all following ones */
7868 break;
7869 }
7870 }
7871#endif
7872#if ENABLE_HUSH_LOOPS
7873 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7874 if (!for_lcur) {
7875 /* first loop through for */
7876
7877 static const char encoded_dollar_at[] ALIGN1 = {
7878 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7879 }; /* encoded representation of "$@" */
7880 static const char *const encoded_dollar_at_argv[] = {
7881 encoded_dollar_at, NULL
7882 }; /* argv list with one element: "$@" */
7883 char **vals;
7884
7885 vals = (char**)encoded_dollar_at_argv;
7886 if (pi->next->res_word == RES_IN) {
7887 /* if no variable values after "in" we skip "for" */
7888 if (!pi->next->cmds[0].argv) {
7889 G.last_exitcode = rcode = EXIT_SUCCESS;
7890 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7891 break;
7892 }
7893 vals = pi->next->cmds[0].argv;
7894 } /* else: "for var; do..." -> assume "$@" list */
7895 /* create list of variable values */
7896 debug_print_strings("for_list made from", vals);
7897 for_list = expand_strvec_to_strvec(vals);
7898 for_lcur = for_list;
7899 debug_print_strings("for_list", for_list);
7900 }
7901 if (!*for_lcur) {
7902 /* "for" loop is over, clean up */
7903 free(for_list);
7904 for_list = NULL;
7905 for_lcur = NULL;
7906 break;
7907 }
7908 /* Insert next value from for_lcur */
7909 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7910 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7911 continue;
7912 }
7913 if (rword == RES_IN) {
7914 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7915 }
7916 if (rword == RES_DONE) {
7917 continue; /* "done" has no cmds too */
7918 }
7919#endif
7920#if ENABLE_HUSH_CASE
7921 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007922 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007923 case_word = expand_strvec_to_string(pi->cmds->argv);
7924 continue;
7925 }
7926 if (rword == RES_MATCH) {
7927 char **argv;
7928
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007929 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007930 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7931 break;
7932 /* all prev words didn't match, does this one match? */
7933 argv = pi->cmds->argv;
7934 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007935 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007936 /* TODO: which FNM_xxx flags to use? */
7937 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7938 free(pattern);
7939 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007940 free(case_word);
7941 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007942 break;
7943 }
7944 argv++;
7945 }
7946 continue;
7947 }
7948 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007949 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007950 if (cond_code != 0)
7951 continue; /* not matched yet, skip this pipe */
7952 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007953 if (rword == RES_ESAC) {
7954 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
7955 if (case_word) {
7956 /* "case" did not match anything: still set $? (to 0) */
7957 G.last_exitcode = rcode = EXIT_SUCCESS;
7958 }
7959 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007960#endif
7961 /* Just pressing <enter> in shell should check for jobs.
7962 * OTOH, in non-interactive shell this is useless
7963 * and only leads to extra job checks */
7964 if (pi->num_cmds == 0) {
7965 if (G_interactive_fd)
7966 goto check_jobs_and_continue;
7967 continue;
7968 }
7969
7970 /* After analyzing all keywords and conditions, we decided
7971 * to execute this pipe. NB: have to do checkjobs(NULL)
7972 * after run_pipe to collect any background children,
7973 * even if list execution is to be stopped. */
7974 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007975#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007976 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007977#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007978 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
7979 if (r != -1) {
7980 /* We ran a builtin, function, or group.
7981 * rcode is already known
7982 * and we don't need to wait for anything. */
7983 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7984 G.last_exitcode = rcode;
7985 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007986#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007987 /* Was it "break" or "continue"? */
7988 if (G.flag_break_continue) {
7989 smallint fbc = G.flag_break_continue;
7990 /* We might fall into outer *loop*,
7991 * don't want to break it too */
7992 if (loop_top) {
7993 G.depth_break_continue--;
7994 if (G.depth_break_continue == 0)
7995 G.flag_break_continue = 0;
7996 /* else: e.g. "continue 2" should *break* once, *then* continue */
7997 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7998 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007999 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008000 break;
8001 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008002 /* "continue": simulate end of loop */
8003 rword = RES_DONE;
8004 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008005 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008006#endif
8007 if (G_flag_return_in_progress == 1) {
8008 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8009 break;
8010 }
8011 } else if (pi->followup == PIPE_BG) {
8012 /* What does bash do with attempts to background builtins? */
8013 /* even bash 3.2 doesn't do that well with nested bg:
8014 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8015 * I'm NOT treating inner &'s as jobs */
8016#if ENABLE_HUSH_JOB
8017 if (G.run_list_level == 1)
8018 insert_bg_job(pi);
8019#endif
8020 /* Last command's pid goes to $! */
8021 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8022 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8023/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash says 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008024 rcode = EXIT_SUCCESS;
8025 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008026 } else {
8027#if ENABLE_HUSH_JOB
8028 if (G.run_list_level == 1 && G_interactive_fd) {
8029 /* Waits for completion, then fg's main shell */
8030 rcode = checkjobs_and_fg_shell(pi);
8031 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008032 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008033 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008034#endif
8035 /* This one just waits for completion */
8036 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8037 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8038 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008039 G.last_exitcode = rcode;
8040 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008041 }
8042
8043 /* Analyze how result affects subsequent commands */
8044#if ENABLE_HUSH_IF
8045 if (rword == RES_IF || rword == RES_ELIF)
8046 cond_code = rcode;
8047#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008048 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008049 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008050 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008051#if ENABLE_HUSH_LOOPS
8052 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008053 if (pi->next
8054 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008055 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008056 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008057 if (rword == RES_WHILE) {
8058 if (rcode) {
8059 /* "while false; do...done" - exitcode 0 */
8060 G.last_exitcode = rcode = EXIT_SUCCESS;
8061 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008062 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008063 }
8064 }
8065 if (rword == RES_UNTIL) {
8066 if (!rcode) {
8067 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008068 break;
8069 }
8070 }
8071 }
8072#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008073 } /* for (pi) */
8074
8075#if ENABLE_HUSH_JOB
8076 G.run_list_level--;
8077#endif
8078#if ENABLE_HUSH_LOOPS
8079 if (loop_top)
8080 G.depth_of_loop--;
8081 free(for_list);
8082#endif
8083#if ENABLE_HUSH_CASE
8084 free(case_word);
8085#endif
8086 debug_leave();
8087 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8088 return rcode;
8089}
8090
8091/* Select which version we will use */
8092static int run_and_free_list(struct pipe *pi)
8093{
8094 int rcode = 0;
8095 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08008096 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008097 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8098 rcode = run_list(pi);
8099 }
8100 /* free_pipe_list has the side effect of clearing memory.
8101 * In the long run that function can be merged with run_list,
8102 * but doing that now would hobble the debugging effort. */
8103 free_pipe_list(pi);
8104 debug_printf_exec("run_and_free_list return %d\n", rcode);
8105 return rcode;
8106}
8107
8108
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008109static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00008110{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008111 sighandler_t old_handler;
8112 unsigned sig = 0;
8113 while ((mask >>= 1) != 0) {
8114 sig++;
8115 if (!(mask & 1))
8116 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02008117 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008118 /* POSIX allows shell to re-enable SIGCHLD
8119 * even if it was SIG_IGN on entry.
8120 * Therefore we skip IGN check for it:
8121 */
8122 if (sig == SIGCHLD)
8123 continue;
8124 if (old_handler == SIG_IGN) {
8125 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008126 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008127 if (!G.traps)
8128 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8129 free(G.traps[sig]);
8130 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
8131 }
8132 }
8133}
8134
8135/* Called a few times only (or even once if "sh -c") */
8136static void install_special_sighandlers(void)
8137{
Denis Vlasenkof9375282009-04-05 19:13:39 +00008138 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008139
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008140 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008141 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008142 if (G_interactive_fd) {
8143 mask |= SPECIAL_INTERACTIVE_SIGS;
8144 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008145 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008146 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008147 /* Careful, do not re-install handlers we already installed */
8148 if (G.special_sig_mask != mask) {
8149 unsigned diff = mask & ~G.special_sig_mask;
8150 G.special_sig_mask = mask;
8151 install_sighandlers(diff);
8152 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008153}
8154
8155#if ENABLE_HUSH_JOB
8156/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008157/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008158static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00008159{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008160 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008161
8162 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008163 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01008164 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8165 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008166 + (1 << SIGBUS ) * HUSH_DEBUG
8167 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01008168 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008169 + (1 << SIGABRT)
8170 /* bash 3.2 seems to handle these just like 'fatal' ones */
8171 + (1 << SIGPIPE)
8172 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008173 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008174 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008175 * we never want to restore pgrp on exit, and this fn is not called
8176 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008177 /*+ (1 << SIGHUP )*/
8178 /*+ (1 << SIGTERM)*/
8179 /*+ (1 << SIGINT )*/
8180 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008181 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008182
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008183 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008184}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00008185#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00008186
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008187static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00008188{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008189 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008190 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008191 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08008192 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008193 break;
8194 case 'x':
8195 IF_HUSH_MODE_X(G_x_mode = state;)
8196 break;
8197 case 'o':
8198 if (!o_opt) {
8199 /* "set -+o" without parameter.
8200 * in bash, set -o produces this output:
8201 * pipefail off
8202 * and set +o:
8203 * set +o pipefail
8204 * We always use the second form.
8205 */
8206 const char *p = o_opt_strings;
8207 idx = 0;
8208 while (*p) {
8209 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8210 idx++;
8211 p += strlen(p) + 1;
8212 }
8213 break;
8214 }
8215 idx = index_in_strings(o_opt_strings, o_opt);
8216 if (idx >= 0) {
8217 G.o_opt[idx] = state;
8218 break;
8219 }
8220 default:
8221 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008222 }
8223 return EXIT_SUCCESS;
8224}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008225
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00008226int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00008227int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00008228{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008229 enum {
8230 OPT_login = (1 << 0),
8231 };
8232 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00008233 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008234 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008235 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008236 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008237 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00008238
Denis Vlasenko574f2f42008-02-27 18:41:59 +00008239 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02008240 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008241 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008242
Denys Vlasenko10c01312011-05-11 11:49:21 +02008243#if ENABLE_HUSH_FAST
8244 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8245#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008246#if !BB_MMU
8247 G.argv0_for_re_execing = argv[0];
8248#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008249 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008250 shell_ver = xzalloc(sizeof(*shell_ver));
8251 shell_ver->flg_export = 1;
8252 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02008253 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02008254 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008255 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02008256 /* Create shell local variables from the values
8257 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00008258 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008259 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008260 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008261 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008262 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008263 if (e) while (*e) {
8264 char *value = strchr(*e, '=');
8265 if (value) { /* paranoia */
8266 cur_var->next = xzalloc(sizeof(*cur_var));
8267 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00008268 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008269 cur_var->max_len = strlen(*e);
8270 cur_var->flg_export = 1;
8271 }
8272 e++;
8273 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02008274 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008275 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8276 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02008277
8278 /* Export PWD */
8279 set_pwd_var(/*exp:*/ 1);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008280
8281#if ENABLE_HUSH_BASH_COMPAT
8282 /* Set (but not export) HOSTNAME unless already set */
8283 if (!get_local_var_value("HOSTNAME")) {
8284 struct utsname uts;
8285 uname(&uts);
8286 set_local_var_from_halves("HOSTNAME", uts.nodename);
8287 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008288 /* bash also exports SHLVL and _,
8289 * and sets (but doesn't export) the following variables:
8290 * BASH=/bin/bash
8291 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8292 * BASH_VERSION='3.2.0(1)-release'
8293 * HOSTTYPE=i386
8294 * MACHTYPE=i386-pc-linux-gnu
8295 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02008296 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02008297 * EUID=<NNNNN>
8298 * UID=<NNNNN>
8299 * GROUPS=()
8300 * LINES=<NNN>
8301 * COLUMNS=<NNN>
8302 * BASH_ARGC=()
8303 * BASH_ARGV=()
8304 * BASH_LINENO=()
8305 * BASH_SOURCE=()
8306 * DIRSTACK=()
8307 * PIPESTATUS=([0]="0")
8308 * HISTFILE=/<xxx>/.bash_history
8309 * HISTFILESIZE=500
8310 * HISTSIZE=500
8311 * MAILCHECK=60
8312 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8313 * SHELL=/bin/bash
8314 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8315 * TERM=dumb
8316 * OPTERR=1
8317 * OPTIND=1
8318 * IFS=$' \t\n'
8319 * PS1='\s-\v\$ '
8320 * PS2='> '
8321 * PS4='+ '
8322 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008323#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02008324
Denis Vlasenko38f63192007-01-22 09:03:07 +00008325#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02008326 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008327#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02008328
Eric Andersen94ac2442001-05-22 19:05:18 +00008329 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00008330 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00008331
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008332 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00008333
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008334 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008335 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008336 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008337 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008338 * in order to intercept (more) signals.
8339 */
8340
8341 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008342 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008343 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008344 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008345 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008346 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008347#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00008348 "<:$:R:V:"
8349# if ENABLE_HUSH_FUNCTIONS
8350 "F:"
8351# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008352#endif
8353 );
8354 if (opt <= 0)
8355 break;
Eric Andersen25f27032001-04-26 23:22:31 +00008356 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008357 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008358 /* Possibilities:
8359 * sh ... -c 'script'
8360 * sh ... -c 'script' ARG0 [ARG1...]
8361 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01008362 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008363 * "" needs to be replaced with NULL
8364 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01008365 * Note: the form without ARG0 never happens:
8366 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008367 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02008368 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008369 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008370 G.root_ppid = getppid();
8371 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008372 G.global_argv = argv + optind;
8373 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008374 if (builtin_argc) {
8375 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8376 const struct built_in_command *x;
8377
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008378 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008379 x = find_builtin(optarg);
8380 if (x) { /* paranoia */
8381 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8382 G.global_argv += builtin_argc;
8383 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008384 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01008385 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008386 }
8387 goto final_return;
8388 }
8389 if (!G.global_argv[0]) {
8390 /* -c 'script' (no params): prevent empty $0 */
8391 G.global_argv--; /* points to argv[i] of 'script' */
8392 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02008393 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008394 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008395 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008396 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008397 goto final_return;
8398 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00008399 /* Well, we cannot just declare interactiveness,
8400 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008401 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008402 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008403 case 's':
8404 /* "-s" means "read from stdin", but this is how we always
8405 * operate, so simply do nothing here. */
8406 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008407 case 'l':
8408 flags |= OPT_login;
8409 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008410#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008411 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02008412 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008413 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008414 case '$': {
8415 unsigned long long empty_trap_mask;
8416
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008417 G.root_pid = bb_strtou(optarg, &optarg, 16);
8418 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02008419 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8420 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008421 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8422 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008423 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008424 optarg++;
8425 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008426 optarg++;
8427 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8428 if (empty_trap_mask != 0) {
8429 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008430 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008431 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8432 for (sig = 1; sig < NSIG; sig++) {
8433 if (empty_trap_mask & (1LL << sig)) {
8434 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008435 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008436 }
8437 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008438 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008439# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008440 optarg++;
8441 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008442# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008443 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008444 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008445 case 'R':
8446 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02008447 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008448 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00008449# if ENABLE_HUSH_FUNCTIONS
8450 case 'F': {
8451 struct function *funcp = new_function(optarg);
8452 /* funcp->name is already set to optarg */
8453 /* funcp->body is set to NULL. It's a special case. */
8454 funcp->body_as_string = argv[optind];
8455 optind++;
8456 break;
8457 }
8458# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008459#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008460 case 'n':
8461 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008462 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008463 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008464 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008465#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008466 fprintf(stderr, "Usage: sh [FILE]...\n"
8467 " or: sh -c command [args]...\n\n");
8468 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008469#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008470 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008471#endif
Eric Andersen25f27032001-04-26 23:22:31 +00008472 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008473 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008474
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008475 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8476 G.global_argc = argc - (optind - 1);
8477 G.global_argv = argv + (optind - 1);
8478 G.global_argv[0] = argv[0];
8479
Denys Vlasenkodea47882009-10-09 15:40:49 +02008480 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008481 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008482 G.root_ppid = getppid();
8483 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008484
8485 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008486 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008487 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008488 debug_printf("sourcing /etc/profile\n");
8489 input = fopen_for_read("/etc/profile");
8490 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008491 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008492 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008493 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008494 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008495 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008496 /* bash: after sourcing /etc/profile,
8497 * tries to source (in the given order):
8498 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008499 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008500 * bash also sources ~/.bash_logout on exit.
8501 * If called as sh, skips .bash_XXX files.
8502 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008503 }
8504
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008505 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008506 FILE *input;
8507 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008508 * "bash <script>" (which is never interactive (unless -i?))
8509 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008510 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02008511 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008512 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008513 G.global_argc--;
8514 G.global_argv++;
8515 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02008516 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008517 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02008518 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008519 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008520 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008521 parse_and_run_file(input);
8522#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008523 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008524#endif
8525 goto final_return;
8526 }
8527
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008528 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008529 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008530 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008531
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008532 /* A shell is interactive if the '-i' flag was given,
8533 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008534 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008535 * no arguments remaining or the -s flag given
8536 * standard input is a terminal
8537 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008538 * Refer to Posix.2, the description of the 'sh' utility.
8539 */
8540#if ENABLE_HUSH_JOB
8541 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008542 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8543 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8544 if (G_saved_tty_pgrp < 0)
8545 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008546
8547 /* try to dup stdin to high fd#, >= 255 */
8548 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8549 if (G_interactive_fd < 0) {
8550 /* try to dup to any fd */
8551 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008552 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008553 /* give up */
8554 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008555 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008556 }
8557 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008558// TODO: track & disallow any attempts of user
8559// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008560 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008561 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008562 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008563 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008564
Mike Frysinger38478a62009-05-20 04:48:06 -04008565 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008566 /* If we were run as 'hush &', sleep until we are
8567 * in the foreground (tty pgrp == our pgrp).
8568 * If we get started under a job aware app (like bash),
8569 * make sure we are now in charge so we don't fight over
8570 * who gets the foreground */
8571 while (1) {
8572 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008573 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8574 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008575 break;
8576 /* send TTIN to ourself (should stop us) */
8577 kill(- shell_pgrp, SIGTTIN);
8578 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008579 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008580
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008581 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008582 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008583
Mike Frysinger38478a62009-05-20 04:48:06 -04008584 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008585 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008586 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008587 /* Put ourselves in our own process group
8588 * (bash, too, does this only if ctty is available) */
8589 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8590 /* Grab control of the terminal */
8591 tcsetpgrp(G_interactive_fd, getpid());
8592 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02008593 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008594
8595# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8596 {
8597 const char *hp = get_local_var_value("HISTFILE");
8598 if (!hp) {
8599 hp = get_local_var_value("HOME");
8600 if (hp)
8601 hp = concat_path_file(hp, ".hush_history");
8602 } else {
8603 hp = xstrdup(hp);
8604 }
8605 if (hp) {
8606 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008607 //set_local_var(xasprintf("HISTFILE=%s", ...));
8608 }
8609# if ENABLE_FEATURE_SH_HISTFILESIZE
8610 hp = get_local_var_value("HISTFILESIZE");
8611 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8612# endif
8613 }
8614# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008615 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008616 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008617 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008618#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008619 /* No job control compiled in, only prompt/line editing */
8620 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008621 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8622 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008623 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008624 G_interactive_fd = dup(STDIN_FILENO);
8625 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008626 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008627 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008628 }
8629 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008630 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008631 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008632 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008633 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008634#else
8635 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008636 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008637#endif
8638 /* bash:
8639 * if interactive but not a login shell, sources ~/.bashrc
8640 * (--norc turns this off, --rcfile <file> overrides)
8641 */
8642
8643 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008644 /* note: ash and hush share this string */
8645 printf("\n\n%s %s\n"
8646 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8647 "\n",
8648 bb_banner,
8649 "hush - the humble shell"
8650 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008651 }
8652
Denis Vlasenkof9375282009-04-05 19:13:39 +00008653 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008654
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008655 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008656 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008657}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008658
8659
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008660#if ENABLE_MSH
8661int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8662int msh_main(int argc, char **argv)
8663{
Denys Vlasenkoed6ff5e2016-09-30 12:28:37 +02008664 bb_error_msg("msh is deprecated, please use hush instead");
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008665 return hush_main(argc, argv);
8666}
8667#endif
8668
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008669
8670/*
8671 * Built-ins
8672 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008673static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008674{
8675 return 0;
8676}
8677
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008678static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008679{
8680 int argc = 0;
8681 while (*argv) {
8682 argc++;
8683 argv++;
8684 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008685 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008686}
8687
8688static int FAST_FUNC builtin_test(char **argv)
8689{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008690 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008691}
8692
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008693static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008694{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008695 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008696}
8697
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008698#if ENABLE_PRINTF
8699static int FAST_FUNC builtin_printf(char **argv)
8700{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008701 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008702}
8703#endif
8704
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008705static char **skip_dash_dash(char **argv)
8706{
8707 argv++;
8708 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8709 argv++;
8710 return argv;
8711}
8712
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008713static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008714{
8715 int rcode = EXIT_SUCCESS;
8716
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008717 argv = skip_dash_dash(argv);
8718 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008719 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008720 /* bash:
8721 * eval "echo Hi; done" ("done" is syntax error):
8722 * "echo Hi" will not execute too.
8723 */
8724 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008725 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008726 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008727 }
8728 return rcode;
8729}
8730
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008731static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008732{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008733 const char *newdir;
8734
8735 argv = skip_dash_dash(argv);
8736 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008737 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008738 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008739 * bash says "bash: cd: HOME not set" and does nothing
8740 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008741 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008742 const char *home = get_local_var_value("HOME");
8743 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008744 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008745 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008746 /* Mimic bash message exactly */
8747 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008748 return EXIT_FAILURE;
8749 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008750 /* Read current dir (get_cwd(1) is inside) and set PWD.
8751 * Note: do not enforce exporting. If PWD was unset or unexported,
8752 * set it again, but do not export. bash does the same.
8753 */
8754 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008755 return EXIT_SUCCESS;
8756}
8757
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008758static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008759{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008760 argv = skip_dash_dash(argv);
8761 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008762 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008763
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008764 /* Careful: we can end up here after [v]fork. Do not restore
8765 * tty pgrp then, only top-level shell process does that */
8766 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8767 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8768
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008769 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008770 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008771 * and tcsetpgrp, and this is inherently racy.
8772 */
8773 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008774}
8775
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008776static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008777{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008778 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008779
8780 /* interactive bash:
8781 * # trap "echo EEE" EXIT
8782 * # exit
8783 * exit
8784 * There are stopped jobs.
8785 * (if there are _stopped_ jobs, running ones don't count)
8786 * # exit
8787 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01008788 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00008789 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008790 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008791 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008792
8793 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008794 argv = skip_dash_dash(argv);
8795 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008796 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008797 /* mimic bash: exit 123abc == exit 255 + error msg */
8798 xfunc_error_retval = 255;
8799 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008800 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008801}
8802
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008803static void print_escaped(const char *s)
8804{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008805 if (*s == '\'')
8806 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008807 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008808 const char *p = strchrnul(s, '\'');
8809 /* print 'xxxx', possibly just '' */
8810 printf("'%.*s'", (int)(p - s), s);
8811 if (*p == '\0')
8812 break;
8813 s = p;
8814 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008815 /* s points to '; print "'''...'''" */
8816 putchar('"');
8817 do putchar('\''); while (*++s == '\'');
8818 putchar('"');
8819 } while (*s);
8820}
8821
Denys Vlasenko295fef82009-06-03 12:47:26 +02008822#if !ENABLE_HUSH_LOCAL
8823#define helper_export_local(argv, exp, lvl) \
8824 helper_export_local(argv, exp)
8825#endif
8826static void helper_export_local(char **argv, int exp, int lvl)
8827{
8828 do {
8829 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008830 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008831
8832 /* So far we do not check that name is valid (TODO?) */
8833
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008834 if (*name_end == '\0') {
8835 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008836
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008837 vpp = get_ptr_to_local_var(name, name_end - name);
8838 var = vpp ? *vpp : NULL;
8839
Denys Vlasenko295fef82009-06-03 12:47:26 +02008840 if (exp == -1) { /* unexporting? */
8841 /* export -n NAME (without =VALUE) */
8842 if (var) {
8843 var->flg_export = 0;
8844 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8845 unsetenv(name);
8846 } /* else: export -n NOT_EXISTING_VAR: no-op */
8847 continue;
8848 }
8849 if (exp == 1) { /* exporting? */
8850 /* export NAME (without =VALUE) */
8851 if (var) {
8852 var->flg_export = 1;
8853 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8854 putenv(var->varstr);
8855 continue;
8856 }
8857 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02008858#if ENABLE_HUSH_LOCAL
8859 if (exp == 0 /* local? */
8860 && var && var->func_nest_level == lvl
8861 ) {
8862 /* "local x=abc; ...; local x" - ignore second local decl */
Denys Vlasenko80729a42016-10-02 22:33:15 +02008863 continue;
Denys Vlasenko61508d92016-10-02 21:12:02 +02008864 }
8865#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02008866 /* Exporting non-existing variable.
8867 * bash does not put it in environment,
8868 * but remembers that it is exported,
8869 * and does put it in env when it is set later.
8870 * We just set it to "" and export. */
8871 /* Or, it's "local NAME" (without =VALUE).
8872 * bash sets the value to "". */
8873 name = xasprintf("%s=", name);
8874 } else {
8875 /* (Un)exporting/making local NAME=VALUE */
8876 name = xstrdup(name);
8877 }
8878 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8879 } while (*++argv);
8880}
8881
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008882static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008883{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008884 unsigned opt_unexport;
8885
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008886#if ENABLE_HUSH_EXPORT_N
8887 /* "!": do not abort on errors */
8888 opt_unexport = getopt32(argv, "!n");
8889 if (opt_unexport == (uint32_t)-1)
8890 return EXIT_FAILURE;
8891 argv += optind;
8892#else
8893 opt_unexport = 0;
8894 argv++;
8895#endif
8896
8897 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008898 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008899 if (e) {
8900 while (*e) {
8901#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008902 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008903#else
8904 /* ash emits: export VAR='VAL'
8905 * bash: declare -x VAR="VAL"
8906 * we follow ash example */
8907 const char *s = *e++;
8908 const char *p = strchr(s, '=');
8909
8910 if (!p) /* wtf? take next variable */
8911 continue;
8912 /* export var= */
8913 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008914 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008915 putchar('\n');
8916#endif
8917 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008918 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008919 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008920 return EXIT_SUCCESS;
8921 }
8922
Denys Vlasenko295fef82009-06-03 12:47:26 +02008923 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008924
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008925 return EXIT_SUCCESS;
8926}
8927
Denys Vlasenko295fef82009-06-03 12:47:26 +02008928#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008929static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008930{
8931 if (G.func_nest_level == 0) {
8932 bb_error_msg("%s: not in a function", argv[0]);
8933 return EXIT_FAILURE; /* bash compat */
8934 }
8935 helper_export_local(argv, 0, G.func_nest_level);
8936 return EXIT_SUCCESS;
8937}
8938#endif
8939
Denys Vlasenko61508d92016-10-02 21:12:02 +02008940/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8941static int FAST_FUNC builtin_unset(char **argv)
8942{
8943 int ret;
8944 unsigned opts;
8945
8946 /* "!": do not abort on errors */
8947 /* "+": stop at 1st non-option */
8948 opts = getopt32(argv, "!+vf");
8949 if (opts == (unsigned)-1)
8950 return EXIT_FAILURE;
8951 if (opts == 3) {
8952 bb_error_msg("unset: -v and -f are exclusive");
8953 return EXIT_FAILURE;
8954 }
8955 argv += optind;
8956
8957 ret = EXIT_SUCCESS;
8958 while (*argv) {
8959 if (!(opts & 2)) { /* not -f */
8960 if (unset_local_var(*argv)) {
8961 /* unset <nonexistent_var> doesn't fail.
8962 * Error is when one tries to unset RO var.
8963 * Message was printed by unset_local_var. */
8964 ret = EXIT_FAILURE;
8965 }
8966 }
8967#if ENABLE_HUSH_FUNCTIONS
8968 else {
8969 unset_func(*argv);
8970 }
8971#endif
8972 argv++;
8973 }
8974 return ret;
8975}
8976
8977/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8978 * built-in 'set' handler
8979 * SUSv3 says:
8980 * set [-abCefhmnuvx] [-o option] [argument...]
8981 * set [+abCefhmnuvx] [+o option] [argument...]
8982 * set -- [argument...]
8983 * set -o
8984 * set +o
8985 * Implementations shall support the options in both their hyphen and
8986 * plus-sign forms. These options can also be specified as options to sh.
8987 * Examples:
8988 * Write out all variables and their values: set
8989 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8990 * Turn on the -x and -v options: set -xv
8991 * Unset all positional parameters: set --
8992 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8993 * Set the positional parameters to the expansion of x, even if x expands
8994 * with a leading '-' or '+': set -- $x
8995 *
8996 * So far, we only support "set -- [argument...]" and some of the short names.
8997 */
8998static int FAST_FUNC builtin_set(char **argv)
8999{
9000 int n;
9001 char **pp, **g_argv;
9002 char *arg = *++argv;
9003
9004 if (arg == NULL) {
9005 struct variable *e;
9006 for (e = G.top_var; e; e = e->next)
9007 puts(e->varstr);
9008 return EXIT_SUCCESS;
9009 }
9010
9011 do {
9012 if (strcmp(arg, "--") == 0) {
9013 ++argv;
9014 goto set_argv;
9015 }
9016 if (arg[0] != '+' && arg[0] != '-')
9017 break;
9018 for (n = 1; arg[n]; ++n) {
9019 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9020 goto error;
9021 if (arg[n] == 'o' && argv[1])
9022 argv++;
9023 }
9024 } while ((arg = *++argv) != NULL);
9025 /* Now argv[0] is 1st argument */
9026
9027 if (arg == NULL)
9028 return EXIT_SUCCESS;
9029 set_argv:
9030
9031 /* NB: G.global_argv[0] ($0) is never freed/changed */
9032 g_argv = G.global_argv;
9033 if (G.global_args_malloced) {
9034 pp = g_argv;
9035 while (*++pp)
9036 free(*pp);
9037 g_argv[1] = NULL;
9038 } else {
9039 G.global_args_malloced = 1;
9040 pp = xzalloc(sizeof(pp[0]) * 2);
9041 pp[0] = g_argv[0]; /* retain $0 */
9042 g_argv = pp;
9043 }
9044 /* This realloc's G.global_argv */
9045 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9046
9047 n = 1;
9048 while (*++pp)
9049 n++;
9050 G.global_argc = n;
9051
9052 return EXIT_SUCCESS;
9053
9054 /* Nothing known, so abort */
9055 error:
9056 bb_error_msg("set: %s: invalid option", arg);
9057 return EXIT_FAILURE;
9058}
9059
9060static int FAST_FUNC builtin_shift(char **argv)
9061{
9062 int n = 1;
9063 argv = skip_dash_dash(argv);
9064 if (argv[0]) {
9065 n = atoi(argv[0]);
9066 }
9067 if (n >= 0 && n < G.global_argc) {
9068 if (G.global_args_malloced) {
9069 int m = 1;
9070 while (m <= n)
9071 free(G.global_argv[m++]);
9072 }
9073 G.global_argc -= n;
9074 memmove(&G.global_argv[1], &G.global_argv[n+1],
9075 G.global_argc * sizeof(G.global_argv[0]));
9076 return EXIT_SUCCESS;
9077 }
9078 return EXIT_FAILURE;
9079}
9080
9081/* Interruptibility of read builtin in bash
9082 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9083 *
9084 * Empty trap makes read ignore corresponding signal, for any signal.
9085 *
9086 * SIGINT:
9087 * - terminates non-interactive shell;
9088 * - interrupts read in interactive shell;
9089 * if it has non-empty trap:
9090 * - executes trap and returns to command prompt in interactive shell;
9091 * - executes trap and returns to read in non-interactive shell;
9092 * SIGTERM:
9093 * - is ignored (does not interrupt) read in interactive shell;
9094 * - terminates non-interactive shell;
9095 * if it has non-empty trap:
9096 * - executes trap and returns to read;
9097 * SIGHUP:
9098 * - terminates shell (regardless of interactivity);
9099 * if it has non-empty trap:
9100 * - executes trap and returns to read;
9101 */
9102static int FAST_FUNC builtin_read(char **argv)
9103{
9104 const char *r;
9105 char *opt_n = NULL;
9106 char *opt_p = NULL;
9107 char *opt_t = NULL;
9108 char *opt_u = NULL;
9109 const char *ifs;
9110 int read_flags;
9111
9112 /* "!": do not abort on errors.
9113 * Option string must start with "sr" to match BUILTIN_READ_xxx
9114 */
9115 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9116 if (read_flags == (uint32_t)-1)
9117 return EXIT_FAILURE;
9118 argv += optind;
9119 ifs = get_local_var_value("IFS"); /* can be NULL */
9120
9121 again:
9122 r = shell_builtin_read(set_local_var_from_halves,
9123 argv,
9124 ifs,
9125 read_flags,
9126 opt_n,
9127 opt_p,
9128 opt_t,
9129 opt_u
9130 );
9131
9132 if ((uintptr_t)r == 1 && errno == EINTR) {
9133 unsigned sig = check_and_run_traps();
9134 if (sig && sig != SIGINT)
9135 goto again;
9136 }
9137
9138 if ((uintptr_t)r > 1) {
9139 bb_error_msg("%s", r);
9140 r = (char*)(uintptr_t)1;
9141 }
9142
9143 return (uintptr_t)r;
9144}
9145
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009146static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009147{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009148 int sig;
9149 char *new_cmd;
9150
9151 if (!G.traps)
9152 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
9153
9154 argv++;
9155 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00009156 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009157 /* No args: print all trapped */
9158 for (i = 0; i < NSIG; ++i) {
9159 if (G.traps[i]) {
9160 printf("trap -- ");
9161 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02009162 /* note: bash adds "SIG", but only if invoked
9163 * as "bash". If called as "sh", or if set -o posix,
9164 * then it prints short signal names.
9165 * We are printing short names: */
9166 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009167 }
9168 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009169 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009170 return EXIT_SUCCESS;
9171 }
9172
9173 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009174 /* If first arg is a number: reset all specified signals */
9175 sig = bb_strtou(*argv, NULL, 10);
9176 if (errno == 0) {
9177 int ret;
9178 process_sig_list:
9179 ret = EXIT_SUCCESS;
9180 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009181 sighandler_t handler;
9182
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009183 sig = get_signum(*argv++);
9184 if (sig < 0 || sig >= NSIG) {
9185 ret = EXIT_FAILURE;
9186 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00009187 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009188 continue;
9189 }
9190
9191 free(G.traps[sig]);
9192 G.traps[sig] = xstrdup(new_cmd);
9193
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009194 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009195 get_signame(sig), sig, G.traps[sig]);
9196
9197 /* There is no signal for 0 (EXIT) */
9198 if (sig == 0)
9199 continue;
9200
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009201 if (new_cmd)
9202 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9203 else
9204 /* We are removing trap handler */
9205 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02009206 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009207 }
9208 return ret;
9209 }
9210
9211 if (!argv[1]) { /* no second arg */
9212 bb_error_msg("trap: invalid arguments");
9213 return EXIT_FAILURE;
9214 }
9215
9216 /* First arg is "-": reset all specified to default */
9217 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9218 /* Everything else: set arg as signal handler
9219 * (includes "" case, which ignores signal) */
9220 if (argv[0][0] == '-') {
9221 if (argv[0][1] == '\0') { /* "-" */
9222 /* new_cmd remains NULL: "reset these sigs" */
9223 goto reset_traps;
9224 }
9225 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9226 argv++;
9227 }
9228 /* else: "-something", no special meaning */
9229 }
9230 new_cmd = *argv;
9231 reset_traps:
9232 argv++;
9233 goto process_sig_list;
9234}
9235
Mike Frysinger93cadc22009-05-27 17:06:25 -04009236/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009237static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04009238{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009239 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04009240
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009241 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04009242 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02009243 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04009244
9245 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009246 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009247 type = "an alias";*/
9248#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009249 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009250 type = "a function";
9251#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009252 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009253 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009254 else if ((path = find_in_path(*argv)) != NULL)
9255 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009256 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009257 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04009258 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009259 continue;
9260 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04009261
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009262 printf("%s is %s\n", *argv, type);
9263 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04009264 }
9265
9266 return ret;
9267}
9268
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009269#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009270static struct pipe *parse_jobspec(const char *str)
9271{
9272 struct pipe *pi;
9273 int jobnum;
9274
9275 if (sscanf(str, "%%%d", &jobnum) != 1) {
9276 bb_error_msg("bad argument '%s'", str);
9277 return NULL;
9278 }
9279 for (pi = G.job_list; pi; pi = pi->next) {
9280 if (pi->jobid == jobnum) {
9281 return pi;
9282 }
9283 }
9284 bb_error_msg("%d: no such job", jobnum);
9285 return NULL;
9286}
9287
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009288/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009289static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009290{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009291 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009292 struct pipe *pi;
9293
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009294 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009295 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009296
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009297 /* If they gave us no args, assume they want the last backgrounded task */
9298 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00009299 for (pi = G.job_list; pi; pi = pi->next) {
9300 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009301 goto found;
9302 }
9303 }
9304 bb_error_msg("%s: no current job", argv[0]);
9305 return EXIT_FAILURE;
9306 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009307
9308 pi = parse_jobspec(argv[1]);
9309 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009310 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009311 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00009312 /* TODO: bash prints a string representation
9313 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04009314 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009315 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009316 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009317 }
9318
9319 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009320 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9321 for (i = 0; i < pi->num_cmds; i++) {
9322 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009323 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009324 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009325
9326 i = kill(- pi->pgrp, SIGCONT);
9327 if (i < 0) {
9328 if (errno == ESRCH) {
9329 delete_finished_bg_job(pi);
9330 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009331 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009332 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009333 }
9334
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009335 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009336 remove_bg_job(pi);
9337 return checkjobs_and_fg_shell(pi);
9338 }
9339 return EXIT_SUCCESS;
9340}
9341#endif
9342
9343#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009344static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009345{
9346 const struct built_in_command *x;
9347
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009348 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009349 "Built-in commands:\n"
9350 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009351 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01009352 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009353 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009354 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009355 return EXIT_SUCCESS;
9356}
9357#endif
9358
Denys Vlasenkoff463a82013-05-12 02:45:23 +02009359#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02009360static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9361{
9362 show_history(G.line_input_state);
9363 return EXIT_SUCCESS;
9364}
9365#endif
9366
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009367#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009368static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009369{
9370 struct pipe *job;
9371 const char *status_string;
9372
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009373 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denis Vlasenko87a86552008-07-29 19:43:10 +00009374 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009375 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009376 status_string = "Stopped";
9377 else
9378 status_string = "Running";
9379
9380 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9381 }
9382 return EXIT_SUCCESS;
9383}
9384#endif
9385
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009386#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009387static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009388{
9389 void *p;
9390 unsigned long l;
9391
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009392# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02009393 /* Optional. Reduces probability of false positives */
9394 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009395# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009396 /* Crude attempt to find where "free memory" starts,
9397 * sans fragmentation. */
9398 p = malloc(240);
9399 l = (unsigned long)p;
9400 free(p);
9401 p = malloc(3400);
9402 if (l < (unsigned long)p) l = (unsigned long)p;
9403 free(p);
9404
Denys Vlasenko7f0ebbc2016-10-03 17:42:53 +02009405
9406# if 0 /* debug */
9407 {
9408 struct mallinfo mi = mallinfo();
9409 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
9410 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
9411 }
9412# endif
9413
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009414 if (!G.memleak_value)
9415 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02009416
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009417 l -= G.memleak_value;
9418 if ((long)l < 0)
9419 l = 0;
9420 l /= 1024;
9421 if (l > 127)
9422 l = 127;
9423
9424 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9425 return l;
9426}
9427#endif
9428
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009429static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009430{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009431 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009432 return EXIT_SUCCESS;
9433}
9434
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009435static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009436{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009437 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009438 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009439 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009440#if ENABLE_HUSH_FUNCTIONS
9441 smallint sv_flg;
9442#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009443
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009444 argv = skip_dash_dash(argv);
9445 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009446 if (!filename) {
9447 /* bash says: "bash: .: filename argument required" */
9448 return 2; /* bash compat */
9449 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009450 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009451 if (!strchr(filename, '/')) {
9452 arg_path = find_in_path(filename);
9453 if (arg_path)
9454 filename = arg_path;
9455 }
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009456 input = remember_FILE(fopen_or_warn(filename, "r"));
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009457 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009458 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009459 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009460 /* POSIX: non-interactive shell should abort here,
9461 * not merely fail. So far no one complained :)
9462 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009463 return EXIT_FAILURE;
9464 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009465
Mike Frysinger885b6f22009-04-18 21:04:25 +00009466#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009467 sv_flg = G_flag_return_in_progress;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009468 /* "we are inside sourced file, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009469 G_flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009470#endif
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009471 if (argv[1])
9472 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009473
Denys Vlasenko992e0ff2016-09-29 01:27:09 +02009474 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9475 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009476 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009477 fclose_and_forget(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009478
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009479 if (argv[1])
9480 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00009481#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009482 G_flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009483#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009484
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009485 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009486}
9487
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009488static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009489{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009490 int rc;
9491 mode_t mask;
9492
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009493 rc = 1;
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009494 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009495 argv = skip_dash_dash(argv);
9496 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009497 mode_t old_mask = mask;
9498
Denys Vlasenko6283f982015-10-07 16:56:20 +02009499 /* numeric umasks are taken as-is */
9500 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9501 if (!isdigit(argv[0][0]))
9502 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009503 mask = bb_parse_mode(argv[0], mask);
Denys Vlasenko6283f982015-10-07 16:56:20 +02009504 if (!isdigit(argv[0][0]))
9505 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009506 if ((unsigned)mask > 0777) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009507 mask = old_mask;
9508 /* bash messages:
9509 * bash: umask: 'q': invalid symbolic mode operator
9510 * bash: umask: 999: octal number out of range
9511 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02009512 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009513 rc = 0;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009514 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009515 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009516 /* Mimic bash */
9517 printf("%04o\n", (unsigned) mask);
9518 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009519 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009520 umask(mask);
9521
9522 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009523}
9524
Mike Frysinger56bdea12009-03-28 20:01:58 +00009525/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009526#if !ENABLE_HUSH_JOB
9527# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
9528#endif
9529static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +02009530{
9531 int ret = 0;
9532 for (;;) {
9533 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009534 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +02009535
Denys Vlasenko830ea352016-11-08 04:59:11 +01009536 if (!sigisemptyset(&G.pending_set))
9537 goto check_sig;
9538
Denys Vlasenko7e675362016-10-28 21:57:31 +02009539 /* waitpid is not interruptible by SA_RESTARTed
9540 * signals which we use. Thus, this ugly dance:
9541 */
9542
9543 /* Make sure possible SIGCHLD is stored in kernel's
9544 * pending signal mask before we call waitpid.
9545 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009546 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +02009547 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009548 sigfillset(&oldset); /* block all signals, remember old set */
9549 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009550
9551 if (!sigisemptyset(&G.pending_set)) {
9552 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009553 goto restore;
9554 }
9555
9556 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009557/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009558 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009559 debug_printf_exec("checkjobs:%d\n", ret);
9560#if ENABLE_HUSH_JOB
9561 if (waitfor_pipe) {
9562 int rcode = job_exited_or_stopped(waitfor_pipe);
9563 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
9564 if (rcode >= 0) {
9565 ret = rcode;
9566 sigprocmask(SIG_SETMASK, &oldset, NULL);
9567 break;
9568 }
9569 }
9570#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009571 /* if ECHILD, there are no children (ret is -1 or 0) */
9572 /* if ret == 0, no children changed state */
9573 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009574 if (errno == ECHILD || ret) {
9575 ret--;
9576 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009577 ret = 0;
9578 sigprocmask(SIG_SETMASK, &oldset, NULL);
9579 break;
9580 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009581 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009582 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9583 /* Note: sigsuspend invokes signal handler */
9584 sigsuspend(&oldset);
9585 restore:
9586 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +01009587 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009588 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009589 sig = check_and_run_traps();
9590 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009591 ret = 128 + sig;
9592 break;
9593 }
9594 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9595 }
9596 return ret;
9597}
9598
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009599static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00009600{
Denys Vlasenko7e675362016-10-28 21:57:31 +02009601 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009602 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009603
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009604 argv = skip_dash_dash(argv);
9605 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009606 /* Don't care about wait results */
9607 /* Note 1: must wait until there are no more children */
9608 /* Note 2: must be interruptible */
9609 /* Examples:
9610 * $ sleep 3 & sleep 6 & wait
9611 * [1] 30934 sleep 3
9612 * [2] 30935 sleep 6
9613 * [1] Done sleep 3
9614 * [2] Done sleep 6
9615 * $ sleep 3 & sleep 6 & wait
9616 * [1] 30936 sleep 3
9617 * [2] 30937 sleep 6
9618 * [1] Done sleep 3
9619 * ^C <-- after ~4 sec from keyboard
9620 * $
9621 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009622 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009623 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009624
Denys Vlasenko7e675362016-10-28 21:57:31 +02009625 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009626 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009627 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009628#if ENABLE_HUSH_JOB
9629 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +01009630 struct pipe *wait_pipe;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009631 wait_pipe = parse_jobspec(*argv);
9632 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +01009633 ret = job_exited_or_stopped(wait_pipe);
9634 if (ret < 0)
9635 ret = wait_for_child_or_signal(wait_pipe, 0);
9636 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009637 }
9638 }
9639#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00009640 /* mimic bash message */
9641 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009642 ret = EXIT_FAILURE;
9643 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009644 }
Denys Vlasenko02affb42016-11-08 00:59:29 +01009645
Denys Vlasenko7e675362016-10-28 21:57:31 +02009646 /* Do we have such child? */
9647 ret = waitpid(pid, &status, WNOHANG);
9648 if (ret < 0) {
9649 /* No */
9650 if (errno == ECHILD) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009651 if (G.last_bg_pid > 0 && pid == G.last_bg_pid) {
9652 /* "wait $!" but last bg task has already exited. Try:
9653 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
9654 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +01009655 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009656 */
Denys Vlasenko26ad94b2016-11-07 23:07:21 +01009657 /* ret = G.last_bg_pid_exitstatus - FIXME */
9658 } else {
9659 /* Example: "wait 1". mimic bash message */
9660 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009661 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009662 } else {
9663 /* ??? */
9664 bb_perror_msg("wait %s", *argv);
9665 }
9666 ret = 127;
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009667 continue; /* bash checks all argv[] */
9668 }
9669 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009670 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +01009671 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009672 } else {
9673 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +01009674 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +02009675 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009676 if (WIFSIGNALED(status))
9677 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009678 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009679 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009680
9681 return ret;
9682}
9683
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009684#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9685static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9686{
9687 if (argv[1]) {
9688 def = bb_strtou(argv[1], NULL, 10);
9689 if (errno || def < def_min || argv[2]) {
9690 bb_error_msg("%s: bad arguments", argv[0]);
9691 def = UINT_MAX;
9692 }
9693 }
9694 return def;
9695}
9696#endif
9697
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009698#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009699static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009700{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009701 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009702 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009703 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +02009704 /* if we came from builtin_continue(), need to undo "= 1" */
9705 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009706 return EXIT_SUCCESS; /* bash compat */
9707 }
Denys Vlasenko49117b42016-07-21 14:40:08 +02009708 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009709
9710 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9711 if (depth == UINT_MAX)
9712 G.flag_break_continue = BC_BREAK;
9713 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009714 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009715
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009716 return EXIT_SUCCESS;
9717}
9718
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009719static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009720{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009721 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9722 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009723}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009724#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009725
9726#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009727static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009728{
9729 int rc;
9730
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009731 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009732 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9733 return EXIT_FAILURE; /* bash compat */
9734 }
9735
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009736 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009737
9738 /* bash:
9739 * out of range: wraps around at 256, does not error out
9740 * non-numeric param:
9741 * f() { false; return qwe; }; f; echo $?
9742 * bash: return: qwe: numeric argument required <== we do this
9743 * 255 <== we also do this
9744 */
9745 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9746 return rc;
9747}
9748#endif