blob: fecc8929446959d850c313327168c5ec731f6281 [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 Vlasenko202a2d12010-07-16 12:36:14 +020085//config:config HUSH
86//config: bool "hush"
87//config: default y
88//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +020089//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +020090//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
91//config: case/esac. Redirections, here documents, $((arithmetic))
92//config: and functions are supported.
93//config:
94//config: It will compile and work on no-mmu systems.
95//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +020096//config: It does not handle select, aliases, tilde expansion,
97//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +020098//config:
99//config:config HUSH_BASH_COMPAT
100//config: bool "bash-compatible extensions"
101//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100102//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200103//config: help
104//config: Enable bash-compatible extensions.
105//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200106//config:config HUSH_BRACE_EXPANSION
107//config: bool "Brace expansion"
108//config: default y
109//config: depends on HUSH_BASH_COMPAT
110//config: help
111//config: Enable {abc,def} extension.
112//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200113//config:config HUSH_HELP
114//config: bool "help builtin"
115//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100116//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200117//config: help
118//config: Enable help builtin in hush. Code size + ~1 kbyte.
119//config:
120//config:config HUSH_INTERACTIVE
121//config: bool "Interactive mode"
122//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100123//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200124//config: help
125//config: Enable interactive mode (prompt and command editing).
126//config: Without this, hush simply reads and executes commands
127//config: from stdin just like a shell script from a file.
128//config: No prompt, no PS1/PS2 magic shell variables.
129//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200130//config:config HUSH_SAVEHISTORY
131//config: bool "Save command history to .hush_history"
132//config: default y
133//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
134//config: help
135//config: Enable history saving in hush.
136//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200137//config:config HUSH_JOB
138//config: bool "Job control"
139//config: default y
140//config: depends on HUSH_INTERACTIVE
141//config: help
142//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
143//config: command (not entire shell), fg/bg builtins work. Without this option,
144//config: "cmd &" still works by simply spawning a process and immediately
145//config: prompting for next command (or executing next command in a script),
146//config: but no separate process group is formed.
147//config:
148//config:config HUSH_TICK
149//config: bool "Process substitution"
150//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100151//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200152//config: help
153//config: Enable process substitution `command` and $(command) in hush.
154//config:
155//config:config HUSH_IF
156//config: bool "Support if/then/elif/else/fi"
157//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100158//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200159//config: help
160//config: Enable if/then/elif/else/fi in hush.
161//config:
162//config:config HUSH_LOOPS
163//config: bool "Support for, while and until loops"
164//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100165//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200166//config: help
167//config: Enable for, while and until loops in hush.
168//config:
169//config:config HUSH_CASE
170//config: bool "Support case ... esac statement"
171//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100172//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200173//config: help
174//config: Enable case ... esac statement in hush. +400 bytes.
175//config:
176//config:config HUSH_FUNCTIONS
177//config: bool "Support funcname() { commands; } syntax"
178//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100179//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200180//config: help
181//config: Enable support for shell functions in hush. +800 bytes.
182//config:
183//config:config HUSH_LOCAL
184//config: bool "Support local builtin"
185//config: default y
186//config: depends on HUSH_FUNCTIONS
187//config: help
188//config: Enable support for local variables in functions.
189//config:
190//config:config HUSH_RANDOM_SUPPORT
191//config: bool "Pseudorandom generator and $RANDOM variable"
192//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100193//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200194//config: help
195//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
196//config: Each read of "$RANDOM" will generate a new pseudorandom value.
197//config:
198//config:config HUSH_EXPORT_N
199//config: bool "Support 'export -n' option"
200//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100201//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200202//config: help
203//config: export -n unexports variables. It is a bash extension.
204//config:
205//config:config HUSH_MODE_X
206//config: bool "Support 'hush -x' option and 'set -x' command"
207//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200209//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200210//config: This instructs hush to print commands before execution.
211//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200212//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200213//config:config MSH
214//config: bool "msh (deprecated: aliased to hush)"
215//config: default n
216//config: select HUSH
217//config: help
218//config: msh is deprecated and will be removed, please migrate to hush.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200219
Denys Vlasenko20704f02011-03-23 17:59:27 +0100220//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100221//applet:IF_MSH(APPLET_ODDNAME(msh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
222//applet:IF_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
223//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100224
225//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100226//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
227//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100228//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
229
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100230/* -i (interactive) and -s (read stdin) are also accepted,
231 * but currently do nothing, therefore aren't shown in help.
232 * NOMMU-specific options are not meant to be used by users,
233 * therefore we don't show them either.
234 */
235//usage:#define hush_trivial_usage
Denys Vlasenkof58f7052011-05-12 02:10:33 +0200236//usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100237//usage:#define hush_full_usage "\n\n"
238//usage: "Unix shell interpreter"
239
Denys Vlasenko67047462016-12-22 15:21:58 +0100240#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
241 || defined(__APPLE__) \
242 )
243# include <malloc.h> /* for malloc_trim */
244#endif
245#include <glob.h>
246/* #include <dmalloc.h> */
247#if ENABLE_HUSH_CASE
248# include <fnmatch.h>
249#endif
250#include <sys/utsname.h> /* for setting $HOSTNAME */
251
252#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
253#include "unicode.h"
254#include "shell_common.h"
255#include "math.h"
256#include "match.h"
257#if ENABLE_HUSH_RANDOM_SUPPORT
258# include "random.h"
259#else
260# define CLEAR_RANDOM_T(rnd) ((void)0)
261#endif
262#ifndef F_DUPFD_CLOEXEC
263# define F_DUPFD_CLOEXEC F_DUPFD
264#endif
265#ifndef PIPE_BUF
266# define PIPE_BUF 4096 /* amount of buffering in a pipe */
267#endif
268
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000269
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200270/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000271#define LEAK_HUNTING 0
272#define BUILD_AS_NOMMU 0
273/* Enable/disable sanity checks. Ok to enable in production,
274 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
275 * Keeping 1 for now even in released versions.
276 */
277#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200278/* Slightly bigger (+200 bytes), but faster hush.
279 * So far it only enables a trick with counting SIGCHLDs and forks,
280 * which allows us to do fewer waitpid's.
281 * (we can detect a case where neither forks were done nor SIGCHLDs happened
282 * and therefore waitpid will return the same result as last time)
283 */
284#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200285/* TODO: implement simplified code for users which do not need ${var%...} ops
286 * So far ${var%...} ops are always enabled:
287 */
288#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000289
290
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000291#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000292# undef BB_MMU
293# undef USE_FOR_NOMMU
294# undef USE_FOR_MMU
295# define BB_MMU 0
296# define USE_FOR_NOMMU(...) __VA_ARGS__
297# define USE_FOR_MMU(...)
298#endif
299
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200300#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100301#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000302/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000303# undef CONFIG_FEATURE_SH_STANDALONE
304# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000305# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100306# undef IF_NOT_FEATURE_SH_STANDALONE
307# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000308# define IF_FEATURE_SH_STANDALONE(...)
309# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000310#endif
311
Denis Vlasenko05743d72008-02-10 12:10:08 +0000312#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000313# undef ENABLE_FEATURE_EDITING
314# define ENABLE_FEATURE_EDITING 0
315# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
316# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200317# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
318# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000319#endif
320
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000321/* Do we support ANY keywords? */
322#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000323# define HAS_KEYWORDS 1
324# define IF_HAS_KEYWORDS(...) __VA_ARGS__
325# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000326#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000327# define HAS_KEYWORDS 0
328# define IF_HAS_KEYWORDS(...)
329# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000330#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000331
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000332/* If you comment out one of these below, it will be #defined later
333 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000334#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000335/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000336#define debug_printf_parse(...) do {} while (0)
337#define debug_print_tree(a, b) do {} while (0)
338#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000339#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000340#define debug_printf_jobs(...) do {} while (0)
341#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200342#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000343#define debug_printf_glob(...) do {} while (0)
344#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000345#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000346#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000347
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000348#define ERR_PTR ((void*)(long)1)
349
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200350#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000351
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200352#define _SPECIAL_VARS_STR "_*@$!?#"
353#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
354#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200355#if ENABLE_HUSH_BASH_COMPAT
356/* Support / and // replace ops */
357/* Note that // is stored as \ in "encoded" string representation */
358# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
359# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
360# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
361#else
362# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
363# define VAR_SUBST_OPS "%#:-=+?"
364# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
365#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200366
367#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000368
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200369struct variable;
370
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000371static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
372
373/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000374 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000375 */
376#if !BB_MMU
377typedef struct nommu_save_t {
378 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200379 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000380 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000381 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000382} nommu_save_t;
383#endif
384
Denys Vlasenko9b782552010-09-08 13:33:26 +0200385enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000386 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000387#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000388 RES_IF ,
389 RES_THEN ,
390 RES_ELIF ,
391 RES_ELSE ,
392 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000393#endif
394#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000395 RES_FOR ,
396 RES_WHILE ,
397 RES_UNTIL ,
398 RES_DO ,
399 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000400#endif
401#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000402 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000403#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000404#if ENABLE_HUSH_CASE
405 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200406 /* three pseudo-keywords support contrived "case" syntax: */
407 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
408 RES_MATCH , /* "word)" */
409 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000410 RES_ESAC ,
411#endif
412 RES_XXXX ,
413 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200414};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000415
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000416typedef struct o_string {
417 char *data;
418 int length; /* position where data is appended */
419 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200420 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000421 /* At least some part of the string was inside '' or "",
422 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200423 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000424 smallint has_empty_slot;
425 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
426} o_string;
427enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200428 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
429 EXP_FLAG_GLOB = 0x2,
430 /* Protect newly added chars against globbing
431 * by prepending \ to *, ?, [, \ */
432 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
433};
434enum {
435 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000436 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200437 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200438 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200439 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000440};
441/* Used for initialization: o_string foo = NULL_O_STRING; */
442#define NULL_O_STRING { NULL }
443
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200444#ifndef debug_printf_parse
445static const char *const assignment_flag[] = {
446 "MAYBE_ASSIGNMENT",
447 "DEFINITELY_ASSIGNMENT",
448 "NOT_ASSIGNMENT",
449 "WORD_IS_KEYWORD",
450};
451#endif
452
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000453typedef struct in_str {
454 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000455#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000456 smallint promptmode; /* 0: PS1, 1: PS2 */
457#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200458 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200459 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000460 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000461} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000462
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200463/* The descrip member of this structure is only used to make
464 * debugging output pretty */
465static const struct {
466 int mode;
467 signed char default_fd;
468 char descrip[3];
469} redir_table[] = {
470 { O_RDONLY, 0, "<" },
471 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
472 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
473 { O_CREAT|O_RDWR, 1, "<>" },
474 { O_RDONLY, 0, "<<" },
475/* Should not be needed. Bogus default_fd helps in debugging */
476/* { O_RDONLY, 77, "<<" }, */
477};
478
Eric Andersen25f27032001-04-26 23:22:31 +0000479struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000480 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000481 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000482 int rd_fd; /* fd to redirect */
483 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
484 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000485 smallint rd_type; /* (enum redir_type) */
486 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000487 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200488 * bit 0: do we need to trim leading tabs?
489 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000490 */
Eric Andersen25f27032001-04-26 23:22:31 +0000491};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000492typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200493 REDIRECT_INPUT = 0,
494 REDIRECT_OVERWRITE = 1,
495 REDIRECT_APPEND = 2,
496 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000497 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200498 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000499
500 REDIRFD_CLOSE = -3,
501 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000502 REDIRFD_TO_FILE = -1,
503 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000504
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000505 HEREDOC_SKIPTABS = 1,
506 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000507} redir_type;
508
Eric Andersen25f27032001-04-26 23:22:31 +0000509
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000510struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000511 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000512 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200513 smallint cmd_type; /* CMD_xxx */
514#define CMD_NORMAL 0
515#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200516#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200517/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200518# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000519#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200520#if ENABLE_HUSH_FUNCTIONS
521# define CMD_FUNCDEF 3
522#endif
523
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100524 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200525 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
526 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000527#if !BB_MMU
528 char *group_as_string;
529#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000530#if ENABLE_HUSH_FUNCTIONS
531 struct function *child_func;
532/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200533 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000534 * When we execute "f1() {a;}" cmd, we create new function and clear
535 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200536 * When we execute "f1() {b;}", we notice that f1 exists,
537 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000538 * we put those fields back into cmd->xxx
539 * (struct function has ->parent_cmd ptr to facilitate that).
540 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
541 * Without this trick, loop would execute a;b;b;b;...
542 * instead of correct sequence a;b;a;b;...
543 * When command is freed, it severs the link
544 * (sets ->child_func->parent_cmd to NULL).
545 */
546#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000547 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000548/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
549 * and on execution these are substituted with their values.
550 * Substitution can make _several_ words out of one argv[n]!
551 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000552 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000553 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000554 struct redir_struct *redirects; /* I/O redirections */
555};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000556/* Is there anything in this command at all? */
557#define IS_NULL_CMD(cmd) \
558 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
559
Eric Andersen25f27032001-04-26 23:22:31 +0000560struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000561 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000562 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000563 int alive_cmds; /* number of commands running (not exited) */
564 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000565#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000566 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000567 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000568 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000569#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000570 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000571 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000572 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
573 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000574};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000575typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100576 PIPE_SEQ = 0,
577 PIPE_AND = 1,
578 PIPE_OR = 2,
579 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000580} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000581/* Is there anything in this pipe at all? */
582#define IS_NULL_PIPE(pi) \
583 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000584
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000585/* This holds pointers to the various results of parsing */
586struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000587 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000588 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000589 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000590 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000591 /* last command in pipe (being constructed right now) */
592 struct command *command;
593 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000594 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000595#if !BB_MMU
596 o_string as_string;
597#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000598#if HAS_KEYWORDS
599 smallint ctx_res_w;
600 smallint ctx_inverted; /* "! cmd | cmd" */
601#if ENABLE_HUSH_CASE
602 smallint ctx_dsemicolon; /* ";;" seen */
603#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000604 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
605 int old_flag;
606 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000607 * example: "if pipe1; pipe2; then pipe3; fi"
608 * when we see "if" or "then", we malloc and copy current context,
609 * and make ->stack point to it. then we parse pipeN.
610 * when closing "then" / fi" / whatever is found,
611 * we move list_head into ->stack->command->group,
612 * copy ->stack into current context, and delete ->stack.
613 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000614 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000615 struct parse_context *stack;
616#endif
617};
618
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000619/* On program start, environ points to initial environment.
620 * putenv adds new pointers into it, unsetenv removes them.
621 * Neither of these (de)allocates the strings.
622 * setenv allocates new strings in malloc space and does putenv,
623 * and thus setenv is unusable (leaky) for shell's purposes */
624#define setenv(...) setenv_is_leaky_dont_use()
625struct variable {
626 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000627 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200628#if ENABLE_HUSH_LOCAL
629 unsigned func_nest_level;
630#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000631 int max_len; /* if > 0, name is part of initial env; else name is malloced */
632 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000633 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000634};
635
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000636enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000637 BC_BREAK = 1,
638 BC_CONTINUE = 2,
639};
640
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000641#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000642struct function {
643 struct function *next;
644 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000645 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000646 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200647# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000648 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200649# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000650};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000651#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000652
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000653
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100654/* set -/+o OPT support. (TODO: make it optional)
655 * bash supports the following opts:
656 * allexport off
657 * braceexpand on
658 * emacs on
659 * errexit off
660 * errtrace off
661 * functrace off
662 * hashall on
663 * histexpand off
664 * history on
665 * ignoreeof off
666 * interactive-comments on
667 * keyword off
668 * monitor on
669 * noclobber off
670 * noexec off
671 * noglob off
672 * nolog off
673 * notify off
674 * nounset off
675 * onecmd off
676 * physical off
677 * pipefail off
678 * posix off
679 * privileged off
680 * verbose off
681 * vi off
682 * xtrace off
683 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800684static const char o_opt_strings[] ALIGN1 =
685 "pipefail\0"
686 "noexec\0"
687#if ENABLE_HUSH_MODE_X
688 "xtrace\0"
689#endif
690 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100691enum {
692 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800693 OPT_O_NOEXEC,
694#if ENABLE_HUSH_MODE_X
695 OPT_O_XTRACE,
696#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100697 NUM_OPT_O
698};
699
700
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200701struct FILE_list {
702 struct FILE_list *next;
703 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200704 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200705};
706
707
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000708/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000709/* Sorted roughly by size (smaller offsets == smaller code) */
710struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000711 /* interactive_fd != 0 means we are an interactive shell.
712 * If we are, then saved_tty_pgrp can also be != 0, meaning
713 * that controlling tty is available. With saved_tty_pgrp == 0,
714 * job control still works, but terminal signals
715 * (^C, ^Z, ^Y, ^\) won't work at all, and background
716 * process groups can only be created with "cmd &".
717 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
718 * to give tty to the foreground process group,
719 * and will take it back when the group is stopped (^Z)
720 * or killed (^C).
721 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000722#if ENABLE_HUSH_INTERACTIVE
723 /* 'interactive_fd' is a fd# open to ctty, if we have one
724 * _AND_ if we decided to act interactively */
725 int interactive_fd;
726 const char *PS1;
727 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000728# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000729#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000730# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000731#endif
732#if ENABLE_FEATURE_EDITING
733 line_input_t *line_input_state;
734#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000735 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200736 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000737 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200738#if ENABLE_HUSH_RANDOM_SUPPORT
739 random_t random_gen;
740#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000741#if ENABLE_HUSH_JOB
742 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000743 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000744 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000745 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400746# define G_saved_tty_pgrp (G.saved_tty_pgrp)
747#else
748# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000749#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100750 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100751#if ENABLE_HUSH_MODE_X
752# define G_x_mode (G.o_opt[OPT_O_XTRACE])
753#else
754# define G_x_mode 0
755#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000756 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000757#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000758 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000759#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000760#if ENABLE_HUSH_FUNCTIONS
761 /* 0: outside of a function (or sourced file)
762 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000763 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000764 */
765 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200766# define G_flag_return_in_progress (G.flag_return_in_progress)
767#else
768# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000769#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000770 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000771 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000772 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000773 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000774 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000775 /* how many non-NULL argv's we have. NB: $# + 1 */
776 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000777 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000778#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000779 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000780#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000781#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000782 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000783 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000784#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000785 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000786 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200787 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200788 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000789#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000790 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200791# if ENABLE_HUSH_LOCAL
792 struct variable **shadowed_vars_pp;
793 unsigned func_nest_level;
794# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000795#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000796 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200797#if ENABLE_HUSH_FAST
798 unsigned count_SIGCHLD;
799 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200800 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200801#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200802 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200803 /* Which signals have non-DFL handler (even with no traps set)?
804 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200805 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200806 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200807 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200808 * Other than these two times, never modified.
809 */
810 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200811#if ENABLE_HUSH_JOB
812 unsigned fatal_sig_mask;
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200813# define G_fatal_sig_mask G.fatal_sig_mask
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200814#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200815# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200816#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000817 char **traps; /* char *traps[NSIG] */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200818 sigset_t pending_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000819#if HUSH_DEBUG
820 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000821 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000822#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200823 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200824#if ENABLE_FEATURE_EDITING
825 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
826#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000827};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000828#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000829/* Not #defining name to G.name - this quickly gets unwieldy
830 * (too many defines). Also, I actually prefer to see when a variable
831 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000832#define INIT_G() do { \
833 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200834 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
835 sigfillset(&G.sa.sa_mask); \
836 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000837} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000838
839
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000840/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200841static int builtin_cd(char **argv) FAST_FUNC;
842static int builtin_echo(char **argv) FAST_FUNC;
843static int builtin_eval(char **argv) FAST_FUNC;
844static int builtin_exec(char **argv) FAST_FUNC;
845static int builtin_exit(char **argv) FAST_FUNC;
846static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000847#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200848static int builtin_fg_bg(char **argv) FAST_FUNC;
849static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000850#endif
851#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200852static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000853#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200854#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200855static int builtin_history(char **argv) FAST_FUNC;
856#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200857#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200858static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200859#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000860#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200861static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000862#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400863#if ENABLE_PRINTF
864static int builtin_printf(char **argv) FAST_FUNC;
865#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200866static int builtin_pwd(char **argv) FAST_FUNC;
867static int builtin_read(char **argv) FAST_FUNC;
868static int builtin_set(char **argv) FAST_FUNC;
869static int builtin_shift(char **argv) FAST_FUNC;
870static int builtin_source(char **argv) FAST_FUNC;
871static int builtin_test(char **argv) FAST_FUNC;
872static int builtin_trap(char **argv) FAST_FUNC;
873static int builtin_type(char **argv) FAST_FUNC;
874static int builtin_true(char **argv) FAST_FUNC;
875static int builtin_umask(char **argv) FAST_FUNC;
876static int builtin_unset(char **argv) FAST_FUNC;
877static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000878#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200879static int builtin_break(char **argv) FAST_FUNC;
880static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000881#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000882#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200883static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000884#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000885
886/* Table of built-in functions. They can be forked or not, depending on
887 * context: within pipes, they fork. As simple commands, they do not.
888 * When used in non-forking context, they can change global variables
889 * in the parent shell process. If forked, of course they cannot.
890 * For example, 'unset foo | whatever' will parse and run, but foo will
891 * still be set at the end. */
892struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100893 const char *b_cmd;
894 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000895#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100896 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200897# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000898#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200899# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000900#endif
901};
902
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200903static const struct built_in_command bltins1[] = {
904 BLTIN("." , builtin_source , "Run commands in a file"),
905 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000906#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200907 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000908#endif
909#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200910 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000911#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200912 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000913#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200914 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000915#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200916 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
917 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
918 BLTIN("exit" , builtin_exit , "Exit"),
919 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000920#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200921 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000922#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000923#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200924 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000925#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200926#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200927 BLTIN("history" , builtin_history , "Show command history"),
928#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000929#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200930 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000931#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200932#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200933 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200934#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000935#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200936 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000937#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200938 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000939#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200940 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000941#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200942 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
943 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200944#if ENABLE_HUSH_BASH_COMPAT
945 BLTIN("source" , builtin_source , "Run commands in a file"),
946#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200947 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko2bba5912014-03-14 12:43:57 +0100948 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100949 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100950 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200951 BLTIN("umask" , builtin_umask , "Set file creation mask"),
952 BLTIN("unset" , builtin_unset , "Unset variables"),
953 BLTIN("wait" , builtin_wait , "Wait for process"),
954};
955/* For now, echo and test are unconditionally enabled.
956 * Maybe make it configurable? */
957static const struct built_in_command bltins2[] = {
958 BLTIN("[" , builtin_test , NULL),
959 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400960#if ENABLE_PRINTF
961 BLTIN("printf" , builtin_printf , NULL),
962#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200963 BLTIN("pwd" , builtin_pwd , NULL),
964 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000965};
966
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000967
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000968/* Debug printouts.
969 */
970#if HUSH_DEBUG
971/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100972# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000973# define debug_enter() (G.debug_indent++)
974# define debug_leave() (G.debug_indent--)
975#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200976# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000977# define debug_enter() ((void)0)
978# define debug_leave() ((void)0)
979#endif
980
981#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100982# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000983#endif
984
985#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100986# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000987#endif
988
989#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100990#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000991#endif
992
993#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100994# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000995#endif
996
997#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100998# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000999# define DEBUG_JOBS 1
1000#else
1001# define DEBUG_JOBS 0
1002#endif
1003
1004#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001005# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001006# define DEBUG_EXPAND 1
1007#else
1008# define DEBUG_EXPAND 0
1009#endif
1010
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001011#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001012# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001013#endif
1014
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001015#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001016# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001017# define DEBUG_GLOB 1
1018#else
1019# define DEBUG_GLOB 0
1020#endif
1021
1022#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001023# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001024#endif
1025
1026#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001027# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001028#endif
1029
1030#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001031# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001032# define DEBUG_CLEAN 1
1033#else
1034# define DEBUG_CLEAN 0
1035#endif
1036
1037#if DEBUG_EXPAND
1038static void debug_print_strings(const char *prefix, char **vv)
1039{
1040 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001041 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001042 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001043 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001044}
1045#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001046# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001047#endif
1048
1049
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001050/* Leak hunting. Use hush_leaktool.sh for post-processing.
1051 */
1052#if LEAK_HUNTING
1053static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001054{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001055 void *ptr = xmalloc((size + 0xff) & ~0xff);
1056 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1057 return ptr;
1058}
1059static void *xxrealloc(int lineno, void *ptr, size_t size)
1060{
1061 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1062 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1063 return ptr;
1064}
1065static char *xxstrdup(int lineno, const char *str)
1066{
1067 char *ptr = xstrdup(str);
1068 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1069 return ptr;
1070}
1071static void xxfree(void *ptr)
1072{
1073 fdprintf(2, "free %p\n", ptr);
1074 free(ptr);
1075}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001076# define xmalloc(s) xxmalloc(__LINE__, s)
1077# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1078# define xstrdup(s) xxstrdup(__LINE__, s)
1079# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001080#endif
1081
1082
1083/* Syntax and runtime errors. They always abort scripts.
1084 * In interactive use they usually discard unparsed and/or unexecuted commands
1085 * and return to the prompt.
1086 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1087 */
1088#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001089# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001090# define syntax_error(lineno, msg) syntax_error(msg)
1091# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1092# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1093# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1094# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001095#endif
1096
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001097static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001098{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001099 va_list p;
1100
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001101#if HUSH_DEBUG >= 2
1102 bb_error_msg("hush.c:%u", lineno);
1103#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001104 va_start(p, fmt);
1105 bb_verror_msg(fmt, p, NULL);
1106 va_end(p);
1107 if (!G_interactive_fd)
1108 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001109}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001110
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001111static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001112{
1113 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001114 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001115 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001116 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001117}
1118
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001119static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001120{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001121 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001122}
1123
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001124static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001125{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001126 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001127}
1128
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001129static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001130{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001131 char msg[2] = { ch, '\0' };
1132 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001133}
1134
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001135static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001136{
1137 char msg[2];
1138 msg[0] = ch;
1139 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001140 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001141}
1142
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001143#if HUSH_DEBUG < 2
1144# undef die_if_script
1145# undef syntax_error
1146# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001147# undef syntax_error_unterm_ch
1148# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001149# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001150#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001151# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001152# define syntax_error(msg) syntax_error(__LINE__, msg)
1153# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1154# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1155# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1156# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001157#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001158
Denis Vlasenko552433b2009-04-04 19:29:21 +00001159
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001160#if ENABLE_HUSH_INTERACTIVE
1161static void cmdedit_update_prompt(void);
1162#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001163# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001164#endif
1165
1166
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001167/* Utility functions
1168 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001169/* Replace each \x with x in place, return ptr past NUL. */
1170static char *unbackslash(char *src)
1171{
Denys Vlasenko71885402009-09-24 01:44:13 +02001172 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001173 while (1) {
1174 if (*src == '\\')
1175 src++;
1176 if ((*dst++ = *src++) == '\0')
1177 break;
1178 }
1179 return dst;
1180}
1181
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001182static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001183{
1184 int i;
1185 unsigned count1;
1186 unsigned count2;
1187 char **v;
1188
1189 v = strings;
1190 count1 = 0;
1191 if (v) {
1192 while (*v) {
1193 count1++;
1194 v++;
1195 }
1196 }
1197 count2 = 0;
1198 v = add;
1199 while (*v) {
1200 count2++;
1201 v++;
1202 }
1203 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1204 v[count1 + count2] = NULL;
1205 i = count2;
1206 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001207 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001208 return v;
1209}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001210#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001211static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1212{
1213 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1214 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1215 return ptr;
1216}
1217#define add_strings_to_strings(strings, add, need_to_dup) \
1218 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1219#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001220
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001221/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001222static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001223{
1224 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001225 v[0] = add;
1226 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001227 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001228}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001229#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001230static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1231{
1232 char **ptr = add_string_to_strings(strings, add);
1233 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1234 return ptr;
1235}
1236#define add_string_to_strings(strings, add) \
1237 xx_add_string_to_strings(__LINE__, strings, add)
1238#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001239
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001240static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001241{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001242 char **v;
1243
1244 if (!strings)
1245 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001246 v = strings;
1247 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001248 free(*v);
1249 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001250 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001251 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001252}
1253
Denis Vlasenko76d50412008-06-10 16:19:39 +00001254
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001255static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1256{
1257 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1258 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1259 if (newfd < 0) {
1260 /* fd was not open? */
1261 if (errno == EBADF)
1262 return fd;
1263 xfunc_die();
1264 }
1265 close(fd);
1266 return newfd;
1267}
1268
1269
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001270/* Manipulating the list of open FILEs */
1271static FILE *remember_FILE(FILE *fp)
1272{
1273 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001274 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001275 n->next = G.FILE_list;
1276 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001277 n->fp = fp;
1278 n->fd = fileno(fp);
1279 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001280 }
1281 return fp;
1282}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001283static void fclose_and_forget(FILE *fp)
1284{
1285 struct FILE_list **pp = &G.FILE_list;
1286 while (*pp) {
1287 struct FILE_list *cur = *pp;
1288 if (cur->fp == fp) {
1289 *pp = cur->next;
1290 free(cur);
1291 break;
1292 }
1293 pp = &cur->next;
1294 }
1295 fclose(fp);
1296}
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001297static int save_FILEs_on_redirect(int fd)
1298{
1299 struct FILE_list *fl = G.FILE_list;
1300 while (fl) {
1301 if (fd == fl->fd) {
1302 /* We use it only on script files, they are all CLOEXEC */
1303 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1304 return 1;
1305 }
1306 fl = fl->next;
1307 }
1308 return 0;
1309}
1310static void restore_redirected_FILEs(void)
1311{
1312 struct FILE_list *fl = G.FILE_list;
1313 while (fl) {
1314 int should_be = fileno(fl->fp);
1315 if (fl->fd != should_be) {
1316 xmove_fd(fl->fd, should_be);
1317 fl->fd = should_be;
1318 }
1319 fl = fl->next;
1320 }
1321}
1322#if ENABLE_FEATURE_SH_STANDALONE
1323static void close_all_FILE_list(void)
1324{
1325 struct FILE_list *fl = G.FILE_list;
1326 while (fl) {
1327 /* fclose would also free FILE object.
1328 * It is disastrous if we share memory with a vforked parent.
1329 * I'm not sure we never come here after vfork.
1330 * Therefore just close fd, nothing more.
1331 */
1332 /*fclose(fl->fp); - unsafe */
1333 close(fl->fd);
1334 fl = fl->next;
1335 }
1336}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001337#endif
1338
1339
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001340/* Helpers for setting new $n and restoring them back
1341 */
1342typedef struct save_arg_t {
1343 char *sv_argv0;
1344 char **sv_g_argv;
1345 int sv_g_argc;
1346 smallint sv_g_malloced;
1347} save_arg_t;
1348
1349static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1350{
1351 int n;
1352
1353 sv->sv_argv0 = argv[0];
1354 sv->sv_g_argv = G.global_argv;
1355 sv->sv_g_argc = G.global_argc;
1356 sv->sv_g_malloced = G.global_args_malloced;
1357
1358 argv[0] = G.global_argv[0]; /* retain $0 */
1359 G.global_argv = argv;
1360 G.global_args_malloced = 0;
1361
1362 n = 1;
1363 while (*++argv)
1364 n++;
1365 G.global_argc = n;
1366}
1367
1368static void restore_G_args(save_arg_t *sv, char **argv)
1369{
1370 char **pp;
1371
1372 if (G.global_args_malloced) {
1373 /* someone ran "set -- arg1 arg2 ...", undo */
1374 pp = G.global_argv;
1375 while (*++pp) /* note: does not free $0 */
1376 free(*pp);
1377 free(G.global_argv);
1378 }
1379 argv[0] = sv->sv_argv0;
1380 G.global_argv = sv->sv_g_argv;
1381 G.global_argc = sv->sv_g_argc;
1382 G.global_args_malloced = sv->sv_g_malloced;
1383}
1384
1385
Denis Vlasenkod5762932009-03-31 11:22:57 +00001386/* Basic theory of signal handling in shell
1387 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001388 * This does not describe what hush does, rather, it is current understanding
1389 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001390 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1391 *
1392 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1393 * is finished or backgrounded. It is the same in interactive and
1394 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001395 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001396 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001397 * backgrounds (i.e. stops) or kills all members of currently running
1398 * pipe.
1399 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001400 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001401 * or by SIGINT in interactive shell.
1402 *
1403 * Trap handlers will execute even within trap handlers. (right?)
1404 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001405 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1406 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001407 *
1408 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001409 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001410 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001411 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001412 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001413 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001414 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001415 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001416 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001417 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001418 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001419 *
1420 * SIGQUIT: ignore
1421 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001422 * SIGHUP (interactive):
1423 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001424 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001425 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1426 * that all pipe members are stopped. Try this in bash:
1427 * while :; do :; done - ^Z does not background it
1428 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001429 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001430 * of the command line, show prompt. NB: ^C does not send SIGINT
1431 * to interactive shell while shell is waiting for a pipe,
1432 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001433 * Example 1: this waits 5 sec, but does not execute ls:
1434 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1435 * Example 2: this does not wait and does not execute ls:
1436 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1437 * Example 3: this does not wait 5 sec, but executes ls:
1438 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001439 * Example 4: this does not wait and does not execute ls:
1440 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001441 *
1442 * (What happens to signals which are IGN on shell start?)
1443 * (What happens with signal mask on shell start?)
1444 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001445 * Old implementation
1446 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001447 * We use in-kernel pending signal mask to determine which signals were sent.
1448 * We block all signals which we don't want to take action immediately,
1449 * i.e. we block all signals which need to have special handling as described
1450 * above, and all signals which have traps set.
1451 * After each pipe execution, we extract any pending signals via sigtimedwait()
1452 * and act on them.
1453 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001454 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001455 * sigset_t blocked_set: current blocked signal set
1456 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001457 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001458 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001459 * "trap 'cmd' SIGxxx":
1460 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001461 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001462 * unblock signals with special interactive handling
1463 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001464 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001465 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001466 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001467 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001468 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001469 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001470 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001471 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001472 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001473 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001474 * Standard says "When a subshell is entered, traps that are not being ignored
1475 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001476 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001477 *
1478 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001479 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001480 * masked signals are not visible!
1481 *
1482 * New implementation
1483 * ==================
1484 * We record each signal we are interested in by installing signal handler
1485 * for them - a bit like emulating kernel pending signal mask in userspace.
1486 * We are interested in: signals which need to have special handling
1487 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001488 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001489 * After each pipe execution, we extract any pending signals
1490 * and act on them.
1491 *
1492 * unsigned special_sig_mask: a mask of shell-special signals.
1493 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1494 * char *traps[sig] if trap for sig is set (even if it's '').
1495 * sigset_t pending_set: set of sigs we received.
1496 *
1497 * "trap - SIGxxx":
1498 * if sig is in special_sig_mask, set handler back to:
1499 * record_pending_signo, or to IGN if it's a tty stop signal
1500 * if sig is in fatal_sig_mask, set handler back to sigexit.
1501 * else: set handler back to SIG_DFL
1502 * "trap 'cmd' SIGxxx":
1503 * set handler to record_pending_signo.
1504 * "trap '' SIGxxx":
1505 * set handler to SIG_IGN.
1506 * after [v]fork, if we plan to be a shell:
1507 * set signals with special interactive handling to SIG_DFL
1508 * (because child shell is not interactive),
1509 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1510 * after [v]fork, if we plan to exec:
1511 * POSIX says fork clears pending signal mask in child - no need to clear it.
1512 *
1513 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1514 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1515 *
1516 * Note (compat):
1517 * Standard says "When a subshell is entered, traps that are not being ignored
1518 * are set to the default actions". bash interprets it so that traps which
1519 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001520 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001521enum {
1522 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001523 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001524 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001525 | (1 << SIGHUP)
1526 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001527 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001528#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001529 | (1 << SIGTTIN)
1530 | (1 << SIGTTOU)
1531 | (1 << SIGTSTP)
1532#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001533 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001534};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001535
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001536static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001537{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001538 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001539#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001540 if (sig == SIGCHLD) {
1541 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001542//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 +02001543 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001544#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001545}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001546
Denys Vlasenko0806e402011-05-12 23:06:20 +02001547static sighandler_t install_sighandler(int sig, sighandler_t handler)
1548{
1549 struct sigaction old_sa;
1550
1551 /* We could use signal() to install handlers... almost:
1552 * except that we need to mask ALL signals while handlers run.
1553 * I saw signal nesting in strace, race window isn't small.
1554 * SA_RESTART is also needed, but in Linux, signal()
1555 * sets SA_RESTART too.
1556 */
1557 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1558 /* sigfillset(&G.sa.sa_mask); - already done */
1559 /* G.sa.sa_flags = SA_RESTART; - already done */
1560 G.sa.sa_handler = handler;
1561 sigaction(sig, &G.sa, &old_sa);
1562 return old_sa.sa_handler;
1563}
1564
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001565static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001566
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001567static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001568static void restore_ttypgrp_and__exit(void)
1569{
1570 /* xfunc has failed! die die die */
1571 /* no EXIT traps, this is an escape hatch! */
1572 G.exiting = 1;
1573 hush_exit(xfunc_error_retval);
1574}
1575
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001576#if ENABLE_HUSH_JOB
1577
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001578/* Needed only on some libc:
1579 * It was observed that on exit(), fgetc'ed buffered data
1580 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1581 * With the net effect that even after fork(), not vfork(),
1582 * exit() in NOEXECed applet in "sh SCRIPT":
1583 * noexec_applet_here
1584 * echo END_OF_SCRIPT
1585 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1586 * This makes "echo END_OF_SCRIPT" executed twice.
1587 * Similar problems can be seen with die_if_script() -> xfunc_die()
1588 * and in `cmd` handling.
1589 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1590 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001591static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001592static void fflush_and__exit(void)
1593{
1594 fflush_all();
1595 _exit(xfunc_error_retval);
1596}
1597
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001598/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001599# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001600/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001601# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001602
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001603/* Restores tty foreground process group, and exits.
1604 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001605 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001606 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001607 * We also call it if xfunc is exiting.
1608 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001609static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001610static void sigexit(int sig)
1611{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001612 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001613 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001614 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1615 /* Disable all signals: job control, SIGPIPE, etc.
1616 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1617 */
1618 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001619 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001620 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001621
1622 /* Not a signal, just exit */
1623 if (sig <= 0)
1624 _exit(- sig);
1625
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001626 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001627}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001628#else
1629
Denys Vlasenko8391c482010-05-22 17:50:43 +02001630# define disable_restore_tty_pgrp_on_exit() ((void)0)
1631# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001632
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001633#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001634
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001635static sighandler_t pick_sighandler(unsigned sig)
1636{
1637 sighandler_t handler = SIG_DFL;
1638 if (sig < sizeof(unsigned)*8) {
1639 unsigned sigmask = (1 << sig);
1640
1641#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001642 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001643 if (G_fatal_sig_mask & sigmask)
1644 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001645 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001646#endif
1647 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001648 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001649 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001650 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001651 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001652 * in an endless loop when we try to do some
1653 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001654 */
1655 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1656 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001657 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001658 }
1659 return handler;
1660}
1661
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001662/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001663static void hush_exit(int exitcode)
1664{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001665#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1666 save_history(G.line_input_state);
1667#endif
1668
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001669 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001670 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001671 char *argv[3];
1672 /* argv[0] is unused */
1673 argv[1] = G.traps[0];
1674 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001675 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001676 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001677 * "trap" will still show it, if executed
1678 * in the handler */
1679 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001680 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001681
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001682#if ENABLE_FEATURE_CLEAN_UP
1683 {
1684 struct variable *cur_var;
1685 if (G.cwd != bb_msg_unknown)
1686 free((char*)G.cwd);
1687 cur_var = G.top_var;
1688 while (cur_var) {
1689 struct variable *tmp = cur_var;
1690 if (!cur_var->max_len)
1691 free(cur_var->varstr);
1692 cur_var = cur_var->next;
1693 free(tmp);
1694 }
1695 }
1696#endif
1697
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001698 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001699#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001700 sigexit(- (exitcode & 0xff));
1701#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001702 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001703#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001704}
1705
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001706
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001707//TODO: return a mask of ALL handled sigs?
1708static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001709{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001710 int last_sig = 0;
1711
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001712 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001713 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001714
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001715 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001716 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001717 sig = 0;
1718 do {
1719 sig++;
1720 if (sigismember(&G.pending_set, sig)) {
1721 sigdelset(&G.pending_set, sig);
1722 goto got_sig;
1723 }
1724 } while (sig < NSIG);
1725 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001726 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001727 if (G.traps && G.traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001728 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001729 if (G.traps[sig][0]) {
1730 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001731 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001732 char *argv[3];
1733 /* argv[0] is unused */
1734 argv[1] = G.traps[sig];
1735 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001736 save_rcode = G.last_exitcode;
1737 builtin_eval(argv);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01001738//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001739 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001740 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001741 } /* else: "" trap, ignoring signal */
1742 continue;
1743 }
1744 /* not a trap: special action */
1745 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001746 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001747 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001748 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001749 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001750 break;
1751#if ENABLE_HUSH_JOB
1752 case SIGHUP: {
1753 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001754 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001755 /* bash is observed to signal whole process groups,
1756 * not individual processes */
1757 for (job = G.job_list; job; job = job->next) {
1758 if (job->pgrp <= 0)
1759 continue;
1760 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1761 if (kill(- job->pgrp, SIGHUP) == 0)
1762 kill(- job->pgrp, SIGCONT);
1763 }
1764 sigexit(SIGHUP);
1765 }
1766#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001767#if ENABLE_HUSH_FAST
1768 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001769 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001770 G.count_SIGCHLD++;
1771//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1772 /* Note:
1773 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1774 * This simplifies wait builtin a bit.
1775 */
1776 break;
1777#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001778 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001779 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001780 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001781 /* Note:
1782 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1783 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001784 * in interactive shell, because TERM is ignored.
1785 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001786 break;
1787 }
1788 }
1789 return last_sig;
1790}
1791
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001792
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001793static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001794{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001795 if (force || G.cwd == NULL) {
1796 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1797 * we must not try to free(bb_msg_unknown) */
1798 if (G.cwd == bb_msg_unknown)
1799 G.cwd = NULL;
1800 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1801 if (!G.cwd)
1802 G.cwd = bb_msg_unknown;
1803 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001804 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001805}
1806
Denis Vlasenko83506862007-11-23 13:11:42 +00001807
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001808/*
1809 * Shell and environment variable support
1810 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001811static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001812{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001813 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001814 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001815
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001816 pp = &G.top_var;
1817 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001818 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001819 return pp;
1820 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001821 }
1822 return NULL;
1823}
1824
Denys Vlasenko03dad222010-01-12 23:29:57 +01001825static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001826{
Denys Vlasenko29082232010-07-16 13:52:32 +02001827 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001828 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001829
1830 if (G.expanded_assignments) {
1831 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001832 while (*cpp) {
1833 char *cp = *cpp;
1834 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1835 return cp + len + 1;
1836 cpp++;
1837 }
1838 }
1839
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001840 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001841 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001842 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001843
Denys Vlasenkodea47882009-10-09 15:40:49 +02001844 if (strcmp(name, "PPID") == 0)
1845 return utoa(G.root_ppid);
1846 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001847#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001848 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001849 return utoa(next_random(&G.random_gen));
1850#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001851 return NULL;
1852}
1853
1854/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001855 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001856 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001857 * 0: do not change export flag
1858 * (if creating new variable, flag will be 0)
1859 * 1: set export flag and putenv the variable
1860 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001861 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001862 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001863#if !BB_MMU && ENABLE_HUSH_LOCAL
1864/* all params are used */
1865#elif BB_MMU && ENABLE_HUSH_LOCAL
1866#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1867 set_local_var(str, flg_export, local_lvl)
1868#elif BB_MMU && !ENABLE_HUSH_LOCAL
1869#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001870 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001871#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1872#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1873 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001874#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001875static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001876{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001877 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001878 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001879 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001880 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001881 int name_len;
1882
Denis Vlasenko950bd722009-04-21 11:23:56 +00001883 eq_sign = strchr(str, '=');
1884 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001885 free(str);
1886 return -1;
1887 }
1888
Denis Vlasenko950bd722009-04-21 11:23:56 +00001889 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001890 var_pp = &G.top_var;
1891 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001892 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001893 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001894 continue;
1895 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001896
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001897 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001898 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001899#if !BB_MMU
1900 if (!flg_read_only)
1901#endif
1902 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001903 free(str);
1904 return -1;
1905 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001906 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001907 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1908 *eq_sign = '\0';
1909 unsetenv(str);
1910 *eq_sign = '=';
1911 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001912#if ENABLE_HUSH_LOCAL
1913 if (cur->func_nest_level < local_lvl) {
1914 /* New variable is declared as local,
1915 * and existing one is global, or local
1916 * from enclosing function.
1917 * Remove and save old one: */
1918 *var_pp = cur->next;
1919 cur->next = *G.shadowed_vars_pp;
1920 *G.shadowed_vars_pp = cur;
1921 /* bash 3.2.33(1) and exported vars:
1922 * # export z=z
1923 * # f() { local z=a; env | grep ^z; }
1924 * # f
1925 * z=a
1926 * # env | grep ^z
1927 * z=z
1928 */
1929 if (cur->flg_export)
1930 flg_export = 1;
1931 break;
1932 }
1933#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001934 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001935 free_and_exp:
1936 free(str);
1937 goto exp;
1938 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001939 if (cur->max_len != 0) {
1940 if (cur->max_len >= strlen(str)) {
1941 /* This one is from startup env, reuse space */
1942 strcpy(cur->varstr, str);
1943 goto free_and_exp;
1944 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001945 /* Can't reuse */
1946 cur->max_len = 0;
1947 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001948 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001949 /* max_len == 0 signifies "malloced" var, which we can
1950 * (and have to) free. But we can't free(cur->varstr) here:
1951 * if cur->flg_export is 1, it is in the environment.
1952 * We should either unsetenv+free, or wait until putenv,
1953 * then putenv(new)+free(old).
1954 */
1955 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001956 goto set_str_and_exp;
1957 }
1958
Denys Vlasenko295fef82009-06-03 12:47:26 +02001959 /* Not found - create new variable struct */
1960 cur = xzalloc(sizeof(*cur));
1961#if ENABLE_HUSH_LOCAL
1962 cur->func_nest_level = local_lvl;
1963#endif
1964 cur->next = *var_pp;
1965 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001966
1967 set_str_and_exp:
1968 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001969#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001970 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001971#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001972 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001973 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001974 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001975 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1976 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001977 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001978 if (flg_export == -1) {
1979 cur->flg_export = 0;
1980 /* unsetenv was already done */
1981 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001982 int i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001983 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001984 i = putenv(cur->varstr);
1985 /* only now we can free old exported malloced string */
1986 free(free_me);
1987 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001988 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001989 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001990 free(free_me);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001991 return 0;
1992}
1993
Denys Vlasenko6db47842009-09-05 20:15:17 +02001994/* Used at startup and after each cd */
1995static void set_pwd_var(int exp)
1996{
1997 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1998 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1999}
2000
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002001static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002002{
2003 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002004 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002005
2006 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002007 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002008 var_pp = &G.top_var;
2009 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002010 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2011 if (cur->flg_read_only) {
2012 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002013 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002014 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002015 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002016 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2017 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002018 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2019 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002020 if (!cur->max_len)
2021 free(cur->varstr);
2022 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002023 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002024 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002025 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002026 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002027 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002028}
2029
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002030static int unset_local_var(const char *name)
2031{
2032 return unset_local_var_len(name, strlen(name));
2033}
2034
2035static void unset_vars(char **strings)
2036{
2037 char **v;
2038
2039 if (!strings)
2040 return;
2041 v = strings;
2042 while (*v) {
2043 const char *eq = strchrnul(*v, '=');
2044 unset_local_var_len(*v, (int)(eq - *v));
2045 v++;
2046 }
2047 free(strings);
2048}
2049
Denys Vlasenko03dad222010-01-12 23:29:57 +01002050static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002051{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002052 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01002053 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002054}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002055
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002056
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002057/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002058 * Helpers for "var1=val1 var2=val2 cmd" feature
2059 */
2060static void add_vars(struct variable *var)
2061{
2062 struct variable *next;
2063
2064 while (var) {
2065 next = var->next;
2066 var->next = G.top_var;
2067 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002068 if (var->flg_export) {
2069 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002070 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002071 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002072 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002073 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002074 var = next;
2075 }
2076}
2077
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002078static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002079{
2080 char **s;
2081 struct variable *old = NULL;
2082
2083 if (!strings)
2084 return old;
2085 s = strings;
2086 while (*s) {
2087 struct variable *var_p;
2088 struct variable **var_pp;
2089 char *eq;
2090
2091 eq = strchr(*s, '=');
2092 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002093 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002094 if (var_pp) {
2095 /* Remove variable from global linked list */
2096 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002097 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002098 *var_pp = var_p->next;
2099 /* Add it to returned list */
2100 var_p->next = old;
2101 old = var_p;
2102 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002103 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002104 }
2105 s++;
2106 }
2107 return old;
2108}
2109
2110
2111/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002112 * Unicode helper
2113 */
2114static void reinit_unicode_for_hush(void)
2115{
2116 /* Unicode support should be activated even if LANG is set
2117 * _during_ shell execution, not only if it was set when
2118 * shell was started. Therefore, re-check LANG every time:
2119 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002120 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2121 || ENABLE_UNICODE_USING_LOCALE
2122 ) {
2123 const char *s = get_local_var_value("LC_ALL");
2124 if (!s) s = get_local_var_value("LC_CTYPE");
2125 if (!s) s = get_local_var_value("LANG");
2126 reinit_unicode(s);
2127 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002128}
2129
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002130/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002131 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002132 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002133
2134#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002135/* To test correct lineedit/interactive behavior, type from command line:
2136 * echo $P\
2137 * \
2138 * AT\
2139 * H\
2140 * \
2141 * It excercises a lot of corner cases.
2142 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002143static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002144{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002145 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002146 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002147 if (G.PS1 == NULL)
2148 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002149 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002150 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002151 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002152 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002153 if (G.PS2 == NULL)
2154 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002155}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002156static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002157{
2158 const char *prompt_str;
2159 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002160 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2161 /* Set up the prompt */
2162 if (promptmode == 0) { /* PS1 */
2163 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002164 /* bash uses $PWD value, even if it is set by user.
2165 * It uses current dir only if PWD is unset.
2166 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002167 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002168 prompt_str = G.PS1;
2169 } else
2170 prompt_str = G.PS2;
2171 } else
2172 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002173 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002174 return prompt_str;
2175}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002176static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002177{
2178 int r;
2179 const char *prompt_str;
2180
2181 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002182# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002183 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002184 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002185 if (G.flag_SIGINT) {
2186 /* There was ^C'ed, make it look prettier: */
2187 bb_putchar('\n');
2188 G.flag_SIGINT = 0;
2189 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002190 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002191 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002192 r = read_line_input(G.line_input_state, prompt_str,
2193 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2194 /*timeout*/ -1
2195 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002196 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2197 if (r == 0) {
2198 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002199 raise(SIGINT);
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002200 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002201 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002202 if (r != 0 && !G.flag_SIGINT)
2203 break;
2204 /* ^C or SIGINT: repeat */
2205 G.last_exitcode = 128 + SIGINT;
2206 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002207 if (r < 0) {
2208 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002209 i->p = NULL;
2210 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002211 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002212 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002213 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002214 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002215# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002216 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002217 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002218 if (i->last_char == '\0' || i->last_char == '\n') {
2219 /* Why check_and_run_traps here? Try this interactively:
2220 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2221 * $ <[enter], repeatedly...>
2222 * Without check_and_run_traps, handler never runs.
2223 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002224 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002225 fputs(prompt_str, stdout);
2226 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002227 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002228//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002229 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002230 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2231 * no ^C masking happens during fgetc, no special code for ^C:
2232 * it generates SIGINT as usual.
2233 */
2234 check_and_run_traps();
2235 if (G.flag_SIGINT)
2236 G.last_exitcode = 128 + SIGINT;
2237 if (r != '\0')
2238 break;
2239 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002240 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002241# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002242}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002243/* This is the magic location that prints prompts
2244 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002245static int fgetc_interactive(struct in_str *i)
2246{
2247 int ch;
2248 /* If it's interactive stdin, get new line. */
2249 if (G_interactive_fd && i->file == stdin) {
2250 /* Returns first char (or EOF), the rest is in i->p[] */
2251 ch = get_user_input(i);
2252 i->promptmode = 1; /* PS2 */
2253 } else {
2254 /* Not stdin: script file, sourced file, etc */
2255 do ch = fgetc(i->file); while (ch == '\0');
2256 }
2257 return ch;
2258}
2259#else
2260static inline int fgetc_interactive(struct in_str *i)
2261{
2262 int ch;
2263 do ch = fgetc(i->file); while (ch == '\0');
2264 return ch;
2265}
2266#endif /* INTERACTIVE */
2267
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002268static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002269{
2270 int ch;
2271
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002272 if (!i->file) {
2273 /* string-based in_str */
2274 ch = (unsigned char)*i->p;
2275 if (ch != '\0') {
2276 i->p++;
2277 i->last_char = ch;
2278 return ch;
2279 }
2280 return EOF;
2281 }
2282
2283 /* FILE-based in_str */
2284
Denys Vlasenko4074d492016-09-30 01:49:53 +02002285#if ENABLE_FEATURE_EDITING
2286 /* This can be stdin, check line editing char[] buffer */
2287 if (i->p && *i->p != '\0') {
2288 ch = (unsigned char)*i->p++;
2289 goto out;
2290 }
2291#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002292 /* peek_buf[] is an int array, not char. Can contain EOF. */
2293 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002294 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002295 int ch2 = i->peek_buf[1];
2296 i->peek_buf[0] = ch2;
2297 if (ch2 == 0) /* very likely, avoid redundant write */
2298 goto out;
2299 i->peek_buf[1] = 0;
2300 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002301 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002302
Denys Vlasenko4074d492016-09-30 01:49:53 +02002303 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002304 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002305 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002306 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002307 return ch;
2308}
2309
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002310static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002311{
2312 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002313
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002314 if (!i->file) {
2315 /* string-based in_str */
2316 /* Doesn't report EOF on NUL. None of the callers care. */
2317 return (unsigned char)*i->p;
2318 }
2319
2320 /* FILE-based in_str */
2321
Denys Vlasenko4074d492016-09-30 01:49:53 +02002322#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002323 /* This can be stdin, check line editing char[] buffer */
2324 if (i->p && *i->p != '\0')
2325 return (unsigned char)*i->p;
2326#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002327 /* peek_buf[] is an int array, not char. Can contain EOF. */
2328 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002329 if (ch != 0)
2330 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002331
Denys Vlasenko4074d492016-09-30 01:49:53 +02002332 /* Need to get a new char */
2333 ch = fgetc_interactive(i);
2334 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2335
2336 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2337#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2338 if (i->p) {
2339 i->p -= 1;
2340 return ch;
2341 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002342#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002343 i->peek_buf[0] = ch;
2344 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002345 return ch;
2346}
2347
Denys Vlasenko4074d492016-09-30 01:49:53 +02002348/* Only ever called if i_peek() was called, and did not return EOF.
2349 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2350 * not end-of-line. Therefore we never need to read a new editing line here.
2351 */
2352static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002353{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002354 int ch;
2355
2356 /* There are two cases when i->p[] buffer exists.
2357 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002358 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002359 * In both cases, we know that i->p[0] exists and not NUL, and
2360 * the peek2 result is in i->p[1].
2361 */
2362 if (i->p)
2363 return (unsigned char)i->p[1];
2364
2365 /* Now we know it is a file-based in_str. */
2366
2367 /* peek_buf[] is an int array, not char. Can contain EOF. */
2368 /* Is there 2nd char? */
2369 ch = i->peek_buf[1];
2370 if (ch == 0) {
2371 /* We did not read it yet, get it now */
2372 do ch = fgetc(i->file); while (ch == '\0');
2373 i->peek_buf[1] = ch;
2374 }
2375
2376 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2377 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002378}
2379
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002380static void setup_file_in_str(struct in_str *i, FILE *f)
2381{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002382 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002383 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002384 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002385 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002386}
2387
2388static void setup_string_in_str(struct in_str *i, const char *s)
2389{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002390 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002391 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002392 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002393 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002394}
2395
2396
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002397/*
2398 * o_string support
2399 */
2400#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002401
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002402static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002403{
2404 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002405 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002406 if (o->data)
2407 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002408}
2409
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002410static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002411{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002412 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002413 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002414}
2415
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002416static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2417{
2418 free(o->data);
2419}
2420
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002421static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002422{
2423 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002424 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002425 o->data = xrealloc(o->data, 1 + o->maxlen);
2426 }
2427}
2428
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002429static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002430{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002431 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002432 if (o->length < o->maxlen) {
2433 /* likely. avoid o_grow_by() call */
2434 add:
2435 o->data[o->length] = ch;
2436 o->length++;
2437 o->data[o->length] = '\0';
2438 return;
2439 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002440 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002441 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002442}
2443
Denys Vlasenko657086a2016-09-29 18:07:42 +02002444#if 0
2445/* Valid only if we know o_string is not empty */
2446static void o_delchr(o_string *o)
2447{
2448 o->length--;
2449 o->data[o->length] = '\0';
2450}
2451#endif
2452
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002453static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002454{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002455 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002456 memcpy(&o->data[o->length], str, len);
2457 o->length += len;
2458 o->data[o->length] = '\0';
2459}
2460
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002461static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002462{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002463 o_addblock(o, str, strlen(str));
2464}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002465
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002466#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002467static void nommu_addchr(o_string *o, int ch)
2468{
2469 if (o)
2470 o_addchr(o, ch);
2471}
2472#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002473# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002474#endif
2475
2476static void o_addstr_with_NUL(o_string *o, const char *str)
2477{
2478 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002479}
2480
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002481/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002482 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002483 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2484 * Apparently, on unquoted $v bash still does globbing
2485 * ("v='*.txt'; echo $v" prints all .txt files),
2486 * but NOT brace expansion! Thus, there should be TWO independent
2487 * quoting mechanisms on $v expansion side: one protects
2488 * $v from brace expansion, and other additionally protects "$v" against globbing.
2489 * We have only second one.
2490 */
2491
Denys Vlasenko9e800222010-10-03 14:28:04 +02002492#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002493# define MAYBE_BRACES "{}"
2494#else
2495# define MAYBE_BRACES ""
2496#endif
2497
Eric Andersen25f27032001-04-26 23:22:31 +00002498/* My analysis of quoting semantics tells me that state information
2499 * is associated with a destination, not a source.
2500 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002501static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002502{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002503 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002504 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002505 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002506 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002507 o_grow_by(o, sz);
2508 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002509 o->data[o->length] = '\\';
2510 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002511 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002512 o->data[o->length] = ch;
2513 o->length++;
2514 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002515}
2516
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002517static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002518{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002519 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002520 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2521 && strchr("*?[\\" MAYBE_BRACES, ch)
2522 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002523 sz++;
2524 o->data[o->length] = '\\';
2525 o->length++;
2526 }
2527 o_grow_by(o, sz);
2528 o->data[o->length] = ch;
2529 o->length++;
2530 o->data[o->length] = '\0';
2531}
2532
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002533static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002534{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002535 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002536 char ch;
2537 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002538 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002539 if (ordinary_cnt > len) /* paranoia */
2540 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002541 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002542 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002543 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002544 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002545 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002546
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002547 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002548 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002549 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002550 sz++;
2551 o->data[o->length] = '\\';
2552 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002553 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002554 o_grow_by(o, sz);
2555 o->data[o->length] = ch;
2556 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002557 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002558 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002559}
2560
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002561static void o_addQblock(o_string *o, const char *str, int len)
2562{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002563 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002564 o_addblock(o, str, len);
2565 return;
2566 }
2567 o_addqblock(o, str, len);
2568}
2569
Denys Vlasenko38292b62010-09-05 14:49:40 +02002570static void o_addQstr(o_string *o, const char *str)
2571{
2572 o_addQblock(o, str, strlen(str));
2573}
2574
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002575/* A special kind of o_string for $VAR and `cmd` expansion.
2576 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002577 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002578 * list[i] contains an INDEX (int!) into this string data.
2579 * It means that if list[] needs to grow, data needs to be moved higher up
2580 * but list[i]'s need not be modified.
2581 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002582 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002583 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2584 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002585#if DEBUG_EXPAND || DEBUG_GLOB
2586static void debug_print_list(const char *prefix, o_string *o, int n)
2587{
2588 char **list = (char**)o->data;
2589 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2590 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002591
2592 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002593 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 +02002594 prefix, list, n, string_start, o->length, o->maxlen,
2595 !!(o->o_expflags & EXP_FLAG_GLOB),
2596 o->has_quoted_part,
2597 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002598 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002599 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002600 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2601 o->data + (int)(uintptr_t)list[i] + string_start,
2602 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002603 i++;
2604 }
2605 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002606 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002607 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002608 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002609 }
2610}
2611#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002612# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002613#endif
2614
2615/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2616 * in list[n] so that it points past last stored byte so far.
2617 * It returns n+1. */
2618static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002619{
2620 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002621 int string_start;
2622 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002623
2624 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002625 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2626 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002627 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002628 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002629 /* list[n] points to string_start, make space for 16 more pointers */
2630 o->maxlen += 0x10 * sizeof(list[0]);
2631 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002632 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002633 memmove(list + n + 0x10, list + n, string_len);
2634 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002635 } else {
2636 debug_printf_list("list[%d]=%d string_start=%d\n",
2637 n, string_len, string_start);
2638 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002639 } else {
2640 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002641 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2642 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002643 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2644 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002645 o->has_empty_slot = 0;
2646 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002647 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002648 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002649 return n + 1;
2650}
2651
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002652/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002653static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002654{
2655 char **list = (char**)o->data;
2656 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2657
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002658 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002659}
2660
Denys Vlasenko9e800222010-10-03 14:28:04 +02002661#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002662/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2663 * first, it processes even {a} (no commas), second,
2664 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002665 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002666 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002667
2668/* Helper */
2669static int glob_needed(const char *s)
2670{
2671 while (*s) {
2672 if (*s == '\\') {
2673 if (!s[1])
2674 return 0;
2675 s += 2;
2676 continue;
2677 }
2678 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2679 return 1;
2680 s++;
2681 }
2682 return 0;
2683}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002684/* Return pointer to next closing brace or to comma */
2685static const char *next_brace_sub(const char *cp)
2686{
2687 unsigned depth = 0;
2688 cp++;
2689 while (*cp != '\0') {
2690 if (*cp == '\\') {
2691 if (*++cp == '\0')
2692 break;
2693 cp++;
2694 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002695 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002696 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002697 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002698 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002699 depth++;
2700 }
2701
2702 return *cp != '\0' ? cp : NULL;
2703}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002704/* Recursive brace globber. Note: may garble pattern[]. */
2705static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002706{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002707 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002708 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002709 const char *next;
2710 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002711 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002712 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002713
2714 debug_printf_glob("glob_brace('%s')\n", pattern);
2715
2716 begin = pattern;
2717 while (1) {
2718 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002719 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002720 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002721 /* Find the first sub-pattern and at the same time
2722 * find the rest after the closing brace */
2723 next = next_brace_sub(begin);
2724 if (next == NULL) {
2725 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002726 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002727 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002728 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002729 /* "{abc}" with no commas - illegal
2730 * brace expr, disregard and skip it */
2731 begin = next + 1;
2732 continue;
2733 }
2734 break;
2735 }
2736 if (*begin == '\\' && begin[1] != '\0')
2737 begin++;
2738 begin++;
2739 }
2740 debug_printf_glob("begin:%s\n", begin);
2741 debug_printf_glob("next:%s\n", next);
2742
2743 /* Now find the end of the whole brace expression */
2744 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002745 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002746 rest = next_brace_sub(rest);
2747 if (rest == NULL) {
2748 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002749 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002750 }
2751 debug_printf_glob("rest:%s\n", rest);
2752 }
2753 rest_len = strlen(++rest) + 1;
2754
2755 /* We are sure the brace expression is well-formed */
2756
2757 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002758 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002759
2760 /* We have a brace expression. BEGIN points to the opening {,
2761 * NEXT points past the terminator of the first element, and REST
2762 * points past the final }. We will accumulate result names from
2763 * recursive runs for each brace alternative in the buffer using
2764 * GLOB_APPEND. */
2765
2766 p = begin + 1;
2767 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002768 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002769 memcpy(
2770 mempcpy(
2771 mempcpy(new_pattern_buf,
2772 /* We know the prefix for all sub-patterns */
2773 pattern, begin - pattern),
2774 p, next - p),
2775 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002776
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002777 /* Note: glob_brace() may garble new_pattern_buf[].
2778 * That's why we re-copy prefix every time (1st memcpy above).
2779 */
2780 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002781 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002782 /* We saw the last entry */
2783 break;
2784 }
2785 p = next + 1;
2786 next = next_brace_sub(next);
2787 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002788 free(new_pattern_buf);
2789 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002790
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002791 simple_glob:
2792 {
2793 int gr;
2794 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002795
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002796 memset(&globdata, 0, sizeof(globdata));
2797 gr = glob(pattern, 0, NULL, &globdata);
2798 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2799 if (gr != 0) {
2800 if (gr == GLOB_NOMATCH) {
2801 globfree(&globdata);
2802 /* NB: garbles parameter */
2803 unbackslash(pattern);
2804 o_addstr_with_NUL(o, pattern);
2805 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2806 return o_save_ptr_helper(o, n);
2807 }
2808 if (gr == GLOB_NOSPACE)
2809 bb_error_msg_and_die(bb_msg_memory_exhausted);
2810 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2811 * but we didn't specify it. Paranoia again. */
2812 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2813 }
2814 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2815 char **argv = globdata.gl_pathv;
2816 while (1) {
2817 o_addstr_with_NUL(o, *argv);
2818 n = o_save_ptr_helper(o, n);
2819 argv++;
2820 if (!*argv)
2821 break;
2822 }
2823 }
2824 globfree(&globdata);
2825 }
2826 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002827}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002828/* Performs globbing on last list[],
2829 * saving each result as a new list[].
2830 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002831static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002832{
2833 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002834
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002835 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002836 if (!o->data)
2837 return o_save_ptr_helper(o, n);
2838 pattern = o->data + o_get_last_ptr(o, n);
2839 debug_printf_glob("glob pattern '%s'\n", pattern);
2840 if (!glob_needed(pattern)) {
2841 /* unbackslash last string in o in place, fix length */
2842 o->length = unbackslash(pattern) - o->data;
2843 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2844 return o_save_ptr_helper(o, n);
2845 }
2846
2847 copy = xstrdup(pattern);
2848 /* "forget" pattern in o */
2849 o->length = pattern - o->data;
2850 n = glob_brace(copy, o, n);
2851 free(copy);
2852 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002853 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002854 return n;
2855}
2856
Denys Vlasenko238081f2010-10-03 14:26:26 +02002857#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002858
2859/* Helper */
2860static int glob_needed(const char *s)
2861{
2862 while (*s) {
2863 if (*s == '\\') {
2864 if (!s[1])
2865 return 0;
2866 s += 2;
2867 continue;
2868 }
2869 if (*s == '*' || *s == '[' || *s == '?')
2870 return 1;
2871 s++;
2872 }
2873 return 0;
2874}
2875/* Performs globbing on last list[],
2876 * saving each result as a new list[].
2877 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002878static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002879{
2880 glob_t globdata;
2881 int gr;
2882 char *pattern;
2883
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002884 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002885 if (!o->data)
2886 return o_save_ptr_helper(o, n);
2887 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002888 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002889 if (!glob_needed(pattern)) {
2890 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002891 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002892 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002893 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002894 return o_save_ptr_helper(o, n);
2895 }
2896
2897 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002898 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2899 * If we glob "*.\*" and don't find anything, we need
2900 * to fall back to using literal "*.*", but GLOB_NOCHECK
2901 * will return "*.\*"!
2902 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002903 gr = glob(pattern, 0, NULL, &globdata);
2904 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002905 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002906 if (gr == GLOB_NOMATCH) {
2907 globfree(&globdata);
2908 goto literal;
2909 }
2910 if (gr == GLOB_NOSPACE)
2911 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002912 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2913 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002914 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002915 }
2916 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2917 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002918 /* "forget" pattern in o */
2919 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002920 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002921 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002922 n = o_save_ptr_helper(o, n);
2923 argv++;
2924 if (!*argv)
2925 break;
2926 }
2927 }
2928 globfree(&globdata);
2929 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002930 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002931 return n;
2932}
2933
Denys Vlasenko238081f2010-10-03 14:26:26 +02002934#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002935
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002936/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002937 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002938static int o_save_ptr(o_string *o, int n)
2939{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002940 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002941 /* If o->has_empty_slot, list[n] was already globbed
2942 * (if it was requested back then when it was filled)
2943 * so don't do that again! */
2944 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002945 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002946 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002947 return o_save_ptr_helper(o, n);
2948}
2949
2950/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002951static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002952{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002953 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002954 int string_start;
2955
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002956 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2957 if (DEBUG_EXPAND)
2958 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002959 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002960 list = (char**)o->data;
2961 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2962 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002963 while (n) {
2964 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002965 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002966 }
2967 return list;
2968}
2969
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002970static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002971
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002972/* Returns pi->next - next pipe in the list */
2973static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002974{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002975 struct pipe *next;
2976 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002977
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002978 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002979 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002980 struct command *command;
2981 struct redir_struct *r, *rnext;
2982
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002983 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002984 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002985 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002986 if (DEBUG_CLEAN) {
2987 int a;
2988 char **p;
2989 for (a = 0, p = command->argv; *p; a++, p++) {
2990 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2991 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002992 }
2993 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002994 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002995 }
2996 /* not "else if": on syntax error, we may have both! */
2997 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002998 debug_printf_clean(" begin group (cmd_type:%d)\n",
2999 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003000 free_pipe_list(command->group);
3001 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003002 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003003 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003004 /* else is crucial here.
3005 * If group != NULL, child_func is meaningless */
3006#if ENABLE_HUSH_FUNCTIONS
3007 else if (command->child_func) {
3008 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3009 command->child_func->parent_cmd = NULL;
3010 }
3011#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003012#if !BB_MMU
3013 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003014 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003015#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003016 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003017 debug_printf_clean(" redirect %d%s",
3018 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003019 /* guard against the case >$FOO, where foo is unset or blank */
3020 if (r->rd_filename) {
3021 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3022 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003023 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003024 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003025 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003026 rnext = r->next;
3027 free(r);
3028 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003029 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003030 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003031 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003032 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003033#if ENABLE_HUSH_JOB
3034 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003035 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003036#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003037
3038 next = pi->next;
3039 free(pi);
3040 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003041}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003042
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003043static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003044{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003045 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003046#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003047 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003048#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003049 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003050 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003051 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003052}
3053
3054
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003055/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003056
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003057#ifndef debug_print_tree
3058static void debug_print_tree(struct pipe *pi, int lvl)
3059{
3060 static const char *const PIPE[] = {
3061 [PIPE_SEQ] = "SEQ",
3062 [PIPE_AND] = "AND",
3063 [PIPE_OR ] = "OR" ,
3064 [PIPE_BG ] = "BG" ,
3065 };
3066 static const char *RES[] = {
3067 [RES_NONE ] = "NONE" ,
3068# if ENABLE_HUSH_IF
3069 [RES_IF ] = "IF" ,
3070 [RES_THEN ] = "THEN" ,
3071 [RES_ELIF ] = "ELIF" ,
3072 [RES_ELSE ] = "ELSE" ,
3073 [RES_FI ] = "FI" ,
3074# endif
3075# if ENABLE_HUSH_LOOPS
3076 [RES_FOR ] = "FOR" ,
3077 [RES_WHILE] = "WHILE",
3078 [RES_UNTIL] = "UNTIL",
3079 [RES_DO ] = "DO" ,
3080 [RES_DONE ] = "DONE" ,
3081# endif
3082# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3083 [RES_IN ] = "IN" ,
3084# endif
3085# if ENABLE_HUSH_CASE
3086 [RES_CASE ] = "CASE" ,
3087 [RES_CASE_IN ] = "CASE_IN" ,
3088 [RES_MATCH] = "MATCH",
3089 [RES_CASE_BODY] = "CASE_BODY",
3090 [RES_ESAC ] = "ESAC" ,
3091# endif
3092 [RES_XXXX ] = "XXXX" ,
3093 [RES_SNTX ] = "SNTX" ,
3094 };
3095 static const char *const CMDTYPE[] = {
3096 "{}",
3097 "()",
3098 "[noglob]",
3099# if ENABLE_HUSH_FUNCTIONS
3100 "func()",
3101# endif
3102 };
3103
3104 int pin, prn;
3105
3106 pin = 0;
3107 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003108 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003109 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3110 prn = 0;
3111 while (prn < pi->num_cmds) {
3112 struct command *command = &pi->cmds[prn];
3113 char **argv = command->argv;
3114
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003115 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003116 lvl*2, "", prn,
3117 command->assignment_cnt);
3118 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003119 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003120 CMDTYPE[command->cmd_type],
3121 argv
3122# if !BB_MMU
3123 , " group_as_string:", command->group_as_string
3124# else
3125 , "", ""
3126# endif
3127 );
3128 debug_print_tree(command->group, lvl+1);
3129 prn++;
3130 continue;
3131 }
3132 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003133 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003134 argv++;
3135 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003136 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003137 prn++;
3138 }
3139 pi = pi->next;
3140 pin++;
3141 }
3142}
3143#endif /* debug_print_tree */
3144
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003145static struct pipe *new_pipe(void)
3146{
Eric Andersen25f27032001-04-26 23:22:31 +00003147 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003148 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003149 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003150 return pi;
3151}
3152
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003153/* Command (member of a pipe) is complete, or we start a new pipe
3154 * if ctx->command is NULL.
3155 * No errors possible here.
3156 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003157static int done_command(struct parse_context *ctx)
3158{
3159 /* The command is really already in the pipe structure, so
3160 * advance the pipe counter and make a new, null command. */
3161 struct pipe *pi = ctx->pipe;
3162 struct command *command = ctx->command;
3163
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003164#if 0 /* Instead we emit error message at run time */
3165 if (ctx->pending_redirect) {
3166 /* For example, "cmd >" (no filename to redirect to) */
3167 die_if_script("syntax error: %s", "invalid redirect");
3168 ctx->pending_redirect = NULL;
3169 }
3170#endif
3171
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003172 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003173 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003174 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003175 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003176 }
3177 pi->num_cmds++;
3178 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003179 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003180 } else {
3181 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3182 }
3183
3184 /* Only real trickiness here is that the uncommitted
3185 * command structure is not counted in pi->num_cmds. */
3186 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003187 ctx->command = command = &pi->cmds[pi->num_cmds];
3188 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003189 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003190 return pi->num_cmds; /* used only for 0/nonzero check */
3191}
3192
3193static void done_pipe(struct parse_context *ctx, pipe_style type)
3194{
3195 int not_null;
3196
3197 debug_printf_parse("done_pipe entered, followup %d\n", type);
3198 /* Close previous command */
3199 not_null = done_command(ctx);
3200 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003201#if HAS_KEYWORDS
3202 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3203 ctx->ctx_inverted = 0;
3204 ctx->pipe->res_word = ctx->ctx_res_w;
3205#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003206
3207 /* Without this check, even just <enter> on command line generates
3208 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003209 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003210 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003211#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003212 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003213#endif
3214#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003215 || ctx->ctx_res_w == RES_DONE
3216 || ctx->ctx_res_w == RES_FOR
3217 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003218#endif
3219#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003220 || ctx->ctx_res_w == RES_ESAC
3221#endif
3222 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003223 struct pipe *new_p;
3224 debug_printf_parse("done_pipe: adding new pipe: "
3225 "not_null:%d ctx->ctx_res_w:%d\n",
3226 not_null, ctx->ctx_res_w);
3227 new_p = new_pipe();
3228 ctx->pipe->next = new_p;
3229 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003230 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003231 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003232 * This is used to control execution.
3233 * RES_FOR and RES_IN are NOT sticky (needed to support
3234 * cases where variable or value happens to match a keyword):
3235 */
3236#if ENABLE_HUSH_LOOPS
3237 if (ctx->ctx_res_w == RES_FOR
3238 || ctx->ctx_res_w == RES_IN)
3239 ctx->ctx_res_w = RES_NONE;
3240#endif
3241#if ENABLE_HUSH_CASE
3242 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003243 ctx->ctx_res_w = RES_CASE_BODY;
3244 if (ctx->ctx_res_w == RES_CASE)
3245 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003246#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003247 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003248 /* Create the memory for command, roughly:
3249 * ctx->pipe->cmds = new struct command;
3250 * ctx->command = &ctx->pipe->cmds[0];
3251 */
3252 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003253 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003254 }
3255 debug_printf_parse("done_pipe return\n");
3256}
3257
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003258static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003259{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003260 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003261 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003262 /* Create the memory for command, roughly:
3263 * ctx->pipe->cmds = new struct command;
3264 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003265 */
3266 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003267}
3268
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003269/* If a reserved word is found and processed, parse context is modified
3270 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003271 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003272#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003273struct reserved_combo {
3274 char literal[6];
3275 unsigned char res;
3276 unsigned char assignment_flag;
3277 int flag;
3278};
3279enum {
3280 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003281# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003282 FLAG_IF = (1 << RES_IF ),
3283 FLAG_THEN = (1 << RES_THEN ),
3284 FLAG_ELIF = (1 << RES_ELIF ),
3285 FLAG_ELSE = (1 << RES_ELSE ),
3286 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003287# endif
3288# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003289 FLAG_FOR = (1 << RES_FOR ),
3290 FLAG_WHILE = (1 << RES_WHILE),
3291 FLAG_UNTIL = (1 << RES_UNTIL),
3292 FLAG_DO = (1 << RES_DO ),
3293 FLAG_DONE = (1 << RES_DONE ),
3294 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003295# endif
3296# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003297 FLAG_MATCH = (1 << RES_MATCH),
3298 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003299# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003300 FLAG_START = (1 << RES_XXXX ),
3301};
3302
3303static const struct reserved_combo* match_reserved_word(o_string *word)
3304{
Eric Andersen25f27032001-04-26 23:22:31 +00003305 /* Mostly a list of accepted follow-up reserved words.
3306 * FLAG_END means we are done with the sequence, and are ready
3307 * to turn the compound list into a command.
3308 * FLAG_START means the word must start a new compound list.
3309 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003310 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003311# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003312 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3313 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3314 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3315 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3316 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3317 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003318# endif
3319# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003320 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3321 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3322 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3323 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3324 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3325 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003326# endif
3327# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003328 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3329 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003330# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003331 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003332 const struct reserved_combo *r;
3333
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003334 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003335 if (strcmp(word->data, r->literal) == 0)
3336 return r;
3337 }
3338 return NULL;
3339}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003340/* Return 0: not a keyword, 1: keyword
3341 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003342static int reserved_word(o_string *word, struct parse_context *ctx)
3343{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003344# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003345 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003346 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003347 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003348# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003349 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003350
Denys Vlasenko38292b62010-09-05 14:49:40 +02003351 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003352 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003353 r = match_reserved_word(word);
3354 if (!r)
3355 return 0;
3356
3357 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003358# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003359 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3360 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003361 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003362 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003363# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003364 if (r->flag == 0) { /* '!' */
3365 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003366 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003367 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003368 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003369 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003370 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003371 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003372 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003373 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003374
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003375 old = xmalloc(sizeof(*old));
3376 debug_printf_parse("push stack %p\n", old);
3377 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003378 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003379 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003380 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003381 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003382 ctx->ctx_res_w = RES_SNTX;
3383 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003384 } else {
3385 /* "{...} fi" is ok. "{...} if" is not
3386 * Example:
3387 * if { echo foo; } then { echo bar; } fi */
3388 if (ctx->command->group)
3389 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003390 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003391
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003392 ctx->ctx_res_w = r->res;
3393 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003394 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003395 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003396
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003397 if (ctx->old_flag & FLAG_END) {
3398 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003399
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003400 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003401 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003402 old = ctx->stack;
3403 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003404 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003405# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003406 /* At this point, the compound command's string is in
3407 * ctx->as_string... except for the leading keyword!
3408 * Consider this example: "echo a | if true; then echo a; fi"
3409 * ctx->as_string will contain "true; then echo a; fi",
3410 * with "if " remaining in old->as_string!
3411 */
3412 {
3413 char *str;
3414 int len = old->as_string.length;
3415 /* Concatenate halves */
3416 o_addstr(&old->as_string, ctx->as_string.data);
3417 o_free_unsafe(&ctx->as_string);
3418 /* Find where leading keyword starts in first half */
3419 str = old->as_string.data + len;
3420 if (str > old->as_string.data)
3421 str--; /* skip whitespace after keyword */
3422 while (str > old->as_string.data && isalpha(str[-1]))
3423 str--;
3424 /* Ugh, we're done with this horrid hack */
3425 old->command->group_as_string = xstrdup(str);
3426 debug_printf_parse("pop, remembering as:'%s'\n",
3427 old->command->group_as_string);
3428 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003429# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003430 *ctx = *old; /* physical copy */
3431 free(old);
3432 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003433 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003434}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003435#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003436
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003437/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003438 * Normal return is 0. Syntax errors return 1.
3439 * Note: on return, word is reset, but not o_free'd!
3440 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003441static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003442{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003443 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003444
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003445 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003446 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003447 debug_printf_parse("done_word return 0: true null, ignored\n");
3448 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003449 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003450
Eric Andersen25f27032001-04-26 23:22:31 +00003451 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003452 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3453 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003454 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3455 * "2.7 Redirection
3456 * ...the word that follows the redirection operator
3457 * shall be subjected to tilde expansion, parameter expansion,
3458 * command substitution, arithmetic expansion, and quote
3459 * removal. Pathname expansion shall not be performed
3460 * on the word by a non-interactive shell; an interactive
3461 * shell may perform it, but shall do so only when
3462 * the expansion would result in one word."
3463 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003464 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003465 /* Cater for >\file case:
3466 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3467 * Same with heredocs:
3468 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3469 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003470 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3471 unbackslash(ctx->pending_redirect->rd_filename);
3472 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003473 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003474 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3475 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003476 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003477 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003478 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003479 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003480#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003481# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003482 if (ctx->ctx_dsemicolon
3483 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3484 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003485 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003486 /* ctx->ctx_res_w = RES_MATCH; */
3487 ctx->ctx_dsemicolon = 0;
3488 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003489# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003490 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003491# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003492 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3493 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003494# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003495# if ENABLE_HUSH_CASE
3496 && ctx->ctx_res_w != RES_CASE
3497# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003498 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003499 int reserved = reserved_word(word, ctx);
3500 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3501 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003502 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003503 debug_printf_parse("done_word return %d\n",
3504 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003505 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003506 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003507# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003508 if (strcmp(word->data, "[[") == 0) {
3509 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3510 }
3511 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003512# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003513 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003514#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003515 if (command->group) {
3516 /* "{ echo foo; } echo bar" - bad */
3517 syntax_error_at(word->data);
3518 debug_printf_parse("done_word return 1: syntax error, "
3519 "groups and arglists don't mix\n");
3520 return 1;
3521 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003522
3523 /* If this word wasn't an assignment, next ones definitely
3524 * can't be assignments. Even if they look like ones. */
3525 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3526 && word->o_assignment != WORD_IS_KEYWORD
3527 ) {
3528 word->o_assignment = NOT_ASSIGNMENT;
3529 } else {
3530 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3531 command->assignment_cnt++;
3532 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3533 }
3534 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3535 word->o_assignment = MAYBE_ASSIGNMENT;
3536 }
3537 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3538
Denys Vlasenko38292b62010-09-05 14:49:40 +02003539 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003540 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3541 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003542 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003543 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003544 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003545 char *p = word->data;
3546 while (p[0] == SPECIAL_VAR_SYMBOL
3547 && (p[1] & 0x7f) == '@'
3548 && p[2] == SPECIAL_VAR_SYMBOL
3549 ) {
3550 p += 3;
3551 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003552 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003553 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003554 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003555 }
Eric Andersen25f27032001-04-26 23:22:31 +00003556
Denis Vlasenko06810332007-05-21 23:30:54 +00003557#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003558 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003559 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003560 || !is_well_formed_var_name(command->argv[0], '\0')
3561 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003562 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003563 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003564 return 1;
3565 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003566 /* Force FOR to have just one word (variable name) */
3567 /* NB: basically, this makes hush see "for v in ..."
3568 * syntax as if it is "for v; in ...". FOR and IN become
3569 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003570 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003571 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003572#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003573#if ENABLE_HUSH_CASE
3574 /* Force CASE to have just one word */
3575 if (ctx->ctx_res_w == RES_CASE) {
3576 done_pipe(ctx, PIPE_SEQ);
3577 }
3578#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003579
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003580 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003581
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003582 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003583 return 0;
3584}
3585
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003586
3587/* Peek ahead in the input to find out if we have a "&n" construct,
3588 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003589 * Return:
3590 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3591 * REDIRFD_SYNTAX_ERR if syntax error,
3592 * REDIRFD_TO_FILE if no & was seen,
3593 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003594 */
3595#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003596#define parse_redir_right_fd(as_string, input) \
3597 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003598#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003599static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003600{
3601 int ch, d, ok;
3602
3603 ch = i_peek(input);
3604 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003605 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003606
3607 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003608 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003609 ch = i_peek(input);
3610 if (ch == '-') {
3611 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003612 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003613 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003614 }
3615 d = 0;
3616 ok = 0;
3617 while (ch != EOF && isdigit(ch)) {
3618 d = d*10 + (ch-'0');
3619 ok = 1;
3620 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003621 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003622 ch = i_peek(input);
3623 }
3624 if (ok) return d;
3625
3626//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3627
3628 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003629 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003630}
3631
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003632/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003633 */
3634static int parse_redirect(struct parse_context *ctx,
3635 int fd,
3636 redir_type style,
3637 struct in_str *input)
3638{
3639 struct command *command = ctx->command;
3640 struct redir_struct *redir;
3641 struct redir_struct **redirp;
3642 int dup_num;
3643
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003644 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003645 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003646 /* Check for a '>&1' type redirect */
3647 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3648 if (dup_num == REDIRFD_SYNTAX_ERR)
3649 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003650 } else {
3651 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003652 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003653 if (dup_num) { /* <<-... */
3654 ch = i_getch(input);
3655 nommu_addchr(&ctx->as_string, ch);
3656 ch = i_peek(input);
3657 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003658 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003659
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003660 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003661 int ch = i_peek(input);
3662 if (ch == '|') {
3663 /* >|FILE redirect ("clobbering" >).
3664 * Since we do not support "set -o noclobber" yet,
3665 * >| and > are the same for now. Just eat |.
3666 */
3667 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003668 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003669 }
3670 }
3671
3672 /* Create a new redir_struct and append it to the linked list */
3673 redirp = &command->redirects;
3674 while ((redir = *redirp) != NULL) {
3675 redirp = &(redir->next);
3676 }
3677 *redirp = redir = xzalloc(sizeof(*redir));
3678 /* redir->next = NULL; */
3679 /* redir->rd_filename = NULL; */
3680 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003681 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003682
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003683 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3684 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003685
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003686 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003687 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003688 /* Erik had a check here that the file descriptor in question
3689 * is legit; I postpone that to "run time"
3690 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003691 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3692 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003693 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003694#if 0 /* Instead we emit error message at run time */
3695 if (ctx->pending_redirect) {
3696 /* For example, "cmd > <file" */
3697 die_if_script("syntax error: %s", "invalid redirect");
3698 }
3699#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003700 /* Set ctx->pending_redirect, so we know what to do at the
3701 * end of the next parsed word. */
3702 ctx->pending_redirect = redir;
3703 }
3704 return 0;
3705}
3706
Eric Andersen25f27032001-04-26 23:22:31 +00003707/* If a redirect is immediately preceded by a number, that number is
3708 * supposed to tell which file descriptor to redirect. This routine
3709 * looks for such preceding numbers. In an ideal world this routine
3710 * needs to handle all the following classes of redirects...
3711 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3712 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3713 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3714 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003715 *
3716 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3717 * "2.7 Redirection
3718 * ... If n is quoted, the number shall not be recognized as part of
3719 * the redirection expression. For example:
3720 * echo \2>a
3721 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003722 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003723 *
3724 * A -1 return means no valid number was found,
3725 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003726 */
3727static int redirect_opt_num(o_string *o)
3728{
3729 int num;
3730
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003731 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003732 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003733 num = bb_strtou(o->data, NULL, 10);
3734 if (errno || num < 0)
3735 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003736 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003737 return num;
3738}
3739
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003740#if BB_MMU
3741#define fetch_till_str(as_string, input, word, skip_tabs) \
3742 fetch_till_str(input, word, skip_tabs)
3743#endif
3744static char *fetch_till_str(o_string *as_string,
3745 struct in_str *input,
3746 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003747 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003748{
3749 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003750 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003751 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003752 int ch;
3753
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003754 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003755
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003756 while (1) {
3757 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003758 if (ch != EOF)
3759 nommu_addchr(as_string, ch);
3760 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003761 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3762 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003763 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3764 heredoc.data[past_EOL] = '\0';
3765 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3766 return heredoc.data;
3767 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003768 while (ch == '\n') {
3769 o_addchr(&heredoc, ch);
3770 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003771 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003772 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003773 do {
3774 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003775 if (ch != EOF)
3776 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003777 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003778 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003779 }
3780 if (ch == EOF) {
3781 o_free_unsafe(&heredoc);
3782 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003783 }
3784 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003785 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003786 if (prev == '\\' && ch == '\\')
3787 /* Correctly handle foo\\<eol> (not a line cont.) */
3788 prev = 0; /* not \ */
3789 else
3790 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003791 }
3792}
3793
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003794/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3795 * and load them all. There should be exactly heredoc_cnt of them.
3796 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003797static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3798{
3799 struct pipe *pi = ctx->list_head;
3800
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003801 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003802 int i;
3803 struct command *cmd = pi->cmds;
3804
3805 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3806 pi->num_cmds,
3807 cmd->argv ? cmd->argv[0] : "NONE");
3808 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003809 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003810
3811 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3812 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003813 while (redir) {
3814 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003815 char *p;
3816
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003817 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003818 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003819 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003820 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003821 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003822 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003823 return 1;
3824 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003825 free(redir->rd_filename);
3826 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003827 heredoc_cnt--;
3828 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003829 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003830 }
3831 cmd++;
3832 }
3833 pi = pi->next;
3834 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003835#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003836 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003837 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003838 bb_error_msg_and_die("heredoc BUG 2");
3839#endif
3840 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003841}
3842
3843
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003844static int run_list(struct pipe *pi);
3845#if BB_MMU
3846#define parse_stream(pstring, input, end_trigger) \
3847 parse_stream(input, end_trigger)
3848#endif
3849static struct pipe *parse_stream(char **pstring,
3850 struct in_str *input,
3851 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003852
Eric Andersen25f27032001-04-26 23:22:31 +00003853
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003854#if !ENABLE_HUSH_FUNCTIONS
3855#define parse_group(dest, ctx, input, ch) \
3856 parse_group(ctx, input, ch)
3857#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003858static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003859 struct in_str *input, int ch)
3860{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003861 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003862 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003863 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003864 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003865 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003866 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003867
3868 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003869#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003870 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003871 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003872 if (done_word(dest, ctx))
3873 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003874 if (!command->argv)
3875 goto skip; /* (... */
3876 if (command->argv[1]) { /* word word ... (... */
3877 syntax_error_unexpected_ch('(');
3878 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003879 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003880 /* it is "word(..." or "word (..." */
3881 do
3882 ch = i_getch(input);
3883 while (ch == ' ' || ch == '\t');
3884 if (ch != ')') {
3885 syntax_error_unexpected_ch(ch);
3886 return 1;
3887 }
3888 nommu_addchr(&ctx->as_string, ch);
3889 do
3890 ch = i_getch(input);
3891 while (ch == ' ' || ch == '\t' || ch == '\n');
3892 if (ch != '{') {
3893 syntax_error_unexpected_ch(ch);
3894 return 1;
3895 }
3896 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003897 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003898 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003899 }
3900#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003901
3902#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003903 if (command->argv /* word [word]{... */
3904 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003905 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003906 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003907 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003908 debug_printf_parse("parse_group return 1: "
3909 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003910 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003911 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003912#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003913
3914#if ENABLE_HUSH_FUNCTIONS
3915 skip:
3916#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003917 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003918 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003919 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003920 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003921 } else {
3922 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01003923 ch = i_peek(input);
3924 if (ch != ' ' && ch != '\t' && ch != '\n'
3925 && ch != '(' /* but "{(..." is allowed (without whitespace) */
3926 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003927 syntax_error_unexpected_ch(ch);
3928 return 1;
3929 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01003930 if (ch != '(') {
3931 ch = i_getch(input);
3932 nommu_addchr(&ctx->as_string, ch);
3933 }
Eric Andersen25f27032001-04-26 23:22:31 +00003934 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003935
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003936 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003937#if BB_MMU
3938# define as_string NULL
3939#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003940 char *as_string = NULL;
3941#endif
3942 pipe_list = parse_stream(&as_string, input, endch);
3943#if !BB_MMU
3944 if (as_string)
3945 o_addstr(&ctx->as_string, as_string);
3946#endif
3947 /* empty ()/{} or parse error? */
3948 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003949 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003950 if (!BB_MMU)
3951 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003952 debug_printf_parse("parse_group return 1: "
3953 "parse_stream returned %p\n", pipe_list);
3954 return 1;
3955 }
3956 command->group = pipe_list;
3957#if !BB_MMU
3958 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3959 command->group_as_string = as_string;
3960 debug_printf_parse("end of group, remembering as:'%s'\n",
3961 command->group_as_string);
3962#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003963#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003964 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003965 debug_printf_parse("parse_group return 0\n");
3966 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003967 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003968}
3969
Denys Vlasenko46e64982016-09-29 19:50:55 +02003970static int i_getch_and_eat_bkslash_nl(struct in_str *input)
3971{
3972 for (;;) {
3973 int ch, ch2;
3974
3975 ch = i_getch(input);
3976 if (ch != '\\')
3977 return ch;
3978 ch2 = i_peek(input);
3979 if (ch2 != '\n')
3980 return ch;
3981 /* backslash+newline, skip it */
3982 i_getch(input);
3983 }
3984}
3985
Denys Vlasenko657086a2016-09-29 18:07:42 +02003986static int i_peek_and_eat_bkslash_nl(struct in_str *input)
3987{
3988 for (;;) {
3989 int ch, ch2;
3990
3991 ch = i_peek(input);
3992 if (ch != '\\')
3993 return ch;
3994 ch2 = i_peek2(input);
3995 if (ch2 != '\n')
3996 return ch;
3997 /* backslash+newline, skip it */
3998 i_getch(input);
3999 i_getch(input);
4000 }
4001}
4002
Denys Vlasenko0b883582016-12-23 16:49:07 +01004003#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004004/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004005static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004006/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004007static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004008{
4009 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004010 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004011 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004012 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004013 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004014 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004015 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004016 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004017 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004018 }
4019}
4020/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004021static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004022{
4023 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004024 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004025 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004026 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004027 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004028 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004029 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004030 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004031 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004032 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004033 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004034 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004035 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004036 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004037 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4038 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004039 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004040 continue;
4041 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004042 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004043 }
4044}
4045/* Process `cmd` - copy contents until "`" is seen. Complicated by
4046 * \` quoting.
4047 * "Within the backquoted style of command substitution, backslash
4048 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4049 * The search for the matching backquote shall be satisfied by the first
4050 * backquote found without a preceding backslash; during this search,
4051 * if a non-escaped backquote is encountered within a shell comment,
4052 * a here-document, an embedded command substitution of the $(command)
4053 * form, or a quoted string, undefined results occur. A single-quoted
4054 * or double-quoted string that begins, but does not end, within the
4055 * "`...`" sequence produces undefined results."
4056 * Example Output
4057 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4058 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004059static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004060{
4061 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004062 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004063 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004064 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004065 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004066 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4067 ch = i_getch(input);
4068 if (ch != '`'
4069 && ch != '$'
4070 && ch != '\\'
4071 && (!in_dquote || ch != '"')
4072 ) {
4073 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004074 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004075 }
4076 if (ch == EOF) {
4077 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004078 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004079 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004080 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004081 }
4082}
4083/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4084 * quoting and nested ()s.
4085 * "With the $(command) style of command substitution, all characters
4086 * following the open parenthesis to the matching closing parenthesis
4087 * constitute the command. Any valid shell script can be used for command,
4088 * except a script consisting solely of redirections which produces
4089 * unspecified results."
4090 * Example Output
4091 * echo $(echo '(TEST)' BEST) (TEST) BEST
4092 * echo $(echo 'TEST)' BEST) TEST) BEST
4093 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004094 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004095 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004096 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004097 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4098 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004099 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004100#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004101static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004102{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004103 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004104 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004105# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004106 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004107# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004108 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4109
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004110 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004111 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004112 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004113 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004114 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004115 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004116 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004117 if (!dbl)
4118 break;
4119 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004120 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004121 i_getch(input); /* eat second ')' */
4122 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004123 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004124 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004125 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004126 if (ch == '(' || ch == '{') {
4127 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004128 if (!add_till_closing_bracket(dest, input, ch))
4129 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004130 o_addchr(dest, ch);
4131 continue;
4132 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004133 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004134 if (!add_till_single_quote(dest, input))
4135 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004136 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004137 continue;
4138 }
4139 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004140 if (!add_till_double_quote(dest, input))
4141 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004142 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004143 continue;
4144 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004145 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004146 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4147 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004148 o_addchr(dest, ch);
4149 continue;
4150 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004151 if (ch == '\\') {
4152 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004153 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004154 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004155 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004156 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004157 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004158#if 0
4159 if (ch == '\n') {
4160 /* "backslash+newline", ignore both */
4161 o_delchr(dest); /* undo insertion of '\' */
4162 continue;
4163 }
4164#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004165 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004166 continue;
4167 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004168 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004169 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004170}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004171#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004172
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004173/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004174#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004175#define parse_dollar(as_string, dest, input, quote_mask) \
4176 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004177#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004178#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004179static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004180 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004181 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004182{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004183 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004184
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004185 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004186 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004187 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004188 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004189 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004190 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004191 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004192 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004193 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004194 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004195 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004196 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004197 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004198 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004199 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004200 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004201 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004202 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004203 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004204 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004205 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004206 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004207 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004208 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004209 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004210 o_addchr(dest, ch | quote_mask);
4211 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004212 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004213 case '$': /* pid */
4214 case '!': /* last bg pid */
4215 case '?': /* last exit code */
4216 case '#': /* number of args */
4217 case '*': /* args */
4218 case '@': /* args */
4219 goto make_one_char_var;
4220 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004221 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4222
Denys Vlasenko74369502010-05-21 19:52:01 +02004223 ch = i_getch(input); /* eat '{' */
4224 nommu_addchr(as_string, ch);
4225
Denys Vlasenko46e64982016-09-29 19:50:55 +02004226 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004227 /* It should be ${?}, or ${#var},
4228 * or even ${?+subst} - operator acting on a special variable,
4229 * or the beginning of variable name.
4230 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004231 if (ch == EOF
4232 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4233 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004234 bad_dollar_syntax:
4235 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004236 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4237 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004238 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004239 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004240 ch |= quote_mask;
4241
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004242 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004243 * However, this regresses some of our testsuite cases
4244 * which check invalid constructs like ${%}.
4245 * Oh well... let's check that the var name part is fine... */
4246
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004247 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004248 unsigned pos;
4249
Denys Vlasenko74369502010-05-21 19:52:01 +02004250 o_addchr(dest, ch);
4251 debug_printf_parse(": '%c'\n", ch);
4252
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004253 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004254 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004255 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004256 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004257
Denys Vlasenko74369502010-05-21 19:52:01 +02004258 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004259 unsigned end_ch;
4260 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004261 /* handle parameter expansions
4262 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4263 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004264 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02004265 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004266
4267 /* Eat everything until closing '}' (or ':') */
4268 end_ch = '}';
4269 if (ENABLE_HUSH_BASH_COMPAT
4270 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004271 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004272 ) {
4273 /* It's ${var:N[:M]} thing */
4274 end_ch = '}' * 0x100 + ':';
4275 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004276 if (ENABLE_HUSH_BASH_COMPAT
4277 && ch == '/'
4278 ) {
4279 /* It's ${var/[/]pattern[/repl]} thing */
4280 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4281 i_getch(input);
4282 nommu_addchr(as_string, '/');
4283 ch = '\\';
4284 }
4285 end_ch = '}' * 0x100 + '/';
4286 }
4287 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004288 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004289 if (!BB_MMU)
4290 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004291#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004292 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004293 if (last_ch == 0) /* error? */
4294 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004295#else
4296#error Simple code to only allow ${var} is not implemented
4297#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004298 if (as_string) {
4299 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004300 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004301 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004302
4303 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4304 /* close the first block: */
4305 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004306 /* while parsing N from ${var:N[:M]}
4307 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004308 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004309 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004310 end_ch = '}';
4311 goto again;
4312 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004313 /* got '}' */
4314 if (end_ch == '}' * 0x100 + ':') {
4315 /* it's ${var:N} - emulate :999999999 */
4316 o_addstr(dest, "999999999");
4317 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004318 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004319 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004320 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004321 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004322 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4323 break;
4324 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004325#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004326 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004327 unsigned pos;
4328
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004329 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004330 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004331# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004332 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004333 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004334 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004335 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4336 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004337 if (!BB_MMU)
4338 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004339 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4340 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004341 if (as_string) {
4342 o_addstr(as_string, dest->data + pos);
4343 o_addchr(as_string, ')');
4344 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004345 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004346 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004347 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004348 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004349# endif
4350# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004351 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4352 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004353 if (!BB_MMU)
4354 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004355 if (!add_till_closing_bracket(dest, input, ')'))
4356 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004357 if (as_string) {
4358 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004359 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004360 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004361 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004362# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004363 break;
4364 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004365#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004366 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004367 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004368 nommu_addchr(as_string, ch);
Denys Vlasenko657086a2016-09-29 18:07:42 +02004369 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004370 if (isalnum(ch)) { /* it's $_name or $_123 */
4371 ch = '_';
4372 goto make_var;
4373 }
4374 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004375 /* TODO: $_ and $-: */
4376 /* $_ Shell or shell script name; or last argument of last command
4377 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4378 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004379 /* $- Option flags set by set builtin or shell options (-i etc) */
4380 default:
4381 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004382 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004383 debug_printf_parse("parse_dollar return 1 (ok)\n");
4384 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004385#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004386}
4387
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004388#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004389# if ENABLE_HUSH_BASH_COMPAT
4390#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4391 encode_string(dest, input, dquote_end, process_bkslash)
4392# else
4393/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4394#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4395 encode_string(dest, input, dquote_end)
4396# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004397#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004398
4399#else /* !MMU */
4400
4401# if ENABLE_HUSH_BASH_COMPAT
4402/* all parameters are needed, no macro tricks */
4403# else
4404#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4405 encode_string(as_string, dest, input, dquote_end)
4406# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004407#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004408static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004409 o_string *dest,
4410 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004411 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004412 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004413{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004414#if !ENABLE_HUSH_BASH_COMPAT
4415 const int process_bkslash = 1;
4416#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004417 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004418 int next;
4419
4420 again:
4421 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004422 if (ch != EOF)
4423 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004424 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004425 debug_printf_parse("encode_string return 1 (ok)\n");
4426 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004427 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004428 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004429 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004430 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004431 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004432 }
4433 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004434 if (ch != '\n') {
4435 next = i_peek(input);
4436 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004437 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004438 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004439 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004440 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004441 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004442 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004443 }
4444 /* bash:
4445 * "The backslash retains its special meaning [in "..."]
4446 * only when followed by one of the following characters:
4447 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004448 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004449 * NB: in (unquoted) heredoc, above does not apply to ",
4450 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004451 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004452 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004453 ch = i_getch(input); /* eat next */
4454 if (ch == '\n')
4455 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004456 } /* else: ch remains == '\\', and we double it below: */
4457 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004458 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004459 goto again;
4460 }
4461 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004462 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4463 debug_printf_parse("encode_string return 0: "
4464 "parse_dollar returned 0 (error)\n");
4465 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004466 }
4467 goto again;
4468 }
4469#if ENABLE_HUSH_TICK
4470 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004471 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004472 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4473 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004474 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4475 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004476 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4477 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004478 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004479 }
4480#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004481 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004482 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004483#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004484}
4485
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004486/*
4487 * Scan input until EOF or end_trigger char.
4488 * Return a list of pipes to execute, or NULL on EOF
4489 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004490 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004491 * reset parsing machinery and start parsing anew,
4492 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004493 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004494static struct pipe *parse_stream(char **pstring,
4495 struct in_str *input,
4496 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004497{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004498 struct parse_context ctx;
4499 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004500 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004501
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004502 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004503 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004504 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004505 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004506 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004507 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004508
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004509 /* If very first arg is "" or '', dest.data may end up NULL.
4510 * Preventing this: */
4511 o_addchr(&dest, '\0');
4512 dest.length = 0;
4513
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004514 /* We used to separate words on $IFS here. This was wrong.
4515 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004516 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004517 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004518
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004519 if (MAYBE_ASSIGNMENT != 0)
4520 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004521 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004522 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004523 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004524 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004525 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004526 int ch;
4527 int next;
4528 int redir_fd;
4529 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004530
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004531 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004532 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004533 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004534 if (ch == EOF) {
4535 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004536
4537 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004538 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004539 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004540 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004541 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004542 syntax_error_unterm_ch('(');
4543 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004544 }
Denys Vlasenko42246472016-11-07 16:22:35 +01004545 if (end_trigger == '}') {
4546 syntax_error_unterm_ch('{');
4547 goto parse_error;
4548 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004549
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004550 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004551 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004552 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004553 o_free(&dest);
4554 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004555 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004556 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004557 /* (this makes bare "&" cmd a no-op.
4558 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004559 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004560 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004561 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004562 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004563 pi = NULL;
4564 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004565#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004566 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004567 if (pstring)
4568 *pstring = ctx.as_string.data;
4569 else
4570 o_free_unsafe(&ctx.as_string);
4571#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004572 debug_leave();
4573 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004574 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004575 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004576 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004577
4578 next = '\0';
4579 if (ch != '\n')
4580 next = i_peek(input);
4581
4582 is_special = "{}<>;&|()#'" /* special outside of "str" */
4583 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4584 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004585 if (ctx.command->argv /* word [word]{... - non-special */
4586 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004587 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004588 || (next != ';' /* }; - special */
4589 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004590 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004591 && next != '&' /* }& and }&& ... - special */
4592 && next != '|' /* }|| ... - special */
4593 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004594 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004595 ) {
4596 /* They are not special, skip "{}" */
4597 is_special += 2;
4598 }
4599 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004600 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004601
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004602 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004603 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004604 o_addQchr(&dest, ch);
4605 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4606 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004607 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004608 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004609 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004610 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004611 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004612 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004613 continue;
4614 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004615
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004616 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004617 if (done_word(&dest, &ctx)) {
4618 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004619 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004620 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004621 /* Is this a case when newline is simply ignored?
4622 * Some examples:
4623 * "cmd | <newline> cmd ..."
4624 * "case ... in <newline> word) ..."
4625 */
4626 if (IS_NULL_CMD(ctx.command)
4627 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004628 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004629 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004630 * Without check #1, interactive shell
4631 * ignores even bare <newline>,
4632 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004633 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004634 * ps2> _ <=== wrong, should be ps1
4635 * Without check #2, "cmd & <newline>"
4636 * is similarly mistreated.
4637 * (BTW, this makes "cmd & cmd"
4638 * and "cmd && cmd" non-orthogonal.
4639 * Really, ask yourself, why
4640 * "cmd && <newline>" doesn't start
4641 * cmd but waits for more input?
4642 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004643 */
4644 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004645 if (pi->num_cmds != 0 /* check #1 */
4646 && pi->followup != PIPE_BG /* check #2 */
4647 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004648 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004649 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004650 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004651 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004652 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004653 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4654 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004655 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004656 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004657 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004658 heredoc_cnt = 0;
4659 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004660 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004661 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004662 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004663 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004664 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004665 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004666 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004667
4668 /* "cmd}" or "cmd }..." without semicolon or &:
4669 * } is an ordinary char in this case, even inside { cmd; }
4670 * Pathological example: { ""}; } should exec "}" cmd
4671 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004672 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004673 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004674 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004675 ) {
4676 goto ordinary_char;
4677 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004678 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4679 /* Generally, there should be semicolon: "cmd; }"
4680 * However, bash allows to omit it if "cmd" is
4681 * a group. Examples:
4682 * { { echo 1; } }
4683 * {(echo 1)}
4684 * { echo 0 >&2 | { echo 1; } }
4685 * { while false; do :; done }
4686 * { case a in b) ;; esac }
4687 */
4688 if (ctx.command->group)
4689 goto term_group;
4690 goto ordinary_char;
4691 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004692 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004693 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004694 goto skip_end_trigger;
4695 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004696 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004697 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004698 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004699 && (ch != ';' || heredoc_cnt == 0)
4700#if ENABLE_HUSH_CASE
4701 && (ch != ')'
4702 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004703 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004704 )
4705#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004706 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004707 if (heredoc_cnt) {
4708 /* This is technically valid:
4709 * { cat <<HERE; }; echo Ok
4710 * heredoc
4711 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004712 * HERE
4713 * but we don't support this.
4714 * We require heredoc to be in enclosing {}/(),
4715 * if any.
4716 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004717 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004718 goto parse_error;
4719 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004720 if (done_word(&dest, &ctx)) {
4721 goto parse_error;
4722 }
4723 done_pipe(&ctx, PIPE_SEQ);
4724 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004725 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004726 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004727 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004728 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004729 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004730 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004731#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004732 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004733 if (pstring)
4734 *pstring = ctx.as_string.data;
4735 else
4736 o_free_unsafe(&ctx.as_string);
4737#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004738 debug_leave();
4739 debug_printf_parse("parse_stream return %p: "
4740 "end_trigger char found\n",
4741 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004742 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004743 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004744 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004745 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004746 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004747 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004748
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004749 /* Catch <, > before deciding whether this word is
4750 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4751 switch (ch) {
4752 case '>':
4753 redir_fd = redirect_opt_num(&dest);
4754 if (done_word(&dest, &ctx)) {
4755 goto parse_error;
4756 }
4757 redir_style = REDIRECT_OVERWRITE;
4758 if (next == '>') {
4759 redir_style = REDIRECT_APPEND;
4760 ch = i_getch(input);
4761 nommu_addchr(&ctx.as_string, ch);
4762 }
4763#if 0
4764 else if (next == '(') {
4765 syntax_error(">(process) not supported");
4766 goto parse_error;
4767 }
4768#endif
4769 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4770 goto parse_error;
4771 continue; /* back to top of while (1) */
4772 case '<':
4773 redir_fd = redirect_opt_num(&dest);
4774 if (done_word(&dest, &ctx)) {
4775 goto parse_error;
4776 }
4777 redir_style = REDIRECT_INPUT;
4778 if (next == '<') {
4779 redir_style = REDIRECT_HEREDOC;
4780 heredoc_cnt++;
4781 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4782 ch = i_getch(input);
4783 nommu_addchr(&ctx.as_string, ch);
4784 } else if (next == '>') {
4785 redir_style = REDIRECT_IO;
4786 ch = i_getch(input);
4787 nommu_addchr(&ctx.as_string, ch);
4788 }
4789#if 0
4790 else if (next == '(') {
4791 syntax_error("<(process) not supported");
4792 goto parse_error;
4793 }
4794#endif
4795 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4796 goto parse_error;
4797 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004798 case '#':
4799 if (dest.length == 0 && !dest.has_quoted_part) {
4800 /* skip "#comment" */
4801 while (1) {
4802 ch = i_peek(input);
4803 if (ch == EOF || ch == '\n')
4804 break;
4805 i_getch(input);
4806 /* note: we do not add it to &ctx.as_string */
4807 }
4808 nommu_addchr(&ctx.as_string, '\n');
4809 continue; /* back to top of while (1) */
4810 }
4811 break;
4812 case '\\':
4813 if (next == '\n') {
4814 /* It's "\<newline>" */
4815#if !BB_MMU
4816 /* Remove trailing '\' from ctx.as_string */
4817 ctx.as_string.data[--ctx.as_string.length] = '\0';
4818#endif
4819 ch = i_getch(input); /* eat it */
4820 continue; /* back to top of while (1) */
4821 }
4822 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004823 }
4824
4825 if (dest.o_assignment == MAYBE_ASSIGNMENT
4826 /* check that we are not in word in "a=1 2>word b=1": */
4827 && !ctx.pending_redirect
4828 ) {
4829 /* ch is a special char and thus this word
4830 * cannot be an assignment */
4831 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004832 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004833 }
4834
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004835 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4836
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004837 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004838 case '#': /* non-comment #: "echo a#b" etc */
4839 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004840 break;
4841 case '\\':
4842 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004843 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004844 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004845 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004846 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004847 /* note: ch != '\n' (that case does not reach this place) */
4848 o_addchr(&dest, '\\');
4849 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4850 o_addchr(&dest, ch);
4851 nommu_addchr(&ctx.as_string, ch);
4852 /* Example: echo Hello \2>file
4853 * we need to know that word 2 is quoted */
4854 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004855 break;
4856 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004857 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004858 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004859 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004860 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004861 }
Eric Andersen25f27032001-04-26 23:22:31 +00004862 break;
4863 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004864 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004865 if (next == '\'' && !ctx.pending_redirect) {
4866 insert_empty_quoted_str_marker:
4867 nommu_addchr(&ctx.as_string, next);
4868 i_getch(input); /* eat second ' */
4869 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4870 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4871 } else {
4872 while (1) {
4873 ch = i_getch(input);
4874 if (ch == EOF) {
4875 syntax_error_unterm_ch('\'');
4876 goto parse_error;
4877 }
4878 nommu_addchr(&ctx.as_string, ch);
4879 if (ch == '\'')
4880 break;
4881 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004882 }
Eric Andersen25f27032001-04-26 23:22:31 +00004883 }
Eric Andersen25f27032001-04-26 23:22:31 +00004884 break;
4885 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004886 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004887 if (next == '"' && !ctx.pending_redirect)
4888 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004889 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004890 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004891 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004892 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004893 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004894 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004895#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004896 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004897 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004898
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004899 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4900 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004901 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004902 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4903 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004904# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004905 o_addstr(&ctx.as_string, dest.data + pos);
4906 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004907# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004908 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4909 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004910 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004911 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004912#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004913 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004914#if ENABLE_HUSH_CASE
4915 case_semi:
4916#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004917 if (done_word(&dest, &ctx)) {
4918 goto parse_error;
4919 }
4920 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004921#if ENABLE_HUSH_CASE
4922 /* Eat multiple semicolons, detect
4923 * whether it means something special */
4924 while (1) {
4925 ch = i_peek(input);
4926 if (ch != ';')
4927 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004928 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004929 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004930 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004931 ctx.ctx_dsemicolon = 1;
4932 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004933 break;
4934 }
4935 }
4936#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004937 new_cmd:
4938 /* We just finished a cmd. New one may start
4939 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004940 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004941 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004942 break;
4943 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004944 if (done_word(&dest, &ctx)) {
4945 goto parse_error;
4946 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004947 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004948 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004949 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004950 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004951 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004952 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004953 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004954 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004955 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004956 if (done_word(&dest, &ctx)) {
4957 goto parse_error;
4958 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004959#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004960 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004961 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004962#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004963 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004964 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004965 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004966 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004967 } else {
4968 /* we could pick up a file descriptor choice here
4969 * with redirect_opt_num(), but bash doesn't do it.
4970 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004971 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004972 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004973 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004974 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004975#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004976 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004977 if (ctx.ctx_res_w == RES_MATCH
4978 && ctx.command->argv == NULL /* not (word|(... */
4979 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004980 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004981 ) {
4982 continue;
4983 }
4984#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004985 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004986 if (parse_group(&dest, &ctx, input, ch) != 0) {
4987 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004988 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004989 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004990 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004991#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004992 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004993 goto case_semi;
4994#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004995 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004996 /* proper use of this character is caught by end_trigger:
4997 * if we see {, we call parse_group(..., end_trigger='}')
4998 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004999 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005000 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005001 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005002 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005003 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005004 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005005 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005006
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005007 parse_error:
5008 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005009 struct parse_context *pctx;
5010 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005011
5012 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005013 * Sample for finding leaks on syntax error recovery path.
5014 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005015 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005016 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005017 * while if (true | { true;}); then echo ok; fi; do break; done
5018 * 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 +00005019 */
5020 pctx = &ctx;
5021 do {
5022 /* Update pipe/command counts,
5023 * otherwise freeing may miss some */
5024 done_pipe(pctx, PIPE_SEQ);
5025 debug_printf_clean("freeing list %p from ctx %p\n",
5026 pctx->list_head, pctx);
5027 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005028 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005029 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005030#if !BB_MMU
5031 o_free_unsafe(&pctx->as_string);
5032#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005033 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005034 if (pctx != &ctx) {
5035 free(pctx);
5036 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005037 IF_HAS_KEYWORDS(pctx = p2;)
5038 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005039
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005040 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005041 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005042#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005043 if (pstring)
5044 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005045#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005046 debug_leave();
5047 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005048 }
Eric Andersen25f27032001-04-26 23:22:31 +00005049}
5050
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005051
5052/*** Execution routines ***/
5053
5054/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005055#if !ENABLE_HUSH_BASH_COMPAT
5056/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5057#define expand_string_to_string(str, do_unbackslash) \
5058 expand_string_to_string(str)
5059#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005060static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005061#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005062static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005063#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005064
5065/* expand_strvec_to_strvec() takes a list of strings, expands
5066 * all variable references within and returns a pointer to
5067 * a list of expanded strings, possibly with larger number
5068 * of strings. (Think VAR="a b"; echo $VAR).
5069 * This new list is allocated as a single malloc block.
5070 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005071 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005072 * Caller can deallocate entire list by single free(list). */
5073
Denys Vlasenko238081f2010-10-03 14:26:26 +02005074/* A horde of its helpers come first: */
5075
5076static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5077{
5078 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005079 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005080
Denys Vlasenko9e800222010-10-03 14:28:04 +02005081#if ENABLE_HUSH_BRACE_EXPANSION
5082 if (c == '{' || c == '}') {
5083 /* { -> \{, } -> \} */
5084 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005085 /* And now we want to add { or } and continue:
5086 * o_addchr(o, c);
5087 * continue;
5088 * luckily, just falling throught achieves this.
5089 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005090 }
5091#endif
5092 o_addchr(o, c);
5093 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005094 /* \z -> \\\z; \<eol> -> \\<eol> */
5095 o_addchr(o, '\\');
5096 if (len) {
5097 len--;
5098 o_addchr(o, '\\');
5099 o_addchr(o, *str++);
5100 }
5101 }
5102 }
5103}
5104
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005105/* Store given string, finalizing the word and starting new one whenever
5106 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005107 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5108 * Return in *ended_with_ifs:
5109 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5110 */
5111static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005112{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005113 int last_is_ifs = 0;
5114
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005115 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005116 int word_len;
5117
5118 if (!*str) /* EOL - do not finalize word */
5119 break;
5120 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005121 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005122 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005123 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005124 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005125 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005126 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005127 * Example: "v='\*'; echo b$v" prints "b\*"
5128 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005129 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005130 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005131 /*/ Why can't we do it easier? */
5132 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5133 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5134 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005135 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005136 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005137 if (!*str) /* EOL - do not finalize word */
5138 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005139 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005140
5141 /* We know str here points to at least one IFS char */
5142 last_is_ifs = 1;
5143 str += strspn(str, G.ifs); /* skip IFS chars */
5144 if (!*str) /* EOL - do not finalize word */
5145 break;
5146
5147 /* Start new word... but not always! */
5148 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005149 if (output->has_quoted_part
5150 /* Case "v=' a'; echo $v":
5151 * here nothing precedes the space in $v expansion,
5152 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005153 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005154 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005155 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005156 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005157 o_addchr(output, '\0');
5158 debug_print_list("expand_on_ifs", output, n);
5159 n = o_save_ptr(output, n);
5160 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005161 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005162
5163 if (ended_with_ifs)
5164 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005165 debug_print_list("expand_on_ifs[1]", output, n);
5166 return n;
5167}
5168
5169/* Helper to expand $((...)) and heredoc body. These act as if
5170 * they are in double quotes, with the exception that they are not :).
5171 * Just the rules are similar: "expand only $var and `cmd`"
5172 *
5173 * Returns malloced string.
5174 * As an optimization, we return NULL if expansion is not needed.
5175 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005176#if !ENABLE_HUSH_BASH_COMPAT
5177/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5178#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5179 encode_then_expand_string(str)
5180#endif
5181static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005182{
5183 char *exp_str;
5184 struct in_str input;
5185 o_string dest = NULL_O_STRING;
5186
5187 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005188 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005189#if ENABLE_HUSH_TICK
5190 && !strchr(str, '`')
5191#endif
5192 ) {
5193 return NULL;
5194 }
5195
5196 /* We need to expand. Example:
5197 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5198 */
5199 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005200 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005201//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005202 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005203 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005204 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5205 o_free_unsafe(&dest);
5206 return exp_str;
5207}
5208
Denys Vlasenko0b883582016-12-23 16:49:07 +01005209#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005210static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005211{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005212 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005213 arith_t res;
5214 char *exp_str;
5215
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005216 math_state.lookupvar = get_local_var_value;
5217 math_state.setvar = set_local_var_from_halves;
5218 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005219 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005220 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005221 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005222 if (errmsg_p)
5223 *errmsg_p = math_state.errmsg;
5224 if (math_state.errmsg)
5225 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005226 return res;
5227}
5228#endif
5229
5230#if ENABLE_HUSH_BASH_COMPAT
5231/* ${var/[/]pattern[/repl]} helpers */
5232static char *strstr_pattern(char *val, const char *pattern, int *size)
5233{
5234 while (1) {
5235 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5236 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5237 if (end) {
5238 *size = end - val;
5239 return val;
5240 }
5241 if (*val == '\0')
5242 return NULL;
5243 /* Optimization: if "*pat" did not match the start of "string",
5244 * we know that "tring", "ring" etc will not match too:
5245 */
5246 if (pattern[0] == '*')
5247 return NULL;
5248 val++;
5249 }
5250}
5251static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5252{
5253 char *result = NULL;
5254 unsigned res_len = 0;
5255 unsigned repl_len = strlen(repl);
5256
5257 while (1) {
5258 int size;
5259 char *s = strstr_pattern(val, pattern, &size);
5260 if (!s)
5261 break;
5262
5263 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5264 memcpy(result + res_len, val, s - val);
5265 res_len += s - val;
5266 strcpy(result + res_len, repl);
5267 res_len += repl_len;
5268 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5269
5270 val = s + size;
5271 if (exp_op == '/')
5272 break;
5273 }
5274 if (val[0] && result) {
5275 result = xrealloc(result, res_len + strlen(val) + 1);
5276 strcpy(result + res_len, val);
5277 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5278 }
5279 debug_printf_varexp("result:'%s'\n", result);
5280 return result;
5281}
5282#endif
5283
5284/* Helper:
5285 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5286 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005287static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005288{
5289 const char *val = NULL;
5290 char *to_be_freed = NULL;
5291 char *p = *pp;
5292 char *var;
5293 char first_char;
5294 char exp_op;
5295 char exp_save = exp_save; /* for compiler */
5296 char *exp_saveptr; /* points to expansion operator */
5297 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005298 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005299
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005300 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005301 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005302 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005303 arg0 = arg[0];
5304 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005305 exp_op = 0;
5306
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005307 if (first_char == '#' /* ${#... */
5308 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5309 ) {
5310 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005311 var++;
5312 exp_op = 'L';
5313 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005314 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005315 if (exp_saveptr /* if 2nd char is one of expansion operators */
5316 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5317 ) {
5318 /* ${?:0}, ${#[:]%0} etc */
5319 exp_saveptr = var + 1;
5320 } else {
5321 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5322 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5323 }
5324 exp_op = exp_save = *exp_saveptr;
5325 if (exp_op) {
5326 exp_word = exp_saveptr + 1;
5327 if (exp_op == ':') {
5328 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005329//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005330 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005331 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005332 ) {
5333 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5334 exp_op = ':';
5335 exp_word--;
5336 }
5337 }
5338 *exp_saveptr = '\0';
5339 } /* else: it's not an expansion op, but bare ${var} */
5340 }
5341
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005342 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005343 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005344 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005345 int n = xatoi_positive(var);
5346 if (n < G.global_argc)
5347 val = G.global_argv[n];
5348 /* else val remains NULL: $N with too big N */
5349 } else {
5350 switch (var[0]) {
5351 case '$': /* pid */
5352 val = utoa(G.root_pid);
5353 break;
5354 case '!': /* bg pid */
5355 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5356 break;
5357 case '?': /* exitcode */
5358 val = utoa(G.last_exitcode);
5359 break;
5360 case '#': /* argc */
5361 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5362 break;
5363 default:
5364 val = get_local_var_value(var);
5365 }
5366 }
5367
5368 /* Handle any expansions */
5369 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005370 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005371 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005372 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005373 debug_printf_expand("%s\n", val);
5374 } else if (exp_op) {
5375 if (exp_op == '%' || exp_op == '#') {
5376 /* Standard-mandated substring removal ops:
5377 * ${parameter%word} - remove smallest suffix pattern
5378 * ${parameter%%word} - remove largest suffix pattern
5379 * ${parameter#word} - remove smallest prefix pattern
5380 * ${parameter##word} - remove largest prefix pattern
5381 *
5382 * Word is expanded to produce a glob pattern.
5383 * Then var's value is matched to it and matching part removed.
5384 */
5385 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005386 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005387 char *exp_exp_word;
5388 char *loc;
5389 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005390 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005391 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005392 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005393 if (exp_exp_word)
5394 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005395 /* HACK ALERT. We depend here on the fact that
5396 * G.global_argv and results of utoa and get_local_var_value
5397 * are actually in writable memory:
5398 * scan_and_match momentarily stores NULs there. */
5399 t = (char*)val;
5400 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005401 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005402 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005403 free(exp_exp_word);
5404 if (loc) { /* match was found */
5405 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005406 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005407 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005408 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005409 }
5410 }
5411 }
5412#if ENABLE_HUSH_BASH_COMPAT
5413 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005414 /* It's ${var/[/]pattern[/repl]} thing.
5415 * Note that in encoded form it has TWO parts:
5416 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005417 * and if // is used, it is encoded as \:
5418 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005419 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005420 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005421 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005422 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005423 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005424 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005425 * by the usual expansion rules:
5426 * >az; >bz;
5427 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5428 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5429 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5430 * v='a bz'; echo ${v/a*z/\z} prints "z"
5431 * (note that a*z _pattern_ is never globbed!)
5432 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005433 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005434 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005435 if (!pattern)
5436 pattern = xstrdup(exp_word);
5437 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5438 *p++ = SPECIAL_VAR_SYMBOL;
5439 exp_word = p;
5440 p = strchr(p, SPECIAL_VAR_SYMBOL);
5441 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005442 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005443 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5444 /* HACK ALERT. We depend here on the fact that
5445 * G.global_argv and results of utoa and get_local_var_value
5446 * are actually in writable memory:
5447 * replace_pattern momentarily stores NULs there. */
5448 t = (char*)val;
5449 to_be_freed = replace_pattern(t,
5450 pattern,
5451 (repl ? repl : exp_word),
5452 exp_op);
5453 if (to_be_freed) /* at least one replace happened */
5454 val = to_be_freed;
5455 free(pattern);
5456 free(repl);
5457 }
5458 }
5459#endif
5460 else if (exp_op == ':') {
Denys Vlasenko0b883582016-12-23 16:49:07 +01005461#if ENABLE_HUSH_BASH_COMPAT && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005462 /* It's ${var:N[:M]} bashism.
5463 * Note that in encoded form it has TWO parts:
5464 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5465 */
5466 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005467 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005468
Denys Vlasenko063847d2010-09-15 13:33:02 +02005469 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5470 if (errmsg)
5471 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005472 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5473 *p++ = SPECIAL_VAR_SYMBOL;
5474 exp_word = p;
5475 p = strchr(p, SPECIAL_VAR_SYMBOL);
5476 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005477 len = expand_and_evaluate_arith(exp_word, &errmsg);
5478 if (errmsg)
5479 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005480 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005481 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005482 if (beg < 0) /* bash compat */
5483 beg = 0;
5484 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005485 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005486 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005487 val = NULL;
5488 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005489 /* Paranoia. What if user entered 9999999999999
5490 * which fits in arith_t but not int? */
5491 if (len >= INT_MAX)
5492 len = INT_MAX;
5493 val = to_be_freed = xstrndup(val + beg, len);
5494 }
5495 debug_printf_varexp("val:'%s'\n", val);
5496 } else
5497#endif
5498 {
5499 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005500 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005501 }
5502 } else { /* one of "-=+?" */
5503 /* Standard-mandated substitution ops:
5504 * ${var?word} - indicate error if unset
5505 * If var is unset, word (or a message indicating it is unset
5506 * if word is null) is written to standard error
5507 * and the shell exits with a non-zero exit status.
5508 * Otherwise, the value of var is substituted.
5509 * ${var-word} - use default value
5510 * If var is unset, word is substituted.
5511 * ${var=word} - assign and use default value
5512 * If var is unset, word is assigned to var.
5513 * In all cases, final value of var is substituted.
5514 * ${var+word} - use alternative value
5515 * If var is unset, null is substituted.
5516 * Otherwise, word is substituted.
5517 *
5518 * Word is subjected to tilde expansion, parameter expansion,
5519 * command substitution, and arithmetic expansion.
5520 * If word is not needed, it is not expanded.
5521 *
5522 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5523 * but also treat null var as if it is unset.
5524 */
5525 int use_word = (!val || ((exp_save == ':') && !val[0]));
5526 if (exp_op == '+')
5527 use_word = !use_word;
5528 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5529 (exp_save == ':') ? "true" : "false", use_word);
5530 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005531 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005532 if (to_be_freed)
5533 exp_word = to_be_freed;
5534 if (exp_op == '?') {
5535 /* mimic bash message */
5536 die_if_script("%s: %s",
5537 var,
5538 exp_word[0] ? exp_word : "parameter null or not set"
5539 );
5540//TODO: how interactive bash aborts expansion mid-command?
5541 } else {
5542 val = exp_word;
5543 }
5544
5545 if (exp_op == '=') {
5546 /* ${var=[word]} or ${var:=[word]} */
5547 if (isdigit(var[0]) || var[0] == '#') {
5548 /* mimic bash message */
5549 die_if_script("$%s: cannot assign in this way", var);
5550 val = NULL;
5551 } else {
5552 char *new_var = xasprintf("%s=%s", var, val);
5553 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5554 }
5555 }
5556 }
5557 } /* one of "-=+?" */
5558
5559 *exp_saveptr = exp_save;
5560 } /* if (exp_op) */
5561
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005562 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005563
5564 *pp = p;
5565 *to_be_freed_pp = to_be_freed;
5566 return val;
5567}
5568
5569/* Expand all variable references in given string, adding words to list[]
5570 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5571 * to be filled). This routine is extremely tricky: has to deal with
5572 * variables/parameters with whitespace, $* and $@, and constructs like
5573 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005574static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005575{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005576 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005577 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005578 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005579 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005580 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005581 char *p;
5582
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005583 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5584 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005585 debug_print_list("expand_vars_to_list", output, n);
5586 n = o_save_ptr(output, n);
5587 debug_print_list("expand_vars_to_list[0]", output, n);
5588
5589 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5590 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005591 char *to_be_freed = NULL;
5592 const char *val = NULL;
5593#if ENABLE_HUSH_TICK
5594 o_string subst_result = NULL_O_STRING;
5595#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01005596#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005597 char arith_buf[sizeof(arith_t)*3 + 2];
5598#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005599
5600 if (ended_in_ifs) {
5601 o_addchr(output, '\0');
5602 n = o_save_ptr(output, n);
5603 ended_in_ifs = 0;
5604 }
5605
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005606 o_addblock(output, arg, p - arg);
5607 debug_print_list("expand_vars_to_list[1]", output, n);
5608 arg = ++p;
5609 p = strchr(p, SPECIAL_VAR_SYMBOL);
5610
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005611 /* Fetch special var name (if it is indeed one of them)
5612 * and quote bit, force the bit on if singleword expansion -
5613 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005614 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005615
5616 /* Is this variable quoted and thus expansion can't be null?
5617 * "$@" is special. Even if quoted, it can still
5618 * expand to nothing (not even an empty string),
5619 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005620 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005621 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005622
5623 switch (first_ch & 0x7f) {
5624 /* Highest bit in first_ch indicates that var is double-quoted */
5625 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005626 case '@': {
5627 int i;
5628 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005629 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005630 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005631 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005632 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005633 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005634 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005635 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5636 if (G.global_argv[i++][0] && G.global_argv[i]) {
5637 /* this argv[] is not empty and not last:
5638 * put terminating NUL, start new word */
5639 o_addchr(output, '\0');
5640 debug_print_list("expand_vars_to_list[2]", output, n);
5641 n = o_save_ptr(output, n);
5642 debug_print_list("expand_vars_to_list[3]", output, n);
5643 }
5644 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005645 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005646 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005647 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005648 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005649 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005650 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005651 while (1) {
5652 o_addQstr(output, G.global_argv[i]);
5653 if (++i >= G.global_argc)
5654 break;
5655 o_addchr(output, '\0');
5656 debug_print_list("expand_vars_to_list[4]", output, n);
5657 n = o_save_ptr(output, n);
5658 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005659 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005660 while (1) {
5661 o_addQstr(output, G.global_argv[i]);
5662 if (!G.global_argv[++i])
5663 break;
5664 if (G.ifs[0])
5665 o_addchr(output, G.ifs[0]);
5666 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005667 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005668 }
5669 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005670 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005671 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5672 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005673 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005674 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005675 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005676 break;
5677#if ENABLE_HUSH_TICK
5678 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005679 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005680 arg++;
5681 /* Can't just stuff it into output o_string,
5682 * expanded result may need to be globbed
5683 * and $IFS-splitted */
5684 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5685 G.last_exitcode = process_command_subs(&subst_result, arg);
5686 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5687 val = subst_result.data;
5688 goto store_val;
5689#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01005690#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005691 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5692 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005693
5694 arg++; /* skip '+' */
5695 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5696 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005697 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005698 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5699 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005700 val = arith_buf;
5701 break;
5702 }
5703#endif
5704 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005705 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005706 IF_HUSH_TICK(store_val:)
5707 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005708 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5709 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005710 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005711 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005712 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005713 }
5714 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005715 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005716 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5717 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005718 }
5719 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005720 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5721
5722 if (val && val[0]) {
5723 o_addQstr(output, val);
5724 }
5725 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005726
5727 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5728 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005729 if (*p != SPECIAL_VAR_SYMBOL)
5730 *p = SPECIAL_VAR_SYMBOL;
5731
5732#if ENABLE_HUSH_TICK
5733 o_free(&subst_result);
5734#endif
5735 arg = ++p;
5736 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5737
5738 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005739 if (ended_in_ifs) {
5740 o_addchr(output, '\0');
5741 n = o_save_ptr(output, n);
5742 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005743 debug_print_list("expand_vars_to_list[a]", output, n);
5744 /* this part is literal, and it was already pre-quoted
5745 * if needed (much earlier), do not use o_addQstr here! */
5746 o_addstr_with_NUL(output, arg);
5747 debug_print_list("expand_vars_to_list[b]", output, n);
5748 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005749 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005750 ) {
5751 n--;
5752 /* allow to reuse list[n] later without re-growth */
5753 output->has_empty_slot = 1;
5754 } else {
5755 o_addchr(output, '\0');
5756 }
5757
5758 return n;
5759}
5760
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005761static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005762{
5763 int n;
5764 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005765 o_string output = NULL_O_STRING;
5766
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005767 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005768
5769 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005770 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005771 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005772 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005773 }
5774 debug_print_list("expand_variables", &output, n);
5775
5776 /* output.data (malloced in one block) gets returned in "list" */
5777 list = o_finalize_list(&output, n);
5778 debug_print_strings("expand_variables[1]", list);
5779 return list;
5780}
5781
5782static char **expand_strvec_to_strvec(char **argv)
5783{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005784 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005785}
5786
5787#if ENABLE_HUSH_BASH_COMPAT
5788static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5789{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005790 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005791}
5792#endif
5793
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005794/* Used for expansion of right hand of assignments,
5795 * $((...)), heredocs, variable espansion parts.
5796 *
5797 * NB: should NOT do globbing!
5798 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5799 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005800static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005801{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005802#if !ENABLE_HUSH_BASH_COMPAT
5803 const int do_unbackslash = 1;
5804#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005805 char *argv[2], **list;
5806
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005807 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005808 /* This is generally an optimization, but it also
5809 * handles "", which otherwise trips over !list[0] check below.
5810 * (is this ever happens that we actually get str="" here?)
5811 */
5812 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5813 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005814 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005815 return xstrdup(str);
5816 }
5817
5818 argv[0] = (char*)str;
5819 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005820 list = expand_variables(argv, do_unbackslash
5821 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5822 : EXP_FLAG_SINGLEWORD
5823 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005824 if (HUSH_DEBUG)
5825 if (!list[0] || list[1])
5826 bb_error_msg_and_die("BUG in varexp2");
5827 /* actually, just move string 2*sizeof(char*) bytes back */
5828 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005829 if (do_unbackslash)
5830 unbackslash((char*)list);
5831 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005832 return (char*)list;
5833}
5834
5835/* Used for "eval" builtin */
5836static char* expand_strvec_to_string(char **argv)
5837{
5838 char **list;
5839
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005840 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005841 /* Convert all NULs to spaces */
5842 if (list[0]) {
5843 int n = 1;
5844 while (list[n]) {
5845 if (HUSH_DEBUG)
5846 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5847 bb_error_msg_and_die("BUG in varexp3");
5848 /* bash uses ' ' regardless of $IFS contents */
5849 list[n][-1] = ' ';
5850 n++;
5851 }
5852 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02005853 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005854 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5855 return (char*)list;
5856}
5857
5858static char **expand_assignments(char **argv, int count)
5859{
5860 int i;
5861 char **p;
5862
5863 G.expanded_assignments = p = NULL;
5864 /* Expand assignments into one string each */
5865 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005866 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005867 }
5868 G.expanded_assignments = NULL;
5869 return p;
5870}
5871
5872
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005873static void switch_off_special_sigs(unsigned mask)
5874{
5875 unsigned sig = 0;
5876 while ((mask >>= 1) != 0) {
5877 sig++;
5878 if (!(mask & 1))
5879 continue;
5880 if (G.traps) {
5881 if (G.traps[sig] && !G.traps[sig][0])
5882 /* trap is '', has to remain SIG_IGN */
5883 continue;
5884 free(G.traps[sig]);
5885 G.traps[sig] = NULL;
5886 }
5887 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005888 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005889 }
5890}
5891
Denys Vlasenkob347df92011-08-09 22:49:15 +02005892#if BB_MMU
5893/* never called */
5894void re_execute_shell(char ***to_free, const char *s,
5895 char *g_argv0, char **g_argv,
5896 char **builtin_argv) NORETURN;
5897
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005898static void reset_traps_to_defaults(void)
5899{
5900 /* This function is always called in a child shell
5901 * after fork (not vfork, NOMMU doesn't use this function).
5902 */
5903 unsigned sig;
5904 unsigned mask;
5905
5906 /* Child shells are not interactive.
5907 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5908 * Testcase: (while :; do :; done) + ^Z should background.
5909 * Same goes for SIGTERM, SIGHUP, SIGINT.
5910 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005911 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5912 if (!G.traps && !mask)
5913 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005914
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005915 /* Switch off special sigs */
5916 switch_off_special_sigs(mask);
5917#if ENABLE_HUSH_JOB
5918 G_fatal_sig_mask = 0;
5919#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005920 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005921 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5922 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005923
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005924 if (!G.traps)
5925 return;
5926
5927 /* Reset all sigs to default except ones with empty traps */
5928 for (sig = 0; sig < NSIG; sig++) {
5929 if (!G.traps[sig])
5930 continue; /* no trap: nothing to do */
5931 if (!G.traps[sig][0])
5932 continue; /* empty trap: has to remain SIG_IGN */
5933 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005934 free(G.traps[sig]);
5935 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005936 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005937 if (sig == 0)
5938 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005939 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005940 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005941}
5942
5943#else /* !BB_MMU */
5944
5945static void re_execute_shell(char ***to_free, const char *s,
5946 char *g_argv0, char **g_argv,
5947 char **builtin_argv) NORETURN;
5948static void re_execute_shell(char ***to_free, const char *s,
5949 char *g_argv0, char **g_argv,
5950 char **builtin_argv)
5951{
5952# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5953 /* delims + 2 * (number of bytes in printed hex numbers) */
5954 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5955 char *heredoc_argv[4];
5956 struct variable *cur;
5957# if ENABLE_HUSH_FUNCTIONS
5958 struct function *funcp;
5959# endif
5960 char **argv, **pp;
5961 unsigned cnt;
5962 unsigned long long empty_trap_mask;
5963
5964 if (!g_argv0) { /* heredoc */
5965 argv = heredoc_argv;
5966 argv[0] = (char *) G.argv0_for_re_execing;
5967 argv[1] = (char *) "-<";
5968 argv[2] = (char *) s;
5969 argv[3] = NULL;
5970 pp = &argv[3]; /* used as pointer to empty environment */
5971 goto do_exec;
5972 }
5973
5974 cnt = 0;
5975 pp = builtin_argv;
5976 if (pp) while (*pp++)
5977 cnt++;
5978
5979 empty_trap_mask = 0;
5980 if (G.traps) {
5981 int sig;
5982 for (sig = 1; sig < NSIG; sig++) {
5983 if (G.traps[sig] && !G.traps[sig][0])
5984 empty_trap_mask |= 1LL << sig;
5985 }
5986 }
5987
5988 sprintf(param_buf, NOMMU_HACK_FMT
5989 , (unsigned) G.root_pid
5990 , (unsigned) G.root_ppid
5991 , (unsigned) G.last_bg_pid
5992 , (unsigned) G.last_exitcode
5993 , cnt
5994 , empty_trap_mask
5995 IF_HUSH_LOOPS(, G.depth_of_loop)
5996 );
5997# undef NOMMU_HACK_FMT
5998 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5999 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6000 */
6001 cnt += 6;
6002 for (cur = G.top_var; cur; cur = cur->next) {
6003 if (!cur->flg_export || cur->flg_read_only)
6004 cnt += 2;
6005 }
6006# if ENABLE_HUSH_FUNCTIONS
6007 for (funcp = G.top_func; funcp; funcp = funcp->next)
6008 cnt += 3;
6009# endif
6010 pp = g_argv;
6011 while (*pp++)
6012 cnt++;
6013 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6014 *pp++ = (char *) G.argv0_for_re_execing;
6015 *pp++ = param_buf;
6016 for (cur = G.top_var; cur; cur = cur->next) {
6017 if (strcmp(cur->varstr, hush_version_str) == 0)
6018 continue;
6019 if (cur->flg_read_only) {
6020 *pp++ = (char *) "-R";
6021 *pp++ = cur->varstr;
6022 } else if (!cur->flg_export) {
6023 *pp++ = (char *) "-V";
6024 *pp++ = cur->varstr;
6025 }
6026 }
6027# if ENABLE_HUSH_FUNCTIONS
6028 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6029 *pp++ = (char *) "-F";
6030 *pp++ = funcp->name;
6031 *pp++ = funcp->body_as_string;
6032 }
6033# endif
6034 /* We can pass activated traps here. Say, -Tnn:trap_string
6035 *
6036 * However, POSIX says that subshells reset signals with traps
6037 * to SIG_DFL.
6038 * I tested bash-3.2 and it not only does that with true subshells
6039 * of the form ( list ), but with any forked children shells.
6040 * I set trap "echo W" WINCH; and then tried:
6041 *
6042 * { echo 1; sleep 20; echo 2; } &
6043 * while true; do echo 1; sleep 20; echo 2; break; done &
6044 * true | { echo 1; sleep 20; echo 2; } | cat
6045 *
6046 * In all these cases sending SIGWINCH to the child shell
6047 * did not run the trap. If I add trap "echo V" WINCH;
6048 * _inside_ group (just before echo 1), it works.
6049 *
6050 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006051 */
6052 *pp++ = (char *) "-c";
6053 *pp++ = (char *) s;
6054 if (builtin_argv) {
6055 while (*++builtin_argv)
6056 *pp++ = *builtin_argv;
6057 *pp++ = (char *) "";
6058 }
6059 *pp++ = g_argv0;
6060 while (*g_argv)
6061 *pp++ = *g_argv++;
6062 /* *pp = NULL; - is already there */
6063 pp = environ;
6064
6065 do_exec:
6066 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006067 /* Don't propagate SIG_IGN to the child */
6068 if (SPECIAL_JOBSTOP_SIGS != 0)
6069 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006070 execve(bb_busybox_exec_path, argv, pp);
6071 /* Fallback. Useful for init=/bin/hush usage etc */
6072 if (argv[0][0] == '/')
6073 execve(argv[0], argv, pp);
6074 xfunc_error_retval = 127;
6075 bb_error_msg_and_die("can't re-execute the shell");
6076}
6077#endif /* !BB_MMU */
6078
6079
6080static int run_and_free_list(struct pipe *pi);
6081
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006082/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006083 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6084 * end_trigger controls how often we stop parsing
6085 * NUL: parse all, execute, return
6086 * ';': parse till ';' or newline, execute, repeat till EOF
6087 */
6088static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006089{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006090 /* Why we need empty flag?
6091 * An obscure corner case "false; ``; echo $?":
6092 * empty command in `` should still set $? to 0.
6093 * But we can't just set $? to 0 at the start,
6094 * this breaks "false; echo `echo $?`" case.
6095 */
6096 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006097 while (1) {
6098 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006099
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006100#if ENABLE_HUSH_INTERACTIVE
6101 if (end_trigger == ';')
6102 inp->promptmode = 0; /* PS1 */
6103#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006104 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006105 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6106 /* If we are in "big" script
6107 * (not in `cmd` or something similar)...
6108 */
6109 if (pipe_list == ERR_PTR && end_trigger == ';') {
6110 /* Discard cached input (rest of line) */
6111 int ch = inp->last_char;
6112 while (ch != EOF && ch != '\n') {
6113 //bb_error_msg("Discarded:'%c'", ch);
6114 ch = i_getch(inp);
6115 }
6116 /* Force prompt */
6117 inp->p = NULL;
6118 /* This stream isn't empty */
6119 empty = 0;
6120 continue;
6121 }
6122 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006123 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006124 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006125 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006126 debug_print_tree(pipe_list, 0);
6127 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6128 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006129 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006130 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006131 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006132 }
Eric Andersen25f27032001-04-26 23:22:31 +00006133}
6134
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006135static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006136{
6137 struct in_str input;
6138 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006139 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006140}
6141
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006142static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006143{
Eric Andersen25f27032001-04-26 23:22:31 +00006144 struct in_str input;
6145 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006146 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006147}
6148
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006149#if ENABLE_HUSH_TICK
6150static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6151{
6152 pid_t pid;
6153 int channel[2];
6154# if !BB_MMU
6155 char **to_free = NULL;
6156# endif
6157
6158 xpipe(channel);
6159 pid = BB_MMU ? xfork() : xvfork();
6160 if (pid == 0) { /* child */
6161 disable_restore_tty_pgrp_on_exit();
6162 /* Process substitution is not considered to be usual
6163 * 'command execution'.
6164 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6165 */
6166 bb_signals(0
6167 + (1 << SIGTSTP)
6168 + (1 << SIGTTIN)
6169 + (1 << SIGTTOU)
6170 , SIG_IGN);
6171 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6172 close(channel[0]); /* NB: close _first_, then move fd! */
6173 xmove_fd(channel[1], 1);
6174 /* Prevent it from trying to handle ctrl-z etc */
6175 IF_HUSH_JOB(G.run_list_level = 1;)
6176 /* Awful hack for `trap` or $(trap).
6177 *
6178 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6179 * contains an example where "trap" is executed in a subshell:
6180 *
6181 * save_traps=$(trap)
6182 * ...
6183 * eval "$save_traps"
6184 *
6185 * Standard does not say that "trap" in subshell shall print
6186 * parent shell's traps. It only says that its output
6187 * must have suitable form, but then, in the above example
6188 * (which is not supposed to be normative), it implies that.
6189 *
6190 * bash (and probably other shell) does implement it
6191 * (traps are reset to defaults, but "trap" still shows them),
6192 * but as a result, "trap" logic is hopelessly messed up:
6193 *
6194 * # trap
6195 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6196 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6197 * # true | trap <--- trap is in subshell - no output (ditto)
6198 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6199 * trap -- 'echo Ho' SIGWINCH
6200 * # echo `(trap)` <--- in subshell in subshell - output
6201 * trap -- 'echo Ho' SIGWINCH
6202 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6203 * trap -- 'echo Ho' SIGWINCH
6204 *
6205 * The rules when to forget and when to not forget traps
6206 * get really complex and nonsensical.
6207 *
6208 * Our solution: ONLY bare $(trap) or `trap` is special.
6209 */
6210 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006211 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006212 && skip_whitespace(s + 4)[0] == '\0'
6213 ) {
6214 static const char *const argv[] = { NULL, NULL };
6215 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006216 fflush_all(); /* important */
6217 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006218 }
6219# if BB_MMU
6220 reset_traps_to_defaults();
6221 parse_and_run_string(s);
6222 _exit(G.last_exitcode);
6223# else
6224 /* We re-execute after vfork on NOMMU. This makes this script safe:
6225 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6226 * huge=`cat BIG` # was blocking here forever
6227 * echo OK
6228 */
6229 re_execute_shell(&to_free,
6230 s,
6231 G.global_argv[0],
6232 G.global_argv + 1,
6233 NULL);
6234# endif
6235 }
6236
6237 /* parent */
6238 *pid_p = pid;
6239# if ENABLE_HUSH_FAST
6240 G.count_SIGCHLD++;
6241//bb_error_msg("[%d] fork in generate_stream_from_string:"
6242// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6243// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6244# endif
6245 enable_restore_tty_pgrp_on_exit();
6246# if !BB_MMU
6247 free(to_free);
6248# endif
6249 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006250 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006251}
6252
6253/* Return code is exit status of the process that is run. */
6254static int process_command_subs(o_string *dest, const char *s)
6255{
6256 FILE *fp;
6257 struct in_str pipe_str;
6258 pid_t pid;
6259 int status, ch, eol_cnt;
6260
6261 fp = generate_stream_from_string(s, &pid);
6262
6263 /* Now send results of command back into original context */
6264 setup_file_in_str(&pipe_str, fp);
6265 eol_cnt = 0;
6266 while ((ch = i_getch(&pipe_str)) != EOF) {
6267 if (ch == '\n') {
6268 eol_cnt++;
6269 continue;
6270 }
6271 while (eol_cnt) {
6272 o_addchr(dest, '\n');
6273 eol_cnt--;
6274 }
6275 o_addQchr(dest, ch);
6276 }
6277
6278 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006279 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006280 /* We need to extract exitcode. Test case
6281 * "true; echo `sleep 1; false` $?"
6282 * should print 1 */
6283 safe_waitpid(pid, &status, 0);
6284 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6285 return WEXITSTATUS(status);
6286}
6287#endif /* ENABLE_HUSH_TICK */
6288
6289
6290static void setup_heredoc(struct redir_struct *redir)
6291{
6292 struct fd_pair pair;
6293 pid_t pid;
6294 int len, written;
6295 /* the _body_ of heredoc (misleading field name) */
6296 const char *heredoc = redir->rd_filename;
6297 char *expanded;
6298#if !BB_MMU
6299 char **to_free;
6300#endif
6301
6302 expanded = NULL;
6303 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006304 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006305 if (expanded)
6306 heredoc = expanded;
6307 }
6308 len = strlen(heredoc);
6309
6310 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6311 xpiped_pair(pair);
6312 xmove_fd(pair.rd, redir->rd_fd);
6313
6314 /* Try writing without forking. Newer kernels have
6315 * dynamically growing pipes. Must use non-blocking write! */
6316 ndelay_on(pair.wr);
6317 while (1) {
6318 written = write(pair.wr, heredoc, len);
6319 if (written <= 0)
6320 break;
6321 len -= written;
6322 if (len == 0) {
6323 close(pair.wr);
6324 free(expanded);
6325 return;
6326 }
6327 heredoc += written;
6328 }
6329 ndelay_off(pair.wr);
6330
6331 /* Okay, pipe buffer was not big enough */
6332 /* Note: we must not create a stray child (bastard? :)
6333 * for the unsuspecting parent process. Child creates a grandchild
6334 * and exits before parent execs the process which consumes heredoc
6335 * (that exec happens after we return from this function) */
6336#if !BB_MMU
6337 to_free = NULL;
6338#endif
6339 pid = xvfork();
6340 if (pid == 0) {
6341 /* child */
6342 disable_restore_tty_pgrp_on_exit();
6343 pid = BB_MMU ? xfork() : xvfork();
6344 if (pid != 0)
6345 _exit(0);
6346 /* grandchild */
6347 close(redir->rd_fd); /* read side of the pipe */
6348#if BB_MMU
6349 full_write(pair.wr, heredoc, len); /* may loop or block */
6350 _exit(0);
6351#else
6352 /* Delegate blocking writes to another process */
6353 xmove_fd(pair.wr, STDOUT_FILENO);
6354 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6355#endif
6356 }
6357 /* parent */
6358#if ENABLE_HUSH_FAST
6359 G.count_SIGCHLD++;
6360//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6361#endif
6362 enable_restore_tty_pgrp_on_exit();
6363#if !BB_MMU
6364 free(to_free);
6365#endif
6366 close(pair.wr);
6367 free(expanded);
6368 wait(NULL); /* wait till child has died */
6369}
6370
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006371/* fd: redirect wants this fd to be used (e.g. 3>file).
6372 * Move all conflicting internally used fds,
6373 * and remember them so that we can restore them later.
6374 */
6375static int save_fds_on_redirect(int fd, int squirrel[3])
6376{
6377 if (squirrel) {
6378 /* Handle redirects of fds 0,1,2 */
6379
6380 /* If we collide with an already moved stdio fd... */
6381 if (fd == squirrel[0]) {
6382 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6383 return 1;
6384 }
6385 if (fd == squirrel[1]) {
6386 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6387 return 1;
6388 }
6389 if (fd == squirrel[2]) {
6390 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6391 return 1;
6392 }
6393 /* If we are about to redirect stdio fd, and did not yet move it... */
6394 if (fd <= 2 && squirrel[fd] < 0) {
6395 /* We avoid taking stdio fds */
6396 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6397 if (squirrel[fd] < 0 && errno != EBADF)
6398 xfunc_die();
6399 return 0; /* "we did not close fd" */
6400 }
6401 }
6402
6403#if ENABLE_HUSH_INTERACTIVE
6404 if (fd != 0 && fd == G.interactive_fd) {
6405 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6406 return 1;
6407 }
6408#endif
6409
6410 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6411 * (1) Redirect in a forked child. No need to save FILEs' fds,
6412 * we aren't going to use them anymore, ok to trash.
6413 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6414 * but how are we doing to use them?
6415 * "fileno(fd) = new_fd" can't be done.
6416 */
6417 if (!squirrel)
6418 return 0;
6419
6420 return save_FILEs_on_redirect(fd);
6421}
6422
6423static void restore_redirects(int squirrel[3])
6424{
6425 int i, fd;
6426 for (i = 0; i <= 2; i++) {
6427 fd = squirrel[i];
6428 if (fd != -1) {
6429 /* We simply die on error */
6430 xmove_fd(fd, i);
6431 }
6432 }
6433
6434 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6435
6436 restore_redirected_FILEs();
6437}
6438
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006439/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6440 * and stderr if they are redirected. */
6441static int setup_redirects(struct command *prog, int squirrel[])
6442{
6443 int openfd, mode;
6444 struct redir_struct *redir;
6445
6446 for (redir = prog->redirects; redir; redir = redir->next) {
6447 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006448 /* "rd_fd<<HERE" case */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006449 save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006450 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6451 * of the heredoc */
6452 debug_printf_parse("set heredoc '%s'\n",
6453 redir->rd_filename);
6454 setup_heredoc(redir);
6455 continue;
6456 }
6457
6458 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006459 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006460 char *p;
6461 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02006462 /*
6463 * Examples:
6464 * "cmd >" (no filename)
6465 * "cmd > <file" (2nd redirect starts too early)
6466 */
6467 die_if_script("syntax error: %s", "invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006468 continue;
6469 }
6470 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006471 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006472 openfd = open_or_warn(p, mode);
6473 free(p);
6474 if (openfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006475 /* Error message from open_or_warn can be lost
6476 * if stderr has been redirected, but bash
6477 * and ash both lose it as well
6478 * (though zsh doesn't!)
6479 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006480 return 1;
6481 }
6482 } else {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006483 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006484 openfd = redir->rd_dup;
6485 }
6486
6487 if (openfd != redir->rd_fd) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006488 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006489 if (openfd == REDIRFD_CLOSE) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006490 /* "rd_fd >&-" means "close me" */
6491 if (!closed) {
6492 /* ^^^ optimization: saving may already
6493 * have closed it. If not... */
6494 close(redir->rd_fd);
6495 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006496 } else {
6497 xdup2(openfd, redir->rd_fd);
6498 if (redir->rd_dup == REDIRFD_TO_FILE)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006499 /* "rd_fd > FILE" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006500 close(openfd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006501 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006502 }
6503 }
6504 }
6505 return 0;
6506}
6507
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006508static char *find_in_path(const char *arg)
6509{
6510 char *ret = NULL;
6511 const char *PATH = get_local_var_value("PATH");
6512
6513 if (!PATH)
6514 return NULL;
6515
6516 while (1) {
6517 const char *end = strchrnul(PATH, ':');
6518 int sz = end - PATH; /* must be int! */
6519
6520 free(ret);
6521 if (sz != 0) {
6522 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6523 } else {
6524 /* We have xxx::yyyy in $PATH,
6525 * it means "use current dir" */
6526 ret = xstrdup(arg);
6527 }
6528 if (access(ret, F_OK) == 0)
6529 break;
6530
6531 if (*end == '\0') {
6532 free(ret);
6533 return NULL;
6534 }
6535 PATH = end + 1;
6536 }
6537
6538 return ret;
6539}
6540
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006541static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006542 const struct built_in_command *x,
6543 const struct built_in_command *end)
6544{
6545 while (x != end) {
6546 if (strcmp(name, x->b_cmd) != 0) {
6547 x++;
6548 continue;
6549 }
6550 debug_printf_exec("found builtin '%s'\n", name);
6551 return x;
6552 }
6553 return NULL;
6554}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006555static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006556{
6557 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6558}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006559static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006560{
6561 const struct built_in_command *x = find_builtin1(name);
6562 if (x)
6563 return x;
6564 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6565}
6566
6567#if ENABLE_HUSH_FUNCTIONS
6568static struct function **find_function_slot(const char *name)
6569{
6570 struct function **funcpp = &G.top_func;
6571 while (*funcpp) {
6572 if (strcmp(name, (*funcpp)->name) == 0) {
6573 break;
6574 }
6575 funcpp = &(*funcpp)->next;
6576 }
6577 return funcpp;
6578}
6579
6580static const struct function *find_function(const char *name)
6581{
6582 const struct function *funcp = *find_function_slot(name);
6583 if (funcp)
6584 debug_printf_exec("found function '%s'\n", name);
6585 return funcp;
6586}
6587
6588/* Note: takes ownership on name ptr */
6589static struct function *new_function(char *name)
6590{
6591 struct function **funcpp = find_function_slot(name);
6592 struct function *funcp = *funcpp;
6593
6594 if (funcp != NULL) {
6595 struct command *cmd = funcp->parent_cmd;
6596 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6597 if (!cmd) {
6598 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6599 free(funcp->name);
6600 /* Note: if !funcp->body, do not free body_as_string!
6601 * This is a special case of "-F name body" function:
6602 * body_as_string was not malloced! */
6603 if (funcp->body) {
6604 free_pipe_list(funcp->body);
6605# if !BB_MMU
6606 free(funcp->body_as_string);
6607# endif
6608 }
6609 } else {
6610 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6611 cmd->argv[0] = funcp->name;
6612 cmd->group = funcp->body;
6613# if !BB_MMU
6614 cmd->group_as_string = funcp->body_as_string;
6615# endif
6616 }
6617 } else {
6618 debug_printf_exec("remembering new function '%s'\n", name);
6619 funcp = *funcpp = xzalloc(sizeof(*funcp));
6620 /*funcp->next = NULL;*/
6621 }
6622
6623 funcp->name = name;
6624 return funcp;
6625}
6626
6627static void unset_func(const char *name)
6628{
6629 struct function **funcpp = find_function_slot(name);
6630 struct function *funcp = *funcpp;
6631
6632 if (funcp != NULL) {
6633 debug_printf_exec("freeing function '%s'\n", funcp->name);
6634 *funcpp = funcp->next;
6635 /* funcp is unlinked now, deleting it.
6636 * Note: if !funcp->body, the function was created by
6637 * "-F name body", do not free ->body_as_string
6638 * and ->name as they were not malloced. */
6639 if (funcp->body) {
6640 free_pipe_list(funcp->body);
6641 free(funcp->name);
6642# if !BB_MMU
6643 free(funcp->body_as_string);
6644# endif
6645 }
6646 free(funcp);
6647 }
6648}
6649
6650# if BB_MMU
6651#define exec_function(to_free, funcp, argv) \
6652 exec_function(funcp, argv)
6653# endif
6654static void exec_function(char ***to_free,
6655 const struct function *funcp,
6656 char **argv) NORETURN;
6657static void exec_function(char ***to_free,
6658 const struct function *funcp,
6659 char **argv)
6660{
6661# if BB_MMU
6662 int n = 1;
6663
6664 argv[0] = G.global_argv[0];
6665 G.global_argv = argv;
6666 while (*++argv)
6667 n++;
6668 G.global_argc = n;
6669 /* On MMU, funcp->body is always non-NULL */
6670 n = run_list(funcp->body);
6671 fflush_all();
6672 _exit(n);
6673# else
6674 re_execute_shell(to_free,
6675 funcp->body_as_string,
6676 G.global_argv[0],
6677 argv + 1,
6678 NULL);
6679# endif
6680}
6681
6682static int run_function(const struct function *funcp, char **argv)
6683{
6684 int rc;
6685 save_arg_t sv;
6686 smallint sv_flg;
6687
6688 save_and_replace_G_args(&sv, argv);
6689
6690 /* "we are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006691 sv_flg = G_flag_return_in_progress;
6692 G_flag_return_in_progress = -1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006693# if ENABLE_HUSH_LOCAL
6694 G.func_nest_level++;
6695# endif
6696
6697 /* On MMU, funcp->body is always non-NULL */
6698# if !BB_MMU
6699 if (!funcp->body) {
6700 /* Function defined by -F */
6701 parse_and_run_string(funcp->body_as_string);
6702 rc = G.last_exitcode;
6703 } else
6704# endif
6705 {
6706 rc = run_list(funcp->body);
6707 }
6708
6709# if ENABLE_HUSH_LOCAL
6710 {
6711 struct variable *var;
6712 struct variable **var_pp;
6713
6714 var_pp = &G.top_var;
6715 while ((var = *var_pp) != NULL) {
6716 if (var->func_nest_level < G.func_nest_level) {
6717 var_pp = &var->next;
6718 continue;
6719 }
6720 /* Unexport */
6721 if (var->flg_export)
6722 bb_unsetenv(var->varstr);
6723 /* Remove from global list */
6724 *var_pp = var->next;
6725 /* Free */
6726 if (!var->max_len)
6727 free(var->varstr);
6728 free(var);
6729 }
6730 G.func_nest_level--;
6731 }
6732# endif
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006733 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006734
6735 restore_G_args(&sv, argv);
6736
6737 return rc;
6738}
6739#endif /* ENABLE_HUSH_FUNCTIONS */
6740
6741
6742#if BB_MMU
6743#define exec_builtin(to_free, x, argv) \
6744 exec_builtin(x, argv)
6745#else
6746#define exec_builtin(to_free, x, argv) \
6747 exec_builtin(to_free, argv)
6748#endif
6749static void exec_builtin(char ***to_free,
6750 const struct built_in_command *x,
6751 char **argv) NORETURN;
6752static void exec_builtin(char ***to_free,
6753 const struct built_in_command *x,
6754 char **argv)
6755{
6756#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006757 int rcode;
6758 fflush_all();
6759 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006760 fflush_all();
6761 _exit(rcode);
6762#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006763 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006764 /* On NOMMU, we must never block!
6765 * Example: { sleep 99 | read line; } & echo Ok
6766 */
6767 re_execute_shell(to_free,
6768 argv[0],
6769 G.global_argv[0],
6770 G.global_argv + 1,
6771 argv);
6772#endif
6773}
6774
6775
6776static void execvp_or_die(char **argv) NORETURN;
6777static void execvp_or_die(char **argv)
6778{
Denys Vlasenko04465da2016-10-03 01:01:15 +02006779 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006780 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006781 /* Don't propagate SIG_IGN to the child */
6782 if (SPECIAL_JOBSTOP_SIGS != 0)
6783 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006784 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02006785 e = 2;
6786 if (errno == EACCES) e = 126;
6787 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006788 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02006789 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006790}
6791
6792#if ENABLE_HUSH_MODE_X
6793static void dump_cmd_in_x_mode(char **argv)
6794{
6795 if (G_x_mode && argv) {
6796 /* We want to output the line in one write op */
6797 char *buf, *p;
6798 int len;
6799 int n;
6800
6801 len = 3;
6802 n = 0;
6803 while (argv[n])
6804 len += strlen(argv[n++]) + 1;
6805 buf = xmalloc(len);
6806 buf[0] = '+';
6807 p = buf + 1;
6808 n = 0;
6809 while (argv[n])
6810 p += sprintf(p, " %s", argv[n++]);
6811 *p++ = '\n';
6812 *p = '\0';
6813 fputs(buf, stderr);
6814 free(buf);
6815 }
6816}
6817#else
6818# define dump_cmd_in_x_mode(argv) ((void)0)
6819#endif
6820
6821#if BB_MMU
6822#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6823 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6824#define pseudo_exec(nommu_save, command, argv_expanded) \
6825 pseudo_exec(command, argv_expanded)
6826#endif
6827
6828/* Called after [v]fork() in run_pipe, or from builtin_exec.
6829 * Never returns.
6830 * Don't exit() here. If you don't exec, use _exit instead.
6831 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006832 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006833 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006834static void pseudo_exec_argv(nommu_save_t *nommu_save,
6835 char **argv, int assignment_cnt,
6836 char **argv_expanded) NORETURN;
6837static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6838 char **argv, int assignment_cnt,
6839 char **argv_expanded)
6840{
6841 char **new_env;
6842
6843 new_env = expand_assignments(argv, assignment_cnt);
6844 dump_cmd_in_x_mode(new_env);
6845
6846 if (!argv[assignment_cnt]) {
6847 /* Case when we are here: ... | var=val | ...
6848 * (note that we do not exit early, i.e., do not optimize out
6849 * expand_assignments(): think about ... | var=`sleep 1` | ...
6850 */
6851 free_strings(new_env);
6852 _exit(EXIT_SUCCESS);
6853 }
6854
6855#if BB_MMU
6856 set_vars_and_save_old(new_env);
6857 free(new_env); /* optional */
6858 /* we can also destroy set_vars_and_save_old's return value,
6859 * to save memory */
6860#else
6861 nommu_save->new_env = new_env;
6862 nommu_save->old_vars = set_vars_and_save_old(new_env);
6863#endif
6864
6865 if (argv_expanded) {
6866 argv = argv_expanded;
6867 } else {
6868 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6869#if !BB_MMU
6870 nommu_save->argv = argv;
6871#endif
6872 }
6873 dump_cmd_in_x_mode(argv);
6874
6875#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6876 if (strchr(argv[0], '/') != NULL)
6877 goto skip;
6878#endif
6879
6880 /* Check if the command matches any of the builtins.
6881 * Depending on context, this might be redundant. But it's
6882 * easier to waste a few CPU cycles than it is to figure out
6883 * if this is one of those cases.
6884 */
6885 {
6886 /* On NOMMU, it is more expensive to re-execute shell
6887 * just in order to run echo or test builtin.
6888 * It's better to skip it here and run corresponding
6889 * non-builtin later. */
6890 const struct built_in_command *x;
6891 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6892 if (x) {
6893 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6894 }
6895 }
6896#if ENABLE_HUSH_FUNCTIONS
6897 /* Check if the command matches any functions */
6898 {
6899 const struct function *funcp = find_function(argv[0]);
6900 if (funcp) {
6901 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6902 }
6903 }
6904#endif
6905
6906#if ENABLE_FEATURE_SH_STANDALONE
6907 /* Check if the command matches any busybox applets */
6908 {
6909 int a = find_applet_by_name(argv[0]);
6910 if (a >= 0) {
6911# if BB_MMU /* see above why on NOMMU it is not allowed */
6912 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006913 /* Do not leak open fds from opened script files etc */
6914 close_all_FILE_list();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006915 debug_printf_exec("running applet '%s'\n", argv[0]);
6916 run_applet_no_and_exit(a, argv);
6917 }
6918# endif
6919 /* Re-exec ourselves */
6920 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006921 /* Don't propagate SIG_IGN to the child */
6922 if (SPECIAL_JOBSTOP_SIGS != 0)
6923 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006924 execv(bb_busybox_exec_path, argv);
6925 /* If they called chroot or otherwise made the binary no longer
6926 * executable, fall through */
6927 }
6928 }
6929#endif
6930
6931#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6932 skip:
6933#endif
6934 execvp_or_die(argv);
6935}
6936
6937/* Called after [v]fork() in run_pipe
6938 */
6939static void pseudo_exec(nommu_save_t *nommu_save,
6940 struct command *command,
6941 char **argv_expanded) NORETURN;
6942static void pseudo_exec(nommu_save_t *nommu_save,
6943 struct command *command,
6944 char **argv_expanded)
6945{
6946 if (command->argv) {
6947 pseudo_exec_argv(nommu_save, command->argv,
6948 command->assignment_cnt, argv_expanded);
6949 }
6950
6951 if (command->group) {
6952 /* Cases when we are here:
6953 * ( list )
6954 * { list } &
6955 * ... | ( list ) | ...
6956 * ... | { list } | ...
6957 */
6958#if BB_MMU
6959 int rcode;
6960 debug_printf_exec("pseudo_exec: run_list\n");
6961 reset_traps_to_defaults();
6962 rcode = run_list(command->group);
6963 /* OK to leak memory by not calling free_pipe_list,
6964 * since this process is about to exit */
6965 _exit(rcode);
6966#else
6967 re_execute_shell(&nommu_save->argv_from_re_execing,
6968 command->group_as_string,
6969 G.global_argv[0],
6970 G.global_argv + 1,
6971 NULL);
6972#endif
6973 }
6974
6975 /* Case when we are here: ... | >file */
6976 debug_printf_exec("pseudo_exec'ed null command\n");
6977 _exit(EXIT_SUCCESS);
6978}
6979
6980#if ENABLE_HUSH_JOB
6981static const char *get_cmdtext(struct pipe *pi)
6982{
6983 char **argv;
6984 char *p;
6985 int len;
6986
6987 /* This is subtle. ->cmdtext is created only on first backgrounding.
6988 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6989 * On subsequent bg argv is trashed, but we won't use it */
6990 if (pi->cmdtext)
6991 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01006992
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006993 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01006994 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006995 pi->cmdtext = xzalloc(1);
6996 return pi->cmdtext;
6997 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006998 len = 0;
6999 do {
7000 len += strlen(*argv) + 1;
7001 } while (*++argv);
7002 p = xmalloc(len);
7003 pi->cmdtext = p;
7004 argv = pi->cmds[0].argv;
7005 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007006 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007007 *p++ = ' ';
7008 } while (*++argv);
7009 p[-1] = '\0';
7010 return pi->cmdtext;
7011}
7012
7013static void insert_bg_job(struct pipe *pi)
7014{
7015 struct pipe *job, **jobp;
7016 int i;
7017
7018 /* Linear search for the ID of the job to use */
7019 pi->jobid = 1;
7020 for (job = G.job_list; job; job = job->next)
7021 if (job->jobid >= pi->jobid)
7022 pi->jobid = job->jobid + 1;
7023
7024 /* Add job to the list of running jobs */
7025 jobp = &G.job_list;
7026 while ((job = *jobp) != NULL)
7027 jobp = &job->next;
7028 job = *jobp = xmalloc(sizeof(*job));
7029
7030 *job = *pi; /* physical copy */
7031 job->next = NULL;
7032 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7033 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7034 for (i = 0; i < pi->num_cmds; i++) {
7035 job->cmds[i].pid = pi->cmds[i].pid;
7036 /* all other fields are not used and stay zero */
7037 }
7038 job->cmdtext = xstrdup(get_cmdtext(pi));
7039
7040 if (G_interactive_fd)
7041 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
7042 G.last_jobid = job->jobid;
7043}
7044
7045static void remove_bg_job(struct pipe *pi)
7046{
7047 struct pipe *prev_pipe;
7048
7049 if (pi == G.job_list) {
7050 G.job_list = pi->next;
7051 } else {
7052 prev_pipe = G.job_list;
7053 while (prev_pipe->next != pi)
7054 prev_pipe = prev_pipe->next;
7055 prev_pipe->next = pi->next;
7056 }
7057 if (G.job_list)
7058 G.last_jobid = G.job_list->jobid;
7059 else
7060 G.last_jobid = 0;
7061}
7062
7063/* Remove a backgrounded job */
7064static void delete_finished_bg_job(struct pipe *pi)
7065{
7066 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007067 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007068}
7069#endif /* JOB */
7070
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007071static int job_exited_or_stopped(struct pipe *pi)
7072{
7073 int rcode, i;
7074
7075 if (pi->alive_cmds != pi->stopped_cmds)
7076 return -1;
7077
7078 /* All processes in fg pipe have exited or stopped */
7079 rcode = 0;
7080 i = pi->num_cmds;
7081 while (--i >= 0) {
7082 rcode = pi->cmds[i].cmd_exitcode;
7083 /* usually last process gives overall exitstatus,
7084 * but with "set -o pipefail", last *failed* process does */
7085 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7086 break;
7087 }
7088 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7089 return rcode;
7090}
7091
Denys Vlasenko7e675362016-10-28 21:57:31 +02007092static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007093{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007094#if ENABLE_HUSH_JOB
7095 struct pipe *pi;
7096#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007097 int i, dead;
7098
7099 dead = WIFEXITED(status) || WIFSIGNALED(status);
7100
7101#if DEBUG_JOBS
7102 if (WIFSTOPPED(status))
7103 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7104 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7105 if (WIFSIGNALED(status))
7106 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7107 childpid, WTERMSIG(status), WEXITSTATUS(status));
7108 if (WIFEXITED(status))
7109 debug_printf_jobs("pid %d exited, exitcode %d\n",
7110 childpid, WEXITSTATUS(status));
7111#endif
7112 /* Were we asked to wait for a fg pipe? */
7113 if (fg_pipe) {
7114 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007115
Denys Vlasenko7e675362016-10-28 21:57:31 +02007116 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007117 int rcode;
7118
Denys Vlasenko7e675362016-10-28 21:57:31 +02007119 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7120 if (fg_pipe->cmds[i].pid != childpid)
7121 continue;
7122 if (dead) {
7123 int ex;
7124 fg_pipe->cmds[i].pid = 0;
7125 fg_pipe->alive_cmds--;
7126 ex = WEXITSTATUS(status);
7127 /* bash prints killer signal's name for *last*
7128 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7129 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7130 */
7131 if (WIFSIGNALED(status)) {
7132 int sig = WTERMSIG(status);
7133 if (i == fg_pipe->num_cmds-1)
7134 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7135 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7136 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7137 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7138 * Maybe we need to use sig | 128? */
7139 ex = sig + 128;
7140 }
7141 fg_pipe->cmds[i].cmd_exitcode = ex;
7142 } else {
7143 fg_pipe->stopped_cmds++;
7144 }
7145 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7146 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007147 rcode = job_exited_or_stopped(fg_pipe);
7148 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007149/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7150 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7151 * and "killall -STOP cat" */
7152 if (G_interactive_fd) {
7153#if ENABLE_HUSH_JOB
7154 if (fg_pipe->alive_cmds != 0)
7155 insert_bg_job(fg_pipe);
7156#endif
7157 return rcode;
7158 }
7159 if (fg_pipe->alive_cmds == 0)
7160 return rcode;
7161 }
7162 /* There are still running processes in the fg_pipe */
7163 return -1;
7164 }
7165 /* It wasnt in fg_pipe, look for process in bg pipes */
7166 }
7167
7168#if ENABLE_HUSH_JOB
7169 /* We were asked to wait for bg or orphaned children */
7170 /* No need to remember exitcode in this case */
7171 for (pi = G.job_list; pi; pi = pi->next) {
7172 for (i = 0; i < pi->num_cmds; i++) {
7173 if (pi->cmds[i].pid == childpid)
7174 goto found_pi_and_prognum;
7175 }
7176 }
7177 /* Happens when shell is used as init process (init=/bin/sh) */
7178 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7179 return -1; /* this wasn't a process from fg_pipe */
7180
7181 found_pi_and_prognum:
7182 if (dead) {
7183 /* child exited */
7184 pi->cmds[i].pid = 0;
7185 pi->cmds[i].cmd_exitcode = WEXITSTATUS(status);
7186 if (WIFSIGNALED(status))
7187 pi->cmds[i].cmd_exitcode = 128 + WTERMSIG(status);
7188 pi->alive_cmds--;
7189 if (!pi->alive_cmds) {
7190 if (G_interactive_fd)
7191 printf(JOB_STATUS_FORMAT, pi->jobid,
7192 "Done", pi->cmdtext);
7193 delete_finished_bg_job(pi);
7194 }
7195 } else {
7196 /* child stopped */
7197 pi->stopped_cmds++;
7198 }
7199#endif
7200 return -1; /* this wasn't a process from fg_pipe */
7201}
7202
7203/* Check to see if any processes have exited -- if they have,
7204 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007205 *
7206 * If non-NULL fg_pipe: wait for its completion or stop.
7207 * Return its exitcode or zero if stopped.
7208 *
7209 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7210 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7211 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7212 * or 0 if no children changed status.
7213 *
7214 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7215 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7216 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02007217 */
7218static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7219{
7220 int attributes;
7221 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007222 int rcode = 0;
7223
7224 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7225
7226 attributes = WUNTRACED;
7227 if (fg_pipe == NULL)
7228 attributes |= WNOHANG;
7229
7230 errno = 0;
7231#if ENABLE_HUSH_FAST
7232 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7233//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7234//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7235 /* There was neither fork nor SIGCHLD since last waitpid */
7236 /* Avoid doing waitpid syscall if possible */
7237 if (!G.we_have_children) {
7238 errno = ECHILD;
7239 return -1;
7240 }
7241 if (fg_pipe == NULL) { /* is WNOHANG set? */
7242 /* We have children, but they did not exit
7243 * or stop yet (we saw no SIGCHLD) */
7244 return 0;
7245 }
7246 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7247 }
7248#endif
7249
7250/* Do we do this right?
7251 * bash-3.00# sleep 20 | false
7252 * <ctrl-Z pressed>
7253 * [3]+ Stopped sleep 20 | false
7254 * bash-3.00# echo $?
7255 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7256 * [hush 1.14.0: yes we do it right]
7257 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007258 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007259 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007260#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02007261 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007262 i = G.count_SIGCHLD;
7263#endif
7264 childpid = waitpid(-1, &status, attributes);
7265 if (childpid <= 0) {
7266 if (childpid && errno != ECHILD)
7267 bb_perror_msg("waitpid");
7268#if ENABLE_HUSH_FAST
7269 else { /* Until next SIGCHLD, waitpid's are useless */
7270 G.we_have_children = (childpid == 0);
7271 G.handled_SIGCHLD = i;
7272//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7273 }
7274#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007275 /* ECHILD (no children), or 0 (no change in children status) */
7276 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007277 break;
7278 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007279 rcode = process_wait_result(fg_pipe, childpid, status);
7280 if (rcode >= 0) {
7281 /* fg_pipe exited or stopped */
7282 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007283 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007284 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007285 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007286 rcode = WEXITSTATUS(status);
7287 if (WIFSIGNALED(status))
7288 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007289 if (WIFSTOPPED(status))
7290 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7291 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007292 rcode++;
7293 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007294 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007295 /* This wasn't one of our processes, or */
7296 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007297 } /* while (waitpid succeeds)... */
7298
7299 return rcode;
7300}
7301
7302#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007303static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007304{
7305 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007306 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007307 if (G_saved_tty_pgrp) {
7308 /* Job finished, move the shell to the foreground */
7309 p = getpgrp(); /* our process group id */
7310 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7311 tcsetpgrp(G_interactive_fd, p);
7312 }
7313 return rcode;
7314}
7315#endif
7316
7317/* Start all the jobs, but don't wait for anything to finish.
7318 * See checkjobs().
7319 *
7320 * Return code is normally -1, when the caller has to wait for children
7321 * to finish to determine the exit status of the pipe. If the pipe
7322 * is a simple builtin command, however, the action is done by the
7323 * time run_pipe returns, and the exit code is provided as the
7324 * return value.
7325 *
7326 * Returns -1 only if started some children. IOW: we have to
7327 * mask out retvals of builtins etc with 0xff!
7328 *
7329 * The only case when we do not need to [v]fork is when the pipe
7330 * is single, non-backgrounded, non-subshell command. Examples:
7331 * cmd ; ... { list } ; ...
7332 * cmd && ... { list } && ...
7333 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007334 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007335 * or (if SH_STANDALONE) an applet, and we can run the { list }
7336 * with run_list. If it isn't one of these, we fork and exec cmd.
7337 *
7338 * Cases when we must fork:
7339 * non-single: cmd | cmd
7340 * backgrounded: cmd & { list } &
7341 * subshell: ( list ) [&]
7342 */
7343#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01007344#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007345 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7346#endif
7347static int redirect_and_varexp_helper(char ***new_env_p,
7348 struct variable **old_vars_p,
7349 struct command *command,
7350 int squirrel[3],
7351 char **argv_expanded)
7352{
7353 /* setup_redirects acts on file descriptors, not FILEs.
7354 * This is perfect for work that comes after exec().
7355 * Is it really safe for inline use? Experimentally,
7356 * things seem to work. */
7357 int rcode = setup_redirects(command, squirrel);
7358 if (rcode == 0) {
7359 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7360 *new_env_p = new_env;
7361 dump_cmd_in_x_mode(new_env);
7362 dump_cmd_in_x_mode(argv_expanded);
7363 if (old_vars_p)
7364 *old_vars_p = set_vars_and_save_old(new_env);
7365 }
7366 return rcode;
7367}
7368static NOINLINE int run_pipe(struct pipe *pi)
7369{
7370 static const char *const null_ptr = NULL;
7371
7372 int cmd_no;
7373 int next_infd;
7374 struct command *command;
7375 char **argv_expanded;
7376 char **argv;
7377 /* it is not always needed, but we aim to smaller code */
7378 int squirrel[] = { -1, -1, -1 };
7379 int rcode;
7380
7381 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7382 debug_enter();
7383
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007384 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7385 * Result should be 3 lines: q w e, qwe, q w e
7386 */
7387 G.ifs = get_local_var_value("IFS");
7388 if (!G.ifs)
7389 G.ifs = defifs;
7390
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007391 IF_HUSH_JOB(pi->pgrp = -1;)
7392 pi->stopped_cmds = 0;
7393 command = &pi->cmds[0];
7394 argv_expanded = NULL;
7395
7396 if (pi->num_cmds != 1
7397 || pi->followup == PIPE_BG
7398 || command->cmd_type == CMD_SUBSHELL
7399 ) {
7400 goto must_fork;
7401 }
7402
7403 pi->alive_cmds = 1;
7404
7405 debug_printf_exec(": group:%p argv:'%s'\n",
7406 command->group, command->argv ? command->argv[0] : "NONE");
7407
7408 if (command->group) {
7409#if ENABLE_HUSH_FUNCTIONS
7410 if (command->cmd_type == CMD_FUNCDEF) {
7411 /* "executing" func () { list } */
7412 struct function *funcp;
7413
7414 funcp = new_function(command->argv[0]);
7415 /* funcp->name is already set to argv[0] */
7416 funcp->body = command->group;
7417# if !BB_MMU
7418 funcp->body_as_string = command->group_as_string;
7419 command->group_as_string = NULL;
7420# endif
7421 command->group = NULL;
7422 command->argv[0] = NULL;
7423 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7424 funcp->parent_cmd = command;
7425 command->child_func = funcp;
7426
7427 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7428 debug_leave();
7429 return EXIT_SUCCESS;
7430 }
7431#endif
7432 /* { list } */
7433 debug_printf("non-subshell group\n");
7434 rcode = 1; /* exitcode if redir failed */
7435 if (setup_redirects(command, squirrel) == 0) {
7436 debug_printf_exec(": run_list\n");
7437 rcode = run_list(command->group) & 0xff;
7438 }
7439 restore_redirects(squirrel);
7440 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7441 debug_leave();
7442 debug_printf_exec("run_pipe: return %d\n", rcode);
7443 return rcode;
7444 }
7445
7446 argv = command->argv ? command->argv : (char **) &null_ptr;
7447 {
7448 const struct built_in_command *x;
7449#if ENABLE_HUSH_FUNCTIONS
7450 const struct function *funcp;
7451#else
7452 enum { funcp = 0 };
7453#endif
7454 char **new_env = NULL;
7455 struct variable *old_vars = NULL;
7456
7457 if (argv[command->assignment_cnt] == NULL) {
7458 /* Assignments, but no command */
7459 /* Ensure redirects take effect (that is, create files).
7460 * Try "a=t >file" */
7461#if 0 /* A few cases in testsuite fail with this code. FIXME */
7462 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7463 /* Set shell variables */
7464 if (new_env) {
7465 argv = new_env;
7466 while (*argv) {
7467 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7468 /* Do we need to flag set_local_var() errors?
7469 * "assignment to readonly var" and "putenv error"
7470 */
7471 argv++;
7472 }
7473 }
7474 /* Redirect error sets $? to 1. Otherwise,
7475 * if evaluating assignment value set $?, retain it.
7476 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7477 if (rcode == 0)
7478 rcode = G.last_exitcode;
7479 /* Exit, _skipping_ variable restoring code: */
7480 goto clean_up_and_ret0;
7481
7482#else /* Older, bigger, but more correct code */
7483
7484 rcode = setup_redirects(command, squirrel);
7485 restore_redirects(squirrel);
7486 /* Set shell variables */
7487 if (G_x_mode)
7488 bb_putchar_stderr('+');
7489 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007490 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007491 if (G_x_mode)
7492 fprintf(stderr, " %s", p);
7493 debug_printf_exec("set shell var:'%s'->'%s'\n",
7494 *argv, p);
7495 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7496 /* Do we need to flag set_local_var() errors?
7497 * "assignment to readonly var" and "putenv error"
7498 */
7499 argv++;
7500 }
7501 if (G_x_mode)
7502 bb_putchar_stderr('\n');
7503 /* Redirect error sets $? to 1. Otherwise,
7504 * if evaluating assignment value set $?, retain it.
7505 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7506 if (rcode == 0)
7507 rcode = G.last_exitcode;
7508 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7509 debug_leave();
7510 debug_printf_exec("run_pipe: return %d\n", rcode);
7511 return rcode;
7512#endif
7513 }
7514
7515 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007516#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007517 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007518 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007519 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007520#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007521 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007522 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7523 }
7524
7525 /* if someone gives us an empty string: `cmd with empty output` */
7526 if (!argv_expanded[0]) {
7527 free(argv_expanded);
7528 debug_leave();
7529 return G.last_exitcode;
7530 }
7531
7532 x = find_builtin(argv_expanded[0]);
7533#if ENABLE_HUSH_FUNCTIONS
7534 funcp = NULL;
7535 if (!x)
7536 funcp = find_function(argv_expanded[0]);
7537#endif
7538 if (x || funcp) {
7539 if (!funcp) {
7540 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7541 debug_printf("exec with redirects only\n");
7542 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007543 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007544 goto clean_up_and_ret1;
7545 }
7546 }
7547 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7548 if (rcode == 0) {
7549 if (!funcp) {
7550 debug_printf_exec(": builtin '%s' '%s'...\n",
7551 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007552 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007553 rcode = x->b_function(argv_expanded) & 0xff;
7554 fflush_all();
7555 }
7556#if ENABLE_HUSH_FUNCTIONS
7557 else {
7558# if ENABLE_HUSH_LOCAL
7559 struct variable **sv;
7560 sv = G.shadowed_vars_pp;
7561 G.shadowed_vars_pp = &old_vars;
7562# endif
7563 debug_printf_exec(": function '%s' '%s'...\n",
7564 funcp->name, argv_expanded[1]);
7565 rcode = run_function(funcp, argv_expanded) & 0xff;
7566# if ENABLE_HUSH_LOCAL
7567 G.shadowed_vars_pp = sv;
7568# endif
7569 }
7570#endif
7571 }
7572 clean_up_and_ret:
7573 unset_vars(new_env);
7574 add_vars(old_vars);
7575/* clean_up_and_ret0: */
7576 restore_redirects(squirrel);
7577 clean_up_and_ret1:
7578 free(argv_expanded);
7579 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7580 debug_leave();
7581 debug_printf_exec("run_pipe return %d\n", rcode);
7582 return rcode;
7583 }
7584
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007585 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007586 int n = find_applet_by_name(argv_expanded[0]);
7587 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7588 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7589 if (rcode == 0) {
7590 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7591 argv_expanded[0], argv_expanded[1]);
7592 rcode = run_nofork_applet(n, argv_expanded);
7593 }
7594 goto clean_up_and_ret;
7595 }
7596 }
7597 /* It is neither builtin nor applet. We must fork. */
7598 }
7599
7600 must_fork:
7601 /* NB: argv_expanded may already be created, and that
7602 * might include `cmd` runs! Do not rerun it! We *must*
7603 * use argv_expanded if it's non-NULL */
7604
7605 /* Going to fork a child per each pipe member */
7606 pi->alive_cmds = 0;
7607 next_infd = 0;
7608
7609 cmd_no = 0;
7610 while (cmd_no < pi->num_cmds) {
7611 struct fd_pair pipefds;
7612#if !BB_MMU
7613 volatile nommu_save_t nommu_save;
7614 nommu_save.new_env = NULL;
7615 nommu_save.old_vars = NULL;
7616 nommu_save.argv = NULL;
7617 nommu_save.argv_from_re_execing = NULL;
7618#endif
7619 command = &pi->cmds[cmd_no];
7620 cmd_no++;
7621 if (command->argv) {
7622 debug_printf_exec(": pipe member '%s' '%s'...\n",
7623 command->argv[0], command->argv[1]);
7624 } else {
7625 debug_printf_exec(": pipe member with no argv\n");
7626 }
7627
7628 /* pipes are inserted between pairs of commands */
7629 pipefds.rd = 0;
7630 pipefds.wr = 1;
7631 if (cmd_no < pi->num_cmds)
7632 xpiped_pair(pipefds);
7633
7634 command->pid = BB_MMU ? fork() : vfork();
7635 if (!command->pid) { /* child */
7636#if ENABLE_HUSH_JOB
7637 disable_restore_tty_pgrp_on_exit();
7638 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7639
7640 /* Every child adds itself to new process group
7641 * with pgid == pid_of_first_child_in_pipe */
7642 if (G.run_list_level == 1 && G_interactive_fd) {
7643 pid_t pgrp;
7644 pgrp = pi->pgrp;
7645 if (pgrp < 0) /* true for 1st process only */
7646 pgrp = getpid();
7647 if (setpgid(0, pgrp) == 0
7648 && pi->followup != PIPE_BG
7649 && G_saved_tty_pgrp /* we have ctty */
7650 ) {
7651 /* We do it in *every* child, not just first,
7652 * to avoid races */
7653 tcsetpgrp(G_interactive_fd, pgrp);
7654 }
7655 }
7656#endif
7657 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7658 /* 1st cmd in backgrounded pipe
7659 * should have its stdin /dev/null'ed */
7660 close(0);
7661 if (open(bb_dev_null, O_RDONLY))
7662 xopen("/", O_RDONLY);
7663 } else {
7664 xmove_fd(next_infd, 0);
7665 }
7666 xmove_fd(pipefds.wr, 1);
7667 if (pipefds.rd > 1)
7668 close(pipefds.rd);
7669 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02007670 * and the pipe fd (fd#1) is available for dup'ing:
7671 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7672 * of cmd1 goes into pipe.
7673 */
7674 if (setup_redirects(command, NULL)) {
7675 /* Happens when redir file can't be opened:
7676 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7677 * FOO
7678 * hush: can't open '/qwe/rty': No such file or directory
7679 * BAZ
7680 * (echo BAR is not executed, it hits _exit(1) below)
7681 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007682 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007683 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007684
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007685 /* Stores to nommu_save list of env vars putenv'ed
7686 * (NOMMU, on MMU we don't need that) */
7687 /* cast away volatility... */
7688 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7689 /* pseudo_exec() does not return */
7690 }
7691
7692 /* parent or error */
7693#if ENABLE_HUSH_FAST
7694 G.count_SIGCHLD++;
7695//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7696#endif
7697 enable_restore_tty_pgrp_on_exit();
7698#if !BB_MMU
7699 /* Clean up after vforked child */
7700 free(nommu_save.argv);
7701 free(nommu_save.argv_from_re_execing);
7702 unset_vars(nommu_save.new_env);
7703 add_vars(nommu_save.old_vars);
7704#endif
7705 free(argv_expanded);
7706 argv_expanded = NULL;
7707 if (command->pid < 0) { /* [v]fork failed */
7708 /* Clearly indicate, was it fork or vfork */
7709 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7710 } else {
7711 pi->alive_cmds++;
7712#if ENABLE_HUSH_JOB
7713 /* Second and next children need to know pid of first one */
7714 if (pi->pgrp < 0)
7715 pi->pgrp = command->pid;
7716#endif
7717 }
7718
7719 if (cmd_no > 1)
7720 close(next_infd);
7721 if (cmd_no < pi->num_cmds)
7722 close(pipefds.wr);
7723 /* Pass read (output) pipe end to next iteration */
7724 next_infd = pipefds.rd;
7725 }
7726
7727 if (!pi->alive_cmds) {
7728 debug_leave();
7729 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7730 return 1;
7731 }
7732
7733 debug_leave();
7734 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7735 return -1;
7736}
7737
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007738/* NB: called by pseudo_exec, and therefore must not modify any
7739 * global data until exec/_exit (we can be a child after vfork!) */
7740static int run_list(struct pipe *pi)
7741{
7742#if ENABLE_HUSH_CASE
7743 char *case_word = NULL;
7744#endif
7745#if ENABLE_HUSH_LOOPS
7746 struct pipe *loop_top = NULL;
7747 char **for_lcur = NULL;
7748 char **for_list = NULL;
7749#endif
7750 smallint last_followup;
7751 smalluint rcode;
7752#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7753 smalluint cond_code = 0;
7754#else
7755 enum { cond_code = 0 };
7756#endif
7757#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007758 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007759 smallint last_rword; /* ditto */
7760#endif
7761
7762 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7763 debug_enter();
7764
7765#if ENABLE_HUSH_LOOPS
7766 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007767 {
7768 struct pipe *cpipe;
7769 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7770 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7771 continue;
7772 /* current word is FOR or IN (BOLD in comments below) */
7773 if (cpipe->next == NULL) {
7774 syntax_error("malformed for");
7775 debug_leave();
7776 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7777 return 1;
7778 }
7779 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7780 if (cpipe->next->res_word == RES_DO)
7781 continue;
7782 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7783 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7784 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7785 ) {
7786 syntax_error("malformed for");
7787 debug_leave();
7788 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7789 return 1;
7790 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007791 }
7792 }
7793#endif
7794
7795 /* Past this point, all code paths should jump to ret: label
7796 * in order to return, no direct "return" statements please.
7797 * This helps to ensure that no memory is leaked. */
7798
7799#if ENABLE_HUSH_JOB
7800 G.run_list_level++;
7801#endif
7802
7803#if HAS_KEYWORDS
7804 rword = RES_NONE;
7805 last_rword = RES_XXXX;
7806#endif
7807 last_followup = PIPE_SEQ;
7808 rcode = G.last_exitcode;
7809
7810 /* Go through list of pipes, (maybe) executing them. */
7811 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007812 int r;
7813
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007814 if (G.flag_SIGINT)
7815 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007816 if (G_flag_return_in_progress == 1)
7817 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007818
7819 IF_HAS_KEYWORDS(rword = pi->res_word;)
7820 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7821 rword, cond_code, last_rword);
7822#if ENABLE_HUSH_LOOPS
7823 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7824 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7825 ) {
7826 /* start of a loop: remember where loop starts */
7827 loop_top = pi;
7828 G.depth_of_loop++;
7829 }
7830#endif
7831 /* Still in the same "if...", "then..." or "do..." branch? */
7832 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7833 if ((rcode == 0 && last_followup == PIPE_OR)
7834 || (rcode != 0 && last_followup == PIPE_AND)
7835 ) {
7836 /* It is "<true> || CMD" or "<false> && CMD"
7837 * and we should not execute CMD */
7838 debug_printf_exec("skipped cmd because of || or &&\n");
7839 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02007840 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007841 }
7842 }
7843 last_followup = pi->followup;
7844 IF_HAS_KEYWORDS(last_rword = rword;)
7845#if ENABLE_HUSH_IF
7846 if (cond_code) {
7847 if (rword == RES_THEN) {
7848 /* if false; then ... fi has exitcode 0! */
7849 G.last_exitcode = rcode = EXIT_SUCCESS;
7850 /* "if <false> THEN cmd": skip cmd */
7851 continue;
7852 }
7853 } else {
7854 if (rword == RES_ELSE || rword == RES_ELIF) {
7855 /* "if <true> then ... ELSE/ELIF cmd":
7856 * skip cmd and all following ones */
7857 break;
7858 }
7859 }
7860#endif
7861#if ENABLE_HUSH_LOOPS
7862 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7863 if (!for_lcur) {
7864 /* first loop through for */
7865
7866 static const char encoded_dollar_at[] ALIGN1 = {
7867 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7868 }; /* encoded representation of "$@" */
7869 static const char *const encoded_dollar_at_argv[] = {
7870 encoded_dollar_at, NULL
7871 }; /* argv list with one element: "$@" */
7872 char **vals;
7873
7874 vals = (char**)encoded_dollar_at_argv;
7875 if (pi->next->res_word == RES_IN) {
7876 /* if no variable values after "in" we skip "for" */
7877 if (!pi->next->cmds[0].argv) {
7878 G.last_exitcode = rcode = EXIT_SUCCESS;
7879 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7880 break;
7881 }
7882 vals = pi->next->cmds[0].argv;
7883 } /* else: "for var; do..." -> assume "$@" list */
7884 /* create list of variable values */
7885 debug_print_strings("for_list made from", vals);
7886 for_list = expand_strvec_to_strvec(vals);
7887 for_lcur = for_list;
7888 debug_print_strings("for_list", for_list);
7889 }
7890 if (!*for_lcur) {
7891 /* "for" loop is over, clean up */
7892 free(for_list);
7893 for_list = NULL;
7894 for_lcur = NULL;
7895 break;
7896 }
7897 /* Insert next value from for_lcur */
7898 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7899 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7900 continue;
7901 }
7902 if (rword == RES_IN) {
7903 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7904 }
7905 if (rword == RES_DONE) {
7906 continue; /* "done" has no cmds too */
7907 }
7908#endif
7909#if ENABLE_HUSH_CASE
7910 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007911 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007912 case_word = expand_strvec_to_string(pi->cmds->argv);
7913 continue;
7914 }
7915 if (rword == RES_MATCH) {
7916 char **argv;
7917
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007918 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007919 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7920 break;
7921 /* all prev words didn't match, does this one match? */
7922 argv = pi->cmds->argv;
7923 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007924 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007925 /* TODO: which FNM_xxx flags to use? */
7926 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7927 free(pattern);
7928 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007929 free(case_word);
7930 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007931 break;
7932 }
7933 argv++;
7934 }
7935 continue;
7936 }
7937 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007938 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007939 if (cond_code != 0)
7940 continue; /* not matched yet, skip this pipe */
7941 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007942 if (rword == RES_ESAC) {
7943 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
7944 if (case_word) {
7945 /* "case" did not match anything: still set $? (to 0) */
7946 G.last_exitcode = rcode = EXIT_SUCCESS;
7947 }
7948 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007949#endif
7950 /* Just pressing <enter> in shell should check for jobs.
7951 * OTOH, in non-interactive shell this is useless
7952 * and only leads to extra job checks */
7953 if (pi->num_cmds == 0) {
7954 if (G_interactive_fd)
7955 goto check_jobs_and_continue;
7956 continue;
7957 }
7958
7959 /* After analyzing all keywords and conditions, we decided
7960 * to execute this pipe. NB: have to do checkjobs(NULL)
7961 * after run_pipe to collect any background children,
7962 * even if list execution is to be stopped. */
7963 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007964#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007965 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007966#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007967 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
7968 if (r != -1) {
7969 /* We ran a builtin, function, or group.
7970 * rcode is already known
7971 * and we don't need to wait for anything. */
7972 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7973 G.last_exitcode = rcode;
7974 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007975#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007976 /* Was it "break" or "continue"? */
7977 if (G.flag_break_continue) {
7978 smallint fbc = G.flag_break_continue;
7979 /* We might fall into outer *loop*,
7980 * don't want to break it too */
7981 if (loop_top) {
7982 G.depth_break_continue--;
7983 if (G.depth_break_continue == 0)
7984 G.flag_break_continue = 0;
7985 /* else: e.g. "continue 2" should *break* once, *then* continue */
7986 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7987 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007988 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007989 break;
7990 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007991 /* "continue": simulate end of loop */
7992 rword = RES_DONE;
7993 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007994 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007995#endif
7996 if (G_flag_return_in_progress == 1) {
7997 checkjobs(NULL, 0 /*(no pid to wait for)*/);
7998 break;
7999 }
8000 } else if (pi->followup == PIPE_BG) {
8001 /* What does bash do with attempts to background builtins? */
8002 /* even bash 3.2 doesn't do that well with nested bg:
8003 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8004 * I'm NOT treating inner &'s as jobs */
8005#if ENABLE_HUSH_JOB
8006 if (G.run_list_level == 1)
8007 insert_bg_job(pi);
8008#endif
8009 /* Last command's pid goes to $! */
8010 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8011 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8012/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash says 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008013 rcode = EXIT_SUCCESS;
8014 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008015 } else {
8016#if ENABLE_HUSH_JOB
8017 if (G.run_list_level == 1 && G_interactive_fd) {
8018 /* Waits for completion, then fg's main shell */
8019 rcode = checkjobs_and_fg_shell(pi);
8020 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008021 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008022 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008023#endif
8024 /* This one just waits for completion */
8025 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8026 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8027 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008028 G.last_exitcode = rcode;
8029 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008030 }
8031
8032 /* Analyze how result affects subsequent commands */
8033#if ENABLE_HUSH_IF
8034 if (rword == RES_IF || rword == RES_ELIF)
8035 cond_code = rcode;
8036#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008037 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008038 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008039 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008040#if ENABLE_HUSH_LOOPS
8041 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008042 if (pi->next
8043 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008044 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008045 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008046 if (rword == RES_WHILE) {
8047 if (rcode) {
8048 /* "while false; do...done" - exitcode 0 */
8049 G.last_exitcode = rcode = EXIT_SUCCESS;
8050 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008051 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008052 }
8053 }
8054 if (rword == RES_UNTIL) {
8055 if (!rcode) {
8056 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008057 break;
8058 }
8059 }
8060 }
8061#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008062 } /* for (pi) */
8063
8064#if ENABLE_HUSH_JOB
8065 G.run_list_level--;
8066#endif
8067#if ENABLE_HUSH_LOOPS
8068 if (loop_top)
8069 G.depth_of_loop--;
8070 free(for_list);
8071#endif
8072#if ENABLE_HUSH_CASE
8073 free(case_word);
8074#endif
8075 debug_leave();
8076 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8077 return rcode;
8078}
8079
8080/* Select which version we will use */
8081static int run_and_free_list(struct pipe *pi)
8082{
8083 int rcode = 0;
8084 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08008085 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008086 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8087 rcode = run_list(pi);
8088 }
8089 /* free_pipe_list has the side effect of clearing memory.
8090 * In the long run that function can be merged with run_list,
8091 * but doing that now would hobble the debugging effort. */
8092 free_pipe_list(pi);
8093 debug_printf_exec("run_and_free_list return %d\n", rcode);
8094 return rcode;
8095}
8096
8097
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008098static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00008099{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008100 sighandler_t old_handler;
8101 unsigned sig = 0;
8102 while ((mask >>= 1) != 0) {
8103 sig++;
8104 if (!(mask & 1))
8105 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02008106 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008107 /* POSIX allows shell to re-enable SIGCHLD
8108 * even if it was SIG_IGN on entry.
8109 * Therefore we skip IGN check for it:
8110 */
8111 if (sig == SIGCHLD)
8112 continue;
8113 if (old_handler == SIG_IGN) {
8114 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008115 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008116 if (!G.traps)
8117 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8118 free(G.traps[sig]);
8119 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
8120 }
8121 }
8122}
8123
8124/* Called a few times only (or even once if "sh -c") */
8125static void install_special_sighandlers(void)
8126{
Denis Vlasenkof9375282009-04-05 19:13:39 +00008127 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008128
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008129 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008130 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008131 if (G_interactive_fd) {
8132 mask |= SPECIAL_INTERACTIVE_SIGS;
8133 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008134 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008135 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008136 /* Careful, do not re-install handlers we already installed */
8137 if (G.special_sig_mask != mask) {
8138 unsigned diff = mask & ~G.special_sig_mask;
8139 G.special_sig_mask = mask;
8140 install_sighandlers(diff);
8141 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008142}
8143
8144#if ENABLE_HUSH_JOB
8145/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008146/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008147static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00008148{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008149 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008150
8151 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008152 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01008153 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8154 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008155 + (1 << SIGBUS ) * HUSH_DEBUG
8156 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01008157 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008158 + (1 << SIGABRT)
8159 /* bash 3.2 seems to handle these just like 'fatal' ones */
8160 + (1 << SIGPIPE)
8161 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008162 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008163 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008164 * we never want to restore pgrp on exit, and this fn is not called
8165 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008166 /*+ (1 << SIGHUP )*/
8167 /*+ (1 << SIGTERM)*/
8168 /*+ (1 << SIGINT )*/
8169 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008170 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008171
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008172 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008173}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00008174#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00008175
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008176static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00008177{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008178 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008179 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008180 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08008181 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008182 break;
8183 case 'x':
8184 IF_HUSH_MODE_X(G_x_mode = state;)
8185 break;
8186 case 'o':
8187 if (!o_opt) {
8188 /* "set -+o" without parameter.
8189 * in bash, set -o produces this output:
8190 * pipefail off
8191 * and set +o:
8192 * set +o pipefail
8193 * We always use the second form.
8194 */
8195 const char *p = o_opt_strings;
8196 idx = 0;
8197 while (*p) {
8198 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8199 idx++;
8200 p += strlen(p) + 1;
8201 }
8202 break;
8203 }
8204 idx = index_in_strings(o_opt_strings, o_opt);
8205 if (idx >= 0) {
8206 G.o_opt[idx] = state;
8207 break;
8208 }
8209 default:
8210 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008211 }
8212 return EXIT_SUCCESS;
8213}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008214
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00008215int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00008216int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00008217{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008218 enum {
8219 OPT_login = (1 << 0),
8220 };
8221 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00008222 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008223 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008224 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008225 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008226 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00008227
Denis Vlasenko574f2f42008-02-27 18:41:59 +00008228 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02008229 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008230 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008231
Denys Vlasenko10c01312011-05-11 11:49:21 +02008232#if ENABLE_HUSH_FAST
8233 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8234#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008235#if !BB_MMU
8236 G.argv0_for_re_execing = argv[0];
8237#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008238 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008239 shell_ver = xzalloc(sizeof(*shell_ver));
8240 shell_ver->flg_export = 1;
8241 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02008242 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02008243 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008244 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02008245 /* Create shell local variables from the values
8246 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00008247 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008248 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008249 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008250 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008251 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008252 if (e) while (*e) {
8253 char *value = strchr(*e, '=');
8254 if (value) { /* paranoia */
8255 cur_var->next = xzalloc(sizeof(*cur_var));
8256 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00008257 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008258 cur_var->max_len = strlen(*e);
8259 cur_var->flg_export = 1;
8260 }
8261 e++;
8262 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02008263 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008264 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8265 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02008266
8267 /* Export PWD */
8268 set_pwd_var(/*exp:*/ 1);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008269
8270#if ENABLE_HUSH_BASH_COMPAT
8271 /* Set (but not export) HOSTNAME unless already set */
8272 if (!get_local_var_value("HOSTNAME")) {
8273 struct utsname uts;
8274 uname(&uts);
8275 set_local_var_from_halves("HOSTNAME", uts.nodename);
8276 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008277 /* bash also exports SHLVL and _,
8278 * and sets (but doesn't export) the following variables:
8279 * BASH=/bin/bash
8280 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8281 * BASH_VERSION='3.2.0(1)-release'
8282 * HOSTTYPE=i386
8283 * MACHTYPE=i386-pc-linux-gnu
8284 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02008285 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02008286 * EUID=<NNNNN>
8287 * UID=<NNNNN>
8288 * GROUPS=()
8289 * LINES=<NNN>
8290 * COLUMNS=<NNN>
8291 * BASH_ARGC=()
8292 * BASH_ARGV=()
8293 * BASH_LINENO=()
8294 * BASH_SOURCE=()
8295 * DIRSTACK=()
8296 * PIPESTATUS=([0]="0")
8297 * HISTFILE=/<xxx>/.bash_history
8298 * HISTFILESIZE=500
8299 * HISTSIZE=500
8300 * MAILCHECK=60
8301 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8302 * SHELL=/bin/bash
8303 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8304 * TERM=dumb
8305 * OPTERR=1
8306 * OPTIND=1
8307 * IFS=$' \t\n'
8308 * PS1='\s-\v\$ '
8309 * PS2='> '
8310 * PS4='+ '
8311 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008312#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02008313
Denis Vlasenko38f63192007-01-22 09:03:07 +00008314#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02008315 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008316#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02008317
Eric Andersen94ac2442001-05-22 19:05:18 +00008318 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00008319 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00008320
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008321 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00008322
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008323 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008324 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008325 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008326 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008327 * in order to intercept (more) signals.
8328 */
8329
8330 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008331 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008332 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008333 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008334 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008335 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008336#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00008337 "<:$:R:V:"
8338# if ENABLE_HUSH_FUNCTIONS
8339 "F:"
8340# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008341#endif
8342 );
8343 if (opt <= 0)
8344 break;
Eric Andersen25f27032001-04-26 23:22:31 +00008345 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008346 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008347 /* Possibilities:
8348 * sh ... -c 'script'
8349 * sh ... -c 'script' ARG0 [ARG1...]
8350 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01008351 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008352 * "" needs to be replaced with NULL
8353 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01008354 * Note: the form without ARG0 never happens:
8355 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008356 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02008357 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008358 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008359 G.root_ppid = getppid();
8360 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008361 G.global_argv = argv + optind;
8362 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008363 if (builtin_argc) {
8364 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8365 const struct built_in_command *x;
8366
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008367 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008368 x = find_builtin(optarg);
8369 if (x) { /* paranoia */
8370 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8371 G.global_argv += builtin_argc;
8372 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008373 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01008374 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008375 }
8376 goto final_return;
8377 }
8378 if (!G.global_argv[0]) {
8379 /* -c 'script' (no params): prevent empty $0 */
8380 G.global_argv--; /* points to argv[i] of 'script' */
8381 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02008382 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008383 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008384 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008385 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008386 goto final_return;
8387 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00008388 /* Well, we cannot just declare interactiveness,
8389 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008390 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008391 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008392 case 's':
8393 /* "-s" means "read from stdin", but this is how we always
8394 * operate, so simply do nothing here. */
8395 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008396 case 'l':
8397 flags |= OPT_login;
8398 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008399#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008400 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02008401 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008402 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008403 case '$': {
8404 unsigned long long empty_trap_mask;
8405
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008406 G.root_pid = bb_strtou(optarg, &optarg, 16);
8407 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02008408 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8409 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008410 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8411 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008412 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008413 optarg++;
8414 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008415 optarg++;
8416 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8417 if (empty_trap_mask != 0) {
8418 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008419 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008420 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8421 for (sig = 1; sig < NSIG; sig++) {
8422 if (empty_trap_mask & (1LL << sig)) {
8423 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008424 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008425 }
8426 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008427 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008428# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008429 optarg++;
8430 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008431# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008432 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008433 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008434 case 'R':
8435 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02008436 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008437 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00008438# if ENABLE_HUSH_FUNCTIONS
8439 case 'F': {
8440 struct function *funcp = new_function(optarg);
8441 /* funcp->name is already set to optarg */
8442 /* funcp->body is set to NULL. It's a special case. */
8443 funcp->body_as_string = argv[optind];
8444 optind++;
8445 break;
8446 }
8447# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008448#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008449 case 'n':
8450 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008451 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008452 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008453 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008454#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008455 fprintf(stderr, "Usage: sh [FILE]...\n"
8456 " or: sh -c command [args]...\n\n");
8457 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008458#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008459 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008460#endif
Eric Andersen25f27032001-04-26 23:22:31 +00008461 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008462 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008463
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008464 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8465 G.global_argc = argc - (optind - 1);
8466 G.global_argv = argv + (optind - 1);
8467 G.global_argv[0] = argv[0];
8468
Denys Vlasenkodea47882009-10-09 15:40:49 +02008469 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008470 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008471 G.root_ppid = getppid();
8472 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008473
8474 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008475 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008476 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008477 debug_printf("sourcing /etc/profile\n");
8478 input = fopen_for_read("/etc/profile");
8479 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008480 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008481 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008482 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008483 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008484 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008485 /* bash: after sourcing /etc/profile,
8486 * tries to source (in the given order):
8487 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008488 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008489 * bash also sources ~/.bash_logout on exit.
8490 * If called as sh, skips .bash_XXX files.
8491 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008492 }
8493
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008494 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008495 FILE *input;
8496 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008497 * "bash <script>" (which is never interactive (unless -i?))
8498 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008499 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02008500 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008501 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008502 G.global_argc--;
8503 G.global_argv++;
8504 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02008505 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008506 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02008507 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008508 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008509 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008510 parse_and_run_file(input);
8511#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008512 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008513#endif
8514 goto final_return;
8515 }
8516
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008517 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008518 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008519 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008520
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008521 /* A shell is interactive if the '-i' flag was given,
8522 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008523 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008524 * no arguments remaining or the -s flag given
8525 * standard input is a terminal
8526 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008527 * Refer to Posix.2, the description of the 'sh' utility.
8528 */
8529#if ENABLE_HUSH_JOB
8530 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008531 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8532 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8533 if (G_saved_tty_pgrp < 0)
8534 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008535
8536 /* try to dup stdin to high fd#, >= 255 */
8537 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8538 if (G_interactive_fd < 0) {
8539 /* try to dup to any fd */
8540 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008541 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008542 /* give up */
8543 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008544 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008545 }
8546 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008547// TODO: track & disallow any attempts of user
8548// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008549 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008550 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008551 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008552 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008553
Mike Frysinger38478a62009-05-20 04:48:06 -04008554 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008555 /* If we were run as 'hush &', sleep until we are
8556 * in the foreground (tty pgrp == our pgrp).
8557 * If we get started under a job aware app (like bash),
8558 * make sure we are now in charge so we don't fight over
8559 * who gets the foreground */
8560 while (1) {
8561 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008562 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8563 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008564 break;
8565 /* send TTIN to ourself (should stop us) */
8566 kill(- shell_pgrp, SIGTTIN);
8567 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008568 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008569
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008570 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008571 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008572
Mike Frysinger38478a62009-05-20 04:48:06 -04008573 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008574 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008575 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008576 /* Put ourselves in our own process group
8577 * (bash, too, does this only if ctty is available) */
8578 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8579 /* Grab control of the terminal */
8580 tcsetpgrp(G_interactive_fd, getpid());
8581 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02008582 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008583
8584# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8585 {
8586 const char *hp = get_local_var_value("HISTFILE");
8587 if (!hp) {
8588 hp = get_local_var_value("HOME");
8589 if (hp)
8590 hp = concat_path_file(hp, ".hush_history");
8591 } else {
8592 hp = xstrdup(hp);
8593 }
8594 if (hp) {
8595 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008596 //set_local_var(xasprintf("HISTFILE=%s", ...));
8597 }
8598# if ENABLE_FEATURE_SH_HISTFILESIZE
8599 hp = get_local_var_value("HISTFILESIZE");
8600 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8601# endif
8602 }
8603# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008604 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008605 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008606 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008607#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008608 /* No job control compiled in, only prompt/line editing */
8609 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008610 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8611 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008612 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008613 G_interactive_fd = dup(STDIN_FILENO);
8614 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008615 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008616 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008617 }
8618 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008619 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008620 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008621 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008622 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008623#else
8624 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008625 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008626#endif
8627 /* bash:
8628 * if interactive but not a login shell, sources ~/.bashrc
8629 * (--norc turns this off, --rcfile <file> overrides)
8630 */
8631
8632 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008633 /* note: ash and hush share this string */
8634 printf("\n\n%s %s\n"
8635 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8636 "\n",
8637 bb_banner,
8638 "hush - the humble shell"
8639 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008640 }
8641
Denis Vlasenkof9375282009-04-05 19:13:39 +00008642 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008643
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008644 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008645 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008646}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008647
8648
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008649#if ENABLE_MSH
8650int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8651int msh_main(int argc, char **argv)
8652{
Denys Vlasenkoed6ff5e2016-09-30 12:28:37 +02008653 bb_error_msg("msh is deprecated, please use hush instead");
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008654 return hush_main(argc, argv);
8655}
8656#endif
8657
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008658
8659/*
8660 * Built-ins
8661 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008662static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008663{
8664 return 0;
8665}
8666
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008667static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008668{
8669 int argc = 0;
8670 while (*argv) {
8671 argc++;
8672 argv++;
8673 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008674 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008675}
8676
8677static int FAST_FUNC builtin_test(char **argv)
8678{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008679 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008680}
8681
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008682static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008683{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008684 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008685}
8686
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008687#if ENABLE_PRINTF
8688static int FAST_FUNC builtin_printf(char **argv)
8689{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008690 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008691}
8692#endif
8693
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008694static char **skip_dash_dash(char **argv)
8695{
8696 argv++;
8697 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8698 argv++;
8699 return argv;
8700}
8701
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008702static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008703{
8704 int rcode = EXIT_SUCCESS;
8705
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008706 argv = skip_dash_dash(argv);
8707 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008708 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008709 /* bash:
8710 * eval "echo Hi; done" ("done" is syntax error):
8711 * "echo Hi" will not execute too.
8712 */
8713 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008714 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008715 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008716 }
8717 return rcode;
8718}
8719
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008720static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008721{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008722 const char *newdir;
8723
8724 argv = skip_dash_dash(argv);
8725 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008726 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008727 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008728 * bash says "bash: cd: HOME not set" and does nothing
8729 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008730 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008731 const char *home = get_local_var_value("HOME");
8732 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008733 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008734 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008735 /* Mimic bash message exactly */
8736 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008737 return EXIT_FAILURE;
8738 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008739 /* Read current dir (get_cwd(1) is inside) and set PWD.
8740 * Note: do not enforce exporting. If PWD was unset or unexported,
8741 * set it again, but do not export. bash does the same.
8742 */
8743 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008744 return EXIT_SUCCESS;
8745}
8746
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008747static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008748{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008749 argv = skip_dash_dash(argv);
8750 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008751 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008752
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008753 /* Careful: we can end up here after [v]fork. Do not restore
8754 * tty pgrp then, only top-level shell process does that */
8755 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8756 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8757
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008758 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008759 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008760 * and tcsetpgrp, and this is inherently racy.
8761 */
8762 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008763}
8764
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008765static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008766{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008767 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008768
8769 /* interactive bash:
8770 * # trap "echo EEE" EXIT
8771 * # exit
8772 * exit
8773 * There are stopped jobs.
8774 * (if there are _stopped_ jobs, running ones don't count)
8775 * # exit
8776 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01008777 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00008778 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008779 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008780 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008781
8782 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008783 argv = skip_dash_dash(argv);
8784 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008785 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008786 /* mimic bash: exit 123abc == exit 255 + error msg */
8787 xfunc_error_retval = 255;
8788 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008789 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008790}
8791
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008792static void print_escaped(const char *s)
8793{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008794 if (*s == '\'')
8795 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008796 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008797 const char *p = strchrnul(s, '\'');
8798 /* print 'xxxx', possibly just '' */
8799 printf("'%.*s'", (int)(p - s), s);
8800 if (*p == '\0')
8801 break;
8802 s = p;
8803 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008804 /* s points to '; print "'''...'''" */
8805 putchar('"');
8806 do putchar('\''); while (*++s == '\'');
8807 putchar('"');
8808 } while (*s);
8809}
8810
Denys Vlasenko295fef82009-06-03 12:47:26 +02008811#if !ENABLE_HUSH_LOCAL
8812#define helper_export_local(argv, exp, lvl) \
8813 helper_export_local(argv, exp)
8814#endif
8815static void helper_export_local(char **argv, int exp, int lvl)
8816{
8817 do {
8818 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008819 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008820
8821 /* So far we do not check that name is valid (TODO?) */
8822
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008823 if (*name_end == '\0') {
8824 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008825
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008826 vpp = get_ptr_to_local_var(name, name_end - name);
8827 var = vpp ? *vpp : NULL;
8828
Denys Vlasenko295fef82009-06-03 12:47:26 +02008829 if (exp == -1) { /* unexporting? */
8830 /* export -n NAME (without =VALUE) */
8831 if (var) {
8832 var->flg_export = 0;
8833 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8834 unsetenv(name);
8835 } /* else: export -n NOT_EXISTING_VAR: no-op */
8836 continue;
8837 }
8838 if (exp == 1) { /* exporting? */
8839 /* export NAME (without =VALUE) */
8840 if (var) {
8841 var->flg_export = 1;
8842 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8843 putenv(var->varstr);
8844 continue;
8845 }
8846 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02008847#if ENABLE_HUSH_LOCAL
8848 if (exp == 0 /* local? */
8849 && var && var->func_nest_level == lvl
8850 ) {
8851 /* "local x=abc; ...; local x" - ignore second local decl */
Denys Vlasenko80729a42016-10-02 22:33:15 +02008852 continue;
Denys Vlasenko61508d92016-10-02 21:12:02 +02008853 }
8854#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02008855 /* Exporting non-existing variable.
8856 * bash does not put it in environment,
8857 * but remembers that it is exported,
8858 * and does put it in env when it is set later.
8859 * We just set it to "" and export. */
8860 /* Or, it's "local NAME" (without =VALUE).
8861 * bash sets the value to "". */
8862 name = xasprintf("%s=", name);
8863 } else {
8864 /* (Un)exporting/making local NAME=VALUE */
8865 name = xstrdup(name);
8866 }
8867 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8868 } while (*++argv);
8869}
8870
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008871static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008872{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008873 unsigned opt_unexport;
8874
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008875#if ENABLE_HUSH_EXPORT_N
8876 /* "!": do not abort on errors */
8877 opt_unexport = getopt32(argv, "!n");
8878 if (opt_unexport == (uint32_t)-1)
8879 return EXIT_FAILURE;
8880 argv += optind;
8881#else
8882 opt_unexport = 0;
8883 argv++;
8884#endif
8885
8886 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008887 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008888 if (e) {
8889 while (*e) {
8890#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008891 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008892#else
8893 /* ash emits: export VAR='VAL'
8894 * bash: declare -x VAR="VAL"
8895 * we follow ash example */
8896 const char *s = *e++;
8897 const char *p = strchr(s, '=');
8898
8899 if (!p) /* wtf? take next variable */
8900 continue;
8901 /* export var= */
8902 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008903 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008904 putchar('\n');
8905#endif
8906 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008907 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008908 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008909 return EXIT_SUCCESS;
8910 }
8911
Denys Vlasenko295fef82009-06-03 12:47:26 +02008912 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008913
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008914 return EXIT_SUCCESS;
8915}
8916
Denys Vlasenko295fef82009-06-03 12:47:26 +02008917#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008918static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008919{
8920 if (G.func_nest_level == 0) {
8921 bb_error_msg("%s: not in a function", argv[0]);
8922 return EXIT_FAILURE; /* bash compat */
8923 }
8924 helper_export_local(argv, 0, G.func_nest_level);
8925 return EXIT_SUCCESS;
8926}
8927#endif
8928
Denys Vlasenko61508d92016-10-02 21:12:02 +02008929/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8930static int FAST_FUNC builtin_unset(char **argv)
8931{
8932 int ret;
8933 unsigned opts;
8934
8935 /* "!": do not abort on errors */
8936 /* "+": stop at 1st non-option */
8937 opts = getopt32(argv, "!+vf");
8938 if (opts == (unsigned)-1)
8939 return EXIT_FAILURE;
8940 if (opts == 3) {
8941 bb_error_msg("unset: -v and -f are exclusive");
8942 return EXIT_FAILURE;
8943 }
8944 argv += optind;
8945
8946 ret = EXIT_SUCCESS;
8947 while (*argv) {
8948 if (!(opts & 2)) { /* not -f */
8949 if (unset_local_var(*argv)) {
8950 /* unset <nonexistent_var> doesn't fail.
8951 * Error is when one tries to unset RO var.
8952 * Message was printed by unset_local_var. */
8953 ret = EXIT_FAILURE;
8954 }
8955 }
8956#if ENABLE_HUSH_FUNCTIONS
8957 else {
8958 unset_func(*argv);
8959 }
8960#endif
8961 argv++;
8962 }
8963 return ret;
8964}
8965
8966/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8967 * built-in 'set' handler
8968 * SUSv3 says:
8969 * set [-abCefhmnuvx] [-o option] [argument...]
8970 * set [+abCefhmnuvx] [+o option] [argument...]
8971 * set -- [argument...]
8972 * set -o
8973 * set +o
8974 * Implementations shall support the options in both their hyphen and
8975 * plus-sign forms. These options can also be specified as options to sh.
8976 * Examples:
8977 * Write out all variables and their values: set
8978 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8979 * Turn on the -x and -v options: set -xv
8980 * Unset all positional parameters: set --
8981 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8982 * Set the positional parameters to the expansion of x, even if x expands
8983 * with a leading '-' or '+': set -- $x
8984 *
8985 * So far, we only support "set -- [argument...]" and some of the short names.
8986 */
8987static int FAST_FUNC builtin_set(char **argv)
8988{
8989 int n;
8990 char **pp, **g_argv;
8991 char *arg = *++argv;
8992
8993 if (arg == NULL) {
8994 struct variable *e;
8995 for (e = G.top_var; e; e = e->next)
8996 puts(e->varstr);
8997 return EXIT_SUCCESS;
8998 }
8999
9000 do {
9001 if (strcmp(arg, "--") == 0) {
9002 ++argv;
9003 goto set_argv;
9004 }
9005 if (arg[0] != '+' && arg[0] != '-')
9006 break;
9007 for (n = 1; arg[n]; ++n) {
9008 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9009 goto error;
9010 if (arg[n] == 'o' && argv[1])
9011 argv++;
9012 }
9013 } while ((arg = *++argv) != NULL);
9014 /* Now argv[0] is 1st argument */
9015
9016 if (arg == NULL)
9017 return EXIT_SUCCESS;
9018 set_argv:
9019
9020 /* NB: G.global_argv[0] ($0) is never freed/changed */
9021 g_argv = G.global_argv;
9022 if (G.global_args_malloced) {
9023 pp = g_argv;
9024 while (*++pp)
9025 free(*pp);
9026 g_argv[1] = NULL;
9027 } else {
9028 G.global_args_malloced = 1;
9029 pp = xzalloc(sizeof(pp[0]) * 2);
9030 pp[0] = g_argv[0]; /* retain $0 */
9031 g_argv = pp;
9032 }
9033 /* This realloc's G.global_argv */
9034 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9035
9036 n = 1;
9037 while (*++pp)
9038 n++;
9039 G.global_argc = n;
9040
9041 return EXIT_SUCCESS;
9042
9043 /* Nothing known, so abort */
9044 error:
9045 bb_error_msg("set: %s: invalid option", arg);
9046 return EXIT_FAILURE;
9047}
9048
9049static int FAST_FUNC builtin_shift(char **argv)
9050{
9051 int n = 1;
9052 argv = skip_dash_dash(argv);
9053 if (argv[0]) {
9054 n = atoi(argv[0]);
9055 }
9056 if (n >= 0 && n < G.global_argc) {
9057 if (G.global_args_malloced) {
9058 int m = 1;
9059 while (m <= n)
9060 free(G.global_argv[m++]);
9061 }
9062 G.global_argc -= n;
9063 memmove(&G.global_argv[1], &G.global_argv[n+1],
9064 G.global_argc * sizeof(G.global_argv[0]));
9065 return EXIT_SUCCESS;
9066 }
9067 return EXIT_FAILURE;
9068}
9069
9070/* Interruptibility of read builtin in bash
9071 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9072 *
9073 * Empty trap makes read ignore corresponding signal, for any signal.
9074 *
9075 * SIGINT:
9076 * - terminates non-interactive shell;
9077 * - interrupts read in interactive shell;
9078 * if it has non-empty trap:
9079 * - executes trap and returns to command prompt in interactive shell;
9080 * - executes trap and returns to read in non-interactive shell;
9081 * SIGTERM:
9082 * - is ignored (does not interrupt) read in interactive shell;
9083 * - terminates non-interactive shell;
9084 * if it has non-empty trap:
9085 * - executes trap and returns to read;
9086 * SIGHUP:
9087 * - terminates shell (regardless of interactivity);
9088 * if it has non-empty trap:
9089 * - executes trap and returns to read;
9090 */
9091static int FAST_FUNC builtin_read(char **argv)
9092{
9093 const char *r;
9094 char *opt_n = NULL;
9095 char *opt_p = NULL;
9096 char *opt_t = NULL;
9097 char *opt_u = NULL;
9098 const char *ifs;
9099 int read_flags;
9100
9101 /* "!": do not abort on errors.
9102 * Option string must start with "sr" to match BUILTIN_READ_xxx
9103 */
9104 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9105 if (read_flags == (uint32_t)-1)
9106 return EXIT_FAILURE;
9107 argv += optind;
9108 ifs = get_local_var_value("IFS"); /* can be NULL */
9109
9110 again:
9111 r = shell_builtin_read(set_local_var_from_halves,
9112 argv,
9113 ifs,
9114 read_flags,
9115 opt_n,
9116 opt_p,
9117 opt_t,
9118 opt_u
9119 );
9120
9121 if ((uintptr_t)r == 1 && errno == EINTR) {
9122 unsigned sig = check_and_run_traps();
9123 if (sig && sig != SIGINT)
9124 goto again;
9125 }
9126
9127 if ((uintptr_t)r > 1) {
9128 bb_error_msg("%s", r);
9129 r = (char*)(uintptr_t)1;
9130 }
9131
9132 return (uintptr_t)r;
9133}
9134
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009135static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009136{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009137 int sig;
9138 char *new_cmd;
9139
9140 if (!G.traps)
9141 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
9142
9143 argv++;
9144 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00009145 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009146 /* No args: print all trapped */
9147 for (i = 0; i < NSIG; ++i) {
9148 if (G.traps[i]) {
9149 printf("trap -- ");
9150 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02009151 /* note: bash adds "SIG", but only if invoked
9152 * as "bash". If called as "sh", or if set -o posix,
9153 * then it prints short signal names.
9154 * We are printing short names: */
9155 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009156 }
9157 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009158 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009159 return EXIT_SUCCESS;
9160 }
9161
9162 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009163 /* If first arg is a number: reset all specified signals */
9164 sig = bb_strtou(*argv, NULL, 10);
9165 if (errno == 0) {
9166 int ret;
9167 process_sig_list:
9168 ret = EXIT_SUCCESS;
9169 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009170 sighandler_t handler;
9171
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009172 sig = get_signum(*argv++);
9173 if (sig < 0 || sig >= NSIG) {
9174 ret = EXIT_FAILURE;
9175 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00009176 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009177 continue;
9178 }
9179
9180 free(G.traps[sig]);
9181 G.traps[sig] = xstrdup(new_cmd);
9182
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009183 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009184 get_signame(sig), sig, G.traps[sig]);
9185
9186 /* There is no signal for 0 (EXIT) */
9187 if (sig == 0)
9188 continue;
9189
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009190 if (new_cmd)
9191 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9192 else
9193 /* We are removing trap handler */
9194 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02009195 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009196 }
9197 return ret;
9198 }
9199
9200 if (!argv[1]) { /* no second arg */
9201 bb_error_msg("trap: invalid arguments");
9202 return EXIT_FAILURE;
9203 }
9204
9205 /* First arg is "-": reset all specified to default */
9206 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9207 /* Everything else: set arg as signal handler
9208 * (includes "" case, which ignores signal) */
9209 if (argv[0][0] == '-') {
9210 if (argv[0][1] == '\0') { /* "-" */
9211 /* new_cmd remains NULL: "reset these sigs" */
9212 goto reset_traps;
9213 }
9214 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9215 argv++;
9216 }
9217 /* else: "-something", no special meaning */
9218 }
9219 new_cmd = *argv;
9220 reset_traps:
9221 argv++;
9222 goto process_sig_list;
9223}
9224
Mike Frysinger93cadc22009-05-27 17:06:25 -04009225/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009226static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04009227{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009228 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04009229
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009230 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04009231 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02009232 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04009233
9234 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009235 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009236 type = "an alias";*/
9237#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009238 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009239 type = "a function";
9240#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009241 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009242 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009243 else if ((path = find_in_path(*argv)) != NULL)
9244 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009245 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009246 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04009247 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009248 continue;
9249 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04009250
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009251 printf("%s is %s\n", *argv, type);
9252 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04009253 }
9254
9255 return ret;
9256}
9257
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009258#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009259static struct pipe *parse_jobspec(const char *str)
9260{
9261 struct pipe *pi;
9262 int jobnum;
9263
9264 if (sscanf(str, "%%%d", &jobnum) != 1) {
9265 bb_error_msg("bad argument '%s'", str);
9266 return NULL;
9267 }
9268 for (pi = G.job_list; pi; pi = pi->next) {
9269 if (pi->jobid == jobnum) {
9270 return pi;
9271 }
9272 }
9273 bb_error_msg("%d: no such job", jobnum);
9274 return NULL;
9275}
9276
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009277/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009278static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009279{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009280 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009281 struct pipe *pi;
9282
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009283 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009284 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009285
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009286 /* If they gave us no args, assume they want the last backgrounded task */
9287 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00009288 for (pi = G.job_list; pi; pi = pi->next) {
9289 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009290 goto found;
9291 }
9292 }
9293 bb_error_msg("%s: no current job", argv[0]);
9294 return EXIT_FAILURE;
9295 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009296
9297 pi = parse_jobspec(argv[1]);
9298 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009299 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009300 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00009301 /* TODO: bash prints a string representation
9302 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04009303 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009304 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009305 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009306 }
9307
9308 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009309 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9310 for (i = 0; i < pi->num_cmds; i++) {
9311 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009312 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009313 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009314
9315 i = kill(- pi->pgrp, SIGCONT);
9316 if (i < 0) {
9317 if (errno == ESRCH) {
9318 delete_finished_bg_job(pi);
9319 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009320 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009321 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009322 }
9323
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009324 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009325 remove_bg_job(pi);
9326 return checkjobs_and_fg_shell(pi);
9327 }
9328 return EXIT_SUCCESS;
9329}
9330#endif
9331
9332#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009333static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009334{
9335 const struct built_in_command *x;
9336
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009337 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009338 "Built-in commands:\n"
9339 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009340 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01009341 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009342 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009343 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009344 return EXIT_SUCCESS;
9345}
9346#endif
9347
Denys Vlasenkoff463a82013-05-12 02:45:23 +02009348#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02009349static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9350{
9351 show_history(G.line_input_state);
9352 return EXIT_SUCCESS;
9353}
9354#endif
9355
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009356#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009357static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009358{
9359 struct pipe *job;
9360 const char *status_string;
9361
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009362 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denis Vlasenko87a86552008-07-29 19:43:10 +00009363 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009364 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009365 status_string = "Stopped";
9366 else
9367 status_string = "Running";
9368
9369 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9370 }
9371 return EXIT_SUCCESS;
9372}
9373#endif
9374
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009375#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009376static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009377{
9378 void *p;
9379 unsigned long l;
9380
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009381# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02009382 /* Optional. Reduces probability of false positives */
9383 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009384# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009385 /* Crude attempt to find where "free memory" starts,
9386 * sans fragmentation. */
9387 p = malloc(240);
9388 l = (unsigned long)p;
9389 free(p);
9390 p = malloc(3400);
9391 if (l < (unsigned long)p) l = (unsigned long)p;
9392 free(p);
9393
Denys Vlasenko7f0ebbc2016-10-03 17:42:53 +02009394
9395# if 0 /* debug */
9396 {
9397 struct mallinfo mi = mallinfo();
9398 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
9399 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
9400 }
9401# endif
9402
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009403 if (!G.memleak_value)
9404 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02009405
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009406 l -= G.memleak_value;
9407 if ((long)l < 0)
9408 l = 0;
9409 l /= 1024;
9410 if (l > 127)
9411 l = 127;
9412
9413 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9414 return l;
9415}
9416#endif
9417
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009418static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009419{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009420 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009421 return EXIT_SUCCESS;
9422}
9423
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009424static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009425{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009426 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009427 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009428 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009429#if ENABLE_HUSH_FUNCTIONS
9430 smallint sv_flg;
9431#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009432
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009433 argv = skip_dash_dash(argv);
9434 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009435 if (!filename) {
9436 /* bash says: "bash: .: filename argument required" */
9437 return 2; /* bash compat */
9438 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009439 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009440 if (!strchr(filename, '/')) {
9441 arg_path = find_in_path(filename);
9442 if (arg_path)
9443 filename = arg_path;
9444 }
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009445 input = remember_FILE(fopen_or_warn(filename, "r"));
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009446 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009447 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009448 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009449 /* POSIX: non-interactive shell should abort here,
9450 * not merely fail. So far no one complained :)
9451 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009452 return EXIT_FAILURE;
9453 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009454
Mike Frysinger885b6f22009-04-18 21:04:25 +00009455#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009456 sv_flg = G_flag_return_in_progress;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009457 /* "we are inside sourced file, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009458 G_flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009459#endif
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009460 if (argv[1])
9461 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009462
Denys Vlasenko992e0ff2016-09-29 01:27:09 +02009463 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9464 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009465 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009466 fclose_and_forget(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009467
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009468 if (argv[1])
9469 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00009470#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009471 G_flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009472#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009473
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009474 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009475}
9476
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009477static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009478{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009479 int rc;
9480 mode_t mask;
9481
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009482 rc = 1;
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009483 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009484 argv = skip_dash_dash(argv);
9485 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009486 mode_t old_mask = mask;
9487
Denys Vlasenko6283f982015-10-07 16:56:20 +02009488 /* numeric umasks are taken as-is */
9489 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9490 if (!isdigit(argv[0][0]))
9491 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009492 mask = bb_parse_mode(argv[0], mask);
Denys Vlasenko6283f982015-10-07 16:56:20 +02009493 if (!isdigit(argv[0][0]))
9494 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009495 if ((unsigned)mask > 0777) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009496 mask = old_mask;
9497 /* bash messages:
9498 * bash: umask: 'q': invalid symbolic mode operator
9499 * bash: umask: 999: octal number out of range
9500 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02009501 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009502 rc = 0;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009503 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009504 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009505 /* Mimic bash */
9506 printf("%04o\n", (unsigned) mask);
9507 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009508 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009509 umask(mask);
9510
9511 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009512}
9513
Mike Frysinger56bdea12009-03-28 20:01:58 +00009514/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009515#if !ENABLE_HUSH_JOB
9516# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
9517#endif
9518static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +02009519{
9520 int ret = 0;
9521 for (;;) {
9522 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009523 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +02009524
Denys Vlasenko830ea352016-11-08 04:59:11 +01009525 if (!sigisemptyset(&G.pending_set))
9526 goto check_sig;
9527
Denys Vlasenko7e675362016-10-28 21:57:31 +02009528 /* waitpid is not interruptible by SA_RESTARTed
9529 * signals which we use. Thus, this ugly dance:
9530 */
9531
9532 /* Make sure possible SIGCHLD is stored in kernel's
9533 * pending signal mask before we call waitpid.
9534 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009535 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +02009536 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009537 sigfillset(&oldset); /* block all signals, remember old set */
9538 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009539
9540 if (!sigisemptyset(&G.pending_set)) {
9541 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009542 goto restore;
9543 }
9544
9545 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009546/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009547 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009548 debug_printf_exec("checkjobs:%d\n", ret);
9549#if ENABLE_HUSH_JOB
9550 if (waitfor_pipe) {
9551 int rcode = job_exited_or_stopped(waitfor_pipe);
9552 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
9553 if (rcode >= 0) {
9554 ret = rcode;
9555 sigprocmask(SIG_SETMASK, &oldset, NULL);
9556 break;
9557 }
9558 }
9559#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009560 /* if ECHILD, there are no children (ret is -1 or 0) */
9561 /* if ret == 0, no children changed state */
9562 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009563 if (errno == ECHILD || ret) {
9564 ret--;
9565 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009566 ret = 0;
9567 sigprocmask(SIG_SETMASK, &oldset, NULL);
9568 break;
9569 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009570 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009571 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9572 /* Note: sigsuspend invokes signal handler */
9573 sigsuspend(&oldset);
9574 restore:
9575 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +01009576 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009577 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009578 sig = check_and_run_traps();
9579 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009580 ret = 128 + sig;
9581 break;
9582 }
9583 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9584 }
9585 return ret;
9586}
9587
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009588static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00009589{
Denys Vlasenko7e675362016-10-28 21:57:31 +02009590 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009591 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009592
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009593 argv = skip_dash_dash(argv);
9594 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009595 /* Don't care about wait results */
9596 /* Note 1: must wait until there are no more children */
9597 /* Note 2: must be interruptible */
9598 /* Examples:
9599 * $ sleep 3 & sleep 6 & wait
9600 * [1] 30934 sleep 3
9601 * [2] 30935 sleep 6
9602 * [1] Done sleep 3
9603 * [2] Done sleep 6
9604 * $ sleep 3 & sleep 6 & wait
9605 * [1] 30936 sleep 3
9606 * [2] 30937 sleep 6
9607 * [1] Done sleep 3
9608 * ^C <-- after ~4 sec from keyboard
9609 * $
9610 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009611 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009612 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009613
Denys Vlasenko7e675362016-10-28 21:57:31 +02009614 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009615 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009616 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009617#if ENABLE_HUSH_JOB
9618 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +01009619 struct pipe *wait_pipe;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009620 wait_pipe = parse_jobspec(*argv);
9621 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +01009622 ret = job_exited_or_stopped(wait_pipe);
9623 if (ret < 0)
9624 ret = wait_for_child_or_signal(wait_pipe, 0);
9625 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009626 }
9627 }
9628#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00009629 /* mimic bash message */
9630 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009631 ret = EXIT_FAILURE;
9632 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009633 }
Denys Vlasenko02affb42016-11-08 00:59:29 +01009634
Denys Vlasenko7e675362016-10-28 21:57:31 +02009635 /* Do we have such child? */
9636 ret = waitpid(pid, &status, WNOHANG);
9637 if (ret < 0) {
9638 /* No */
9639 if (errno == ECHILD) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009640 if (G.last_bg_pid > 0 && pid == G.last_bg_pid) {
9641 /* "wait $!" but last bg task has already exited. Try:
9642 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
9643 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +01009644 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009645 */
Denys Vlasenko26ad94b2016-11-07 23:07:21 +01009646 /* ret = G.last_bg_pid_exitstatus - FIXME */
9647 } else {
9648 /* Example: "wait 1". mimic bash message */
9649 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009650 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009651 } else {
9652 /* ??? */
9653 bb_perror_msg("wait %s", *argv);
9654 }
9655 ret = 127;
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009656 continue; /* bash checks all argv[] */
9657 }
9658 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009659 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +01009660 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009661 } else {
9662 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +01009663 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +02009664 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009665 if (WIFSIGNALED(status))
9666 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009667 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009668 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009669
9670 return ret;
9671}
9672
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009673#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9674static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9675{
9676 if (argv[1]) {
9677 def = bb_strtou(argv[1], NULL, 10);
9678 if (errno || def < def_min || argv[2]) {
9679 bb_error_msg("%s: bad arguments", argv[0]);
9680 def = UINT_MAX;
9681 }
9682 }
9683 return def;
9684}
9685#endif
9686
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009687#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009688static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009689{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009690 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009691 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009692 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +02009693 /* if we came from builtin_continue(), need to undo "= 1" */
9694 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009695 return EXIT_SUCCESS; /* bash compat */
9696 }
Denys Vlasenko49117b42016-07-21 14:40:08 +02009697 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009698
9699 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9700 if (depth == UINT_MAX)
9701 G.flag_break_continue = BC_BREAK;
9702 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009703 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009704
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009705 return EXIT_SUCCESS;
9706}
9707
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009708static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009709{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009710 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9711 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009712}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009713#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009714
9715#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009716static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009717{
9718 int rc;
9719
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009720 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009721 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9722 return EXIT_FAILURE; /* bash compat */
9723 }
9724
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009725 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009726
9727 /* bash:
9728 * out of range: wraps around at 256, does not error out
9729 * non-numeric param:
9730 * f() { false; return qwe; }; f; echo $?
9731 * bash: return: qwe: numeric argument required <== we do this
9732 * 255 <== we also do this
9733 */
9734 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9735 return rc;
9736}
9737#endif