blob: a5f059924859737ce904f68cba8d2220e7e4539e [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
45 * tilde expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000046 * aliases
Denys Vlasenko7e675362016-10-28 21:57:31 +020047 * kill %jobspec
Denys Vlasenko349ef962010-05-21 15:46:24 +020048 * follow IFS rules more precisely, including update semantics
49 * builtins mandated by standards we don't support:
50 * [un]alias, command, fc, getopts, newgrp, readonly, times
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020051 * make complex ${var%...} constructs support optional
52 * make here documents optional
Mike Frysinger25a6ca02009-03-28 13:59:26 +000053 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020054 * Bash compat TODO:
55 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020056 * reserved words: function select
57 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020058 * process substitution: <(list) and >(list)
59 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020060 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020061 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
62 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
63 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020064 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020065 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
66 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020067 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenkobbecd742010-10-03 17:22:52 +020068 *
69 * Won't do:
70 * In bash, export builtin is special, its arguments are assignments
Denys Vlasenko08218012009-06-03 14:43:56 +020071 * and therefore expansion of them should be "one-word" expansion:
72 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
73 * compare with:
74 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
75 * ls: cannot access i=a: No such file or directory
76 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020077 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020078 * Note2: bash 3.2.33(1) does this only if export word itself
79 * is not quoted:
80 * $ export i=`echo 'aaa bbb'`; echo "$i"
81 * aaa bbb
82 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
83 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000084 */
Denys Vlasenko8da415e2010-12-05 01:30:14 +010085#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
86 || defined(__APPLE__) \
87 )
88# include <malloc.h> /* for malloc_trim */
89#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +000090#include <glob.h>
91/* #include <dmalloc.h> */
92#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000093# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000094#endif
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020095#include <sys/utsname.h> /* for setting $HOSTNAME */
Denys Vlasenko03dad222010-01-12 23:29:57 +010096
Denys Vlasenko20704f02011-03-23 17:59:27 +010097#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
98#include "unicode.h"
Denys Vlasenko03dad222010-01-12 23:29:57 +010099#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +0000100#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +0000101#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +0200102#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200103# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +0200104#else
105# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200106#endif
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200107#ifndef F_DUPFD_CLOEXEC
108# define F_DUPFD_CLOEXEC F_DUPFD
109#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000110#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200111# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000112#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000113
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200114//config:config HUSH
115//config: bool "hush"
116//config: default y
117//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200118//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200119//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
120//config: case/esac. Redirections, here documents, $((arithmetic))
121//config: and functions are supported.
122//config:
123//config: It will compile and work on no-mmu systems.
124//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +0200125//config: It does not handle select, aliases, tilde expansion,
126//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200127//config:
128//config:config HUSH_BASH_COMPAT
129//config: bool "bash-compatible extensions"
130//config: default y
131//config: depends on HUSH
132//config: help
133//config: Enable bash-compatible extensions.
134//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200135//config:config HUSH_BRACE_EXPANSION
136//config: bool "Brace expansion"
137//config: default y
138//config: depends on HUSH_BASH_COMPAT
139//config: help
140//config: Enable {abc,def} extension.
141//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200142//config:config HUSH_HELP
143//config: bool "help builtin"
144//config: default y
145//config: depends on HUSH
146//config: help
147//config: Enable help builtin in hush. Code size + ~1 kbyte.
148//config:
149//config:config HUSH_INTERACTIVE
150//config: bool "Interactive mode"
151//config: default y
152//config: depends on HUSH
153//config: help
154//config: Enable interactive mode (prompt and command editing).
155//config: Without this, hush simply reads and executes commands
156//config: from stdin just like a shell script from a file.
157//config: No prompt, no PS1/PS2 magic shell variables.
158//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200159//config:config HUSH_SAVEHISTORY
160//config: bool "Save command history to .hush_history"
161//config: default y
162//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
163//config: help
164//config: Enable history saving in hush.
165//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200166//config:config HUSH_JOB
167//config: bool "Job control"
168//config: default y
169//config: depends on HUSH_INTERACTIVE
170//config: help
171//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
172//config: command (not entire shell), fg/bg builtins work. Without this option,
173//config: "cmd &" still works by simply spawning a process and immediately
174//config: prompting for next command (or executing next command in a script),
175//config: but no separate process group is formed.
176//config:
177//config:config HUSH_TICK
178//config: bool "Process substitution"
179//config: default y
180//config: depends on HUSH
181//config: help
182//config: Enable process substitution `command` and $(command) in hush.
183//config:
184//config:config HUSH_IF
185//config: bool "Support if/then/elif/else/fi"
186//config: default y
187//config: depends on HUSH
188//config: help
189//config: Enable if/then/elif/else/fi in hush.
190//config:
191//config:config HUSH_LOOPS
192//config: bool "Support for, while and until loops"
193//config: default y
194//config: depends on HUSH
195//config: help
196//config: Enable for, while and until loops in hush.
197//config:
198//config:config HUSH_CASE
199//config: bool "Support case ... esac statement"
200//config: default y
201//config: depends on HUSH
202//config: help
203//config: Enable case ... esac statement in hush. +400 bytes.
204//config:
205//config:config HUSH_FUNCTIONS
206//config: bool "Support funcname() { commands; } syntax"
207//config: default y
208//config: depends on HUSH
209//config: help
210//config: Enable support for shell functions in hush. +800 bytes.
211//config:
212//config:config HUSH_LOCAL
213//config: bool "Support local builtin"
214//config: default y
215//config: depends on HUSH_FUNCTIONS
216//config: help
217//config: Enable support for local variables in functions.
218//config:
219//config:config HUSH_RANDOM_SUPPORT
220//config: bool "Pseudorandom generator and $RANDOM variable"
221//config: default y
222//config: depends on HUSH
223//config: help
224//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
225//config: Each read of "$RANDOM" will generate a new pseudorandom value.
226//config:
227//config:config HUSH_EXPORT_N
228//config: bool "Support 'export -n' option"
229//config: default y
230//config: depends on HUSH
231//config: help
232//config: export -n unexports variables. It is a bash extension.
233//config:
234//config:config HUSH_MODE_X
235//config: bool "Support 'hush -x' option and 'set -x' command"
236//config: default y
237//config: depends on HUSH
238//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200239//config: This instructs hush to print commands before execution.
240//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200241//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200242//config:config MSH
243//config: bool "msh (deprecated: aliased to hush)"
244//config: default n
245//config: select HUSH
246//config: help
247//config: msh is deprecated and will be removed, please migrate to hush.
248//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200249
Denys Vlasenko20704f02011-03-23 17:59:27 +0100250//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
251//applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
252//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
253//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
254
255//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
256//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
257
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100258/* -i (interactive) and -s (read stdin) are also accepted,
259 * but currently do nothing, therefore aren't shown in help.
260 * NOMMU-specific options are not meant to be used by users,
261 * therefore we don't show them either.
262 */
263//usage:#define hush_trivial_usage
Denys Vlasenkof58f7052011-05-12 02:10:33 +0200264//usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100265//usage:#define hush_full_usage "\n\n"
266//usage: "Unix shell interpreter"
267
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100268//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100269//usage:#define msh_full_usage hush_full_usage
270
271//usage:#if ENABLE_FEATURE_SH_IS_HUSH
272//usage:# define sh_trivial_usage hush_trivial_usage
273//usage:# define sh_full_usage hush_full_usage
274//usage:#endif
275//usage:#if ENABLE_FEATURE_BASH_IS_HUSH
276//usage:# define bash_trivial_usage hush_trivial_usage
277//usage:# define bash_full_usage hush_full_usage
278//usage:#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200279
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000280
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200281/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000282#define LEAK_HUNTING 0
283#define BUILD_AS_NOMMU 0
284/* Enable/disable sanity checks. Ok to enable in production,
285 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
286 * Keeping 1 for now even in released versions.
287 */
288#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200289/* Slightly bigger (+200 bytes), but faster hush.
290 * So far it only enables a trick with counting SIGCHLDs and forks,
291 * which allows us to do fewer waitpid's.
292 * (we can detect a case where neither forks were done nor SIGCHLDs happened
293 * and therefore waitpid will return the same result as last time)
294 */
295#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200296/* TODO: implement simplified code for users which do not need ${var%...} ops
297 * So far ${var%...} ops are always enabled:
298 */
299#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000300
301
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000302#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000303# undef BB_MMU
304# undef USE_FOR_NOMMU
305# undef USE_FOR_MMU
306# define BB_MMU 0
307# define USE_FOR_NOMMU(...) __VA_ARGS__
308# define USE_FOR_MMU(...)
309#endif
310
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200311#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100312#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000313/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000314# undef CONFIG_FEATURE_SH_STANDALONE
315# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000316# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100317# undef IF_NOT_FEATURE_SH_STANDALONE
318# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000319# define IF_FEATURE_SH_STANDALONE(...)
320# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000321#endif
322
Denis Vlasenko05743d72008-02-10 12:10:08 +0000323#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000324# undef ENABLE_FEATURE_EDITING
325# define ENABLE_FEATURE_EDITING 0
326# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
327# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200328# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
329# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000330#endif
331
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000332/* Do we support ANY keywords? */
333#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000334# define HAS_KEYWORDS 1
335# define IF_HAS_KEYWORDS(...) __VA_ARGS__
336# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000337#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000338# define HAS_KEYWORDS 0
339# define IF_HAS_KEYWORDS(...)
340# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000341#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000342
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000343/* If you comment out one of these below, it will be #defined later
344 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000345#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000346/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000347#define debug_printf_parse(...) do {} while (0)
348#define debug_print_tree(a, b) do {} while (0)
349#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000350#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000351#define debug_printf_jobs(...) do {} while (0)
352#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200353#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000354#define debug_printf_glob(...) do {} while (0)
355#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000356#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000357#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000358
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000359#define ERR_PTR ((void*)(long)1)
360
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200361#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000362
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200363#define _SPECIAL_VARS_STR "_*@$!?#"
364#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
365#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200366#if ENABLE_HUSH_BASH_COMPAT
367/* Support / and // replace ops */
368/* Note that // is stored as \ in "encoded" string representation */
369# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
370# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
371# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
372#else
373# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
374# define VAR_SUBST_OPS "%#:-=+?"
375# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
376#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200377
378#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000379
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200380struct variable;
381
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000382static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
383
384/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000385 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000386 */
387#if !BB_MMU
388typedef struct nommu_save_t {
389 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200390 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000391 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000392 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000393} nommu_save_t;
394#endif
395
Denys Vlasenko9b782552010-09-08 13:33:26 +0200396enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000397 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000398#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000399 RES_IF ,
400 RES_THEN ,
401 RES_ELIF ,
402 RES_ELSE ,
403 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000404#endif
405#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000406 RES_FOR ,
407 RES_WHILE ,
408 RES_UNTIL ,
409 RES_DO ,
410 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000411#endif
412#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000413 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000414#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000415#if ENABLE_HUSH_CASE
416 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200417 /* three pseudo-keywords support contrived "case" syntax: */
418 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
419 RES_MATCH , /* "word)" */
420 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000421 RES_ESAC ,
422#endif
423 RES_XXXX ,
424 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200425};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000426
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000427typedef struct o_string {
428 char *data;
429 int length; /* position where data is appended */
430 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200431 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000432 /* At least some part of the string was inside '' or "",
433 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200434 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000435 smallint has_empty_slot;
436 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
437} o_string;
438enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200439 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
440 EXP_FLAG_GLOB = 0x2,
441 /* Protect newly added chars against globbing
442 * by prepending \ to *, ?, [, \ */
443 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
444};
445enum {
446 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000447 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200448 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200449 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200450 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000451};
452/* Used for initialization: o_string foo = NULL_O_STRING; */
453#define NULL_O_STRING { NULL }
454
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200455#ifndef debug_printf_parse
456static const char *const assignment_flag[] = {
457 "MAYBE_ASSIGNMENT",
458 "DEFINITELY_ASSIGNMENT",
459 "NOT_ASSIGNMENT",
460 "WORD_IS_KEYWORD",
461};
462#endif
463
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000464typedef struct in_str {
465 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000466#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000467 smallint promptmode; /* 0: PS1, 1: PS2 */
468#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200469 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200470 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000471 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200472 int (*get) (struct in_str *) FAST_FUNC;
473 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000474} in_str;
475#define i_getch(input) ((input)->get(input))
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200476#define i_peek(input) ((input)->peek(input))
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000477
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200478/* The descrip member of this structure is only used to make
479 * debugging output pretty */
480static const struct {
481 int mode;
482 signed char default_fd;
483 char descrip[3];
484} redir_table[] = {
485 { O_RDONLY, 0, "<" },
486 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
487 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
488 { O_CREAT|O_RDWR, 1, "<>" },
489 { O_RDONLY, 0, "<<" },
490/* Should not be needed. Bogus default_fd helps in debugging */
491/* { O_RDONLY, 77, "<<" }, */
492};
493
Eric Andersen25f27032001-04-26 23:22:31 +0000494struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000495 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000496 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000497 int rd_fd; /* fd to redirect */
498 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
499 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000500 smallint rd_type; /* (enum redir_type) */
501 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000502 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200503 * bit 0: do we need to trim leading tabs?
504 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000505 */
Eric Andersen25f27032001-04-26 23:22:31 +0000506};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000507typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200508 REDIRECT_INPUT = 0,
509 REDIRECT_OVERWRITE = 1,
510 REDIRECT_APPEND = 2,
511 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000512 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200513 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000514
515 REDIRFD_CLOSE = -3,
516 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000517 REDIRFD_TO_FILE = -1,
518 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000519
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000520 HEREDOC_SKIPTABS = 1,
521 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000522} redir_type;
523
Eric Andersen25f27032001-04-26 23:22:31 +0000524
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000525struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000526 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000527 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200528 smallint cmd_type; /* CMD_xxx */
529#define CMD_NORMAL 0
530#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200531#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200532/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200533# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000534#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200535#if ENABLE_HUSH_FUNCTIONS
536# define CMD_FUNCDEF 3
537#endif
538
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100539 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200540 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
541 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000542#if !BB_MMU
543 char *group_as_string;
544#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000545#if ENABLE_HUSH_FUNCTIONS
546 struct function *child_func;
547/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200548 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000549 * When we execute "f1() {a;}" cmd, we create new function and clear
550 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200551 * When we execute "f1() {b;}", we notice that f1 exists,
552 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000553 * we put those fields back into cmd->xxx
554 * (struct function has ->parent_cmd ptr to facilitate that).
555 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
556 * Without this trick, loop would execute a;b;b;b;...
557 * instead of correct sequence a;b;a;b;...
558 * When command is freed, it severs the link
559 * (sets ->child_func->parent_cmd to NULL).
560 */
561#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000562 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000563/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
564 * and on execution these are substituted with their values.
565 * Substitution can make _several_ words out of one argv[n]!
566 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000567 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000568 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000569 struct redir_struct *redirects; /* I/O redirections */
570};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000571/* Is there anything in this command at all? */
572#define IS_NULL_CMD(cmd) \
573 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
574
Eric Andersen25f27032001-04-26 23:22:31 +0000575struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000576 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000577 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000578 int alive_cmds; /* number of commands running (not exited) */
579 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000580#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000581 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000582 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000583 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000584#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000585 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000586 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000587 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
588 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000589};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000590typedef enum pipe_style {
591 PIPE_SEQ = 1,
592 PIPE_AND = 2,
593 PIPE_OR = 3,
594 PIPE_BG = 4,
595} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000596/* Is there anything in this pipe at all? */
597#define IS_NULL_PIPE(pi) \
598 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000599
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000600/* This holds pointers to the various results of parsing */
601struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000602 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000603 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000604 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000605 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000606 /* last command in pipe (being constructed right now) */
607 struct command *command;
608 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000609 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000610#if !BB_MMU
611 o_string as_string;
612#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000613#if HAS_KEYWORDS
614 smallint ctx_res_w;
615 smallint ctx_inverted; /* "! cmd | cmd" */
616#if ENABLE_HUSH_CASE
617 smallint ctx_dsemicolon; /* ";;" seen */
618#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000619 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
620 int old_flag;
621 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000622 * example: "if pipe1; pipe2; then pipe3; fi"
623 * when we see "if" or "then", we malloc and copy current context,
624 * and make ->stack point to it. then we parse pipeN.
625 * when closing "then" / fi" / whatever is found,
626 * we move list_head into ->stack->command->group,
627 * copy ->stack into current context, and delete ->stack.
628 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000629 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000630 struct parse_context *stack;
631#endif
632};
633
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000634/* On program start, environ points to initial environment.
635 * putenv adds new pointers into it, unsetenv removes them.
636 * Neither of these (de)allocates the strings.
637 * setenv allocates new strings in malloc space and does putenv,
638 * and thus setenv is unusable (leaky) for shell's purposes */
639#define setenv(...) setenv_is_leaky_dont_use()
640struct variable {
641 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000642 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200643#if ENABLE_HUSH_LOCAL
644 unsigned func_nest_level;
645#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000646 int max_len; /* if > 0, name is part of initial env; else name is malloced */
647 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000648 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000649};
650
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000651enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000652 BC_BREAK = 1,
653 BC_CONTINUE = 2,
654};
655
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000656#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000657struct function {
658 struct function *next;
659 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000660 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000661 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200662# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000663 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200664# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000665};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000666#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000667
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000668
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100669/* set -/+o OPT support. (TODO: make it optional)
670 * bash supports the following opts:
671 * allexport off
672 * braceexpand on
673 * emacs on
674 * errexit off
675 * errtrace off
676 * functrace off
677 * hashall on
678 * histexpand off
679 * history on
680 * ignoreeof off
681 * interactive-comments on
682 * keyword off
683 * monitor on
684 * noclobber off
685 * noexec off
686 * noglob off
687 * nolog off
688 * notify off
689 * nounset off
690 * onecmd off
691 * physical off
692 * pipefail off
693 * posix off
694 * privileged off
695 * verbose off
696 * vi off
697 * xtrace off
698 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800699static const char o_opt_strings[] ALIGN1 =
700 "pipefail\0"
701 "noexec\0"
702#if ENABLE_HUSH_MODE_X
703 "xtrace\0"
704#endif
705 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100706enum {
707 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800708 OPT_O_NOEXEC,
709#if ENABLE_HUSH_MODE_X
710 OPT_O_XTRACE,
711#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100712 NUM_OPT_O
713};
714
715
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200716struct FILE_list {
717 struct FILE_list *next;
718 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200719 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200720};
721
722
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000723/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000724/* Sorted roughly by size (smaller offsets == smaller code) */
725struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000726 /* interactive_fd != 0 means we are an interactive shell.
727 * If we are, then saved_tty_pgrp can also be != 0, meaning
728 * that controlling tty is available. With saved_tty_pgrp == 0,
729 * job control still works, but terminal signals
730 * (^C, ^Z, ^Y, ^\) won't work at all, and background
731 * process groups can only be created with "cmd &".
732 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
733 * to give tty to the foreground process group,
734 * and will take it back when the group is stopped (^Z)
735 * or killed (^C).
736 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000737#if ENABLE_HUSH_INTERACTIVE
738 /* 'interactive_fd' is a fd# open to ctty, if we have one
739 * _AND_ if we decided to act interactively */
740 int interactive_fd;
741 const char *PS1;
742 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000743# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000744#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000745# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000746#endif
747#if ENABLE_FEATURE_EDITING
748 line_input_t *line_input_state;
749#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000750 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200751 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000752 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200753#if ENABLE_HUSH_RANDOM_SUPPORT
754 random_t random_gen;
755#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000756#if ENABLE_HUSH_JOB
757 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000758 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000759 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000760 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400761# define G_saved_tty_pgrp (G.saved_tty_pgrp)
762#else
763# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000764#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100765 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100766#if ENABLE_HUSH_MODE_X
767# define G_x_mode (G.o_opt[OPT_O_XTRACE])
768#else
769# define G_x_mode 0
770#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000771 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000772#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000773 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000774#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000775#if ENABLE_HUSH_FUNCTIONS
776 /* 0: outside of a function (or sourced file)
777 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000778 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000779 */
780 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200781# define G_flag_return_in_progress (G.flag_return_in_progress)
782#else
783# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000784#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000785 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000786 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000787 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000788 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000789 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000790 /* how many non-NULL argv's we have. NB: $# + 1 */
791 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000792 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000793#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000794 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000795#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000796#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000797 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000798 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000799#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000800 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000801 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200802 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200803 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000804#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000805 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200806# if ENABLE_HUSH_LOCAL
807 struct variable **shadowed_vars_pp;
808 unsigned func_nest_level;
809# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000810#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000811 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200812#if ENABLE_HUSH_FAST
813 unsigned count_SIGCHLD;
814 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200815 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200816#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200817 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200818 /* Which signals have non-DFL handler (even with no traps set)?
819 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200820 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200821 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200822 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200823 * Other than these two times, never modified.
824 */
825 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200826#if ENABLE_HUSH_JOB
827 unsigned fatal_sig_mask;
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200828# define G_fatal_sig_mask G.fatal_sig_mask
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200829#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200830# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200831#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000832 char **traps; /* char *traps[NSIG] */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200833 sigset_t pending_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000834#if HUSH_DEBUG
835 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000836 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000837#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200838 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200839#if ENABLE_FEATURE_EDITING
840 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
841#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000842};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000843#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000844/* Not #defining name to G.name - this quickly gets unwieldy
845 * (too many defines). Also, I actually prefer to see when a variable
846 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000847#define INIT_G() do { \
848 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200849 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
850 sigfillset(&G.sa.sa_mask); \
851 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000852} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000853
854
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000855/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200856static int builtin_cd(char **argv) FAST_FUNC;
857static int builtin_echo(char **argv) FAST_FUNC;
858static int builtin_eval(char **argv) FAST_FUNC;
859static int builtin_exec(char **argv) FAST_FUNC;
860static int builtin_exit(char **argv) FAST_FUNC;
861static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000862#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200863static int builtin_fg_bg(char **argv) FAST_FUNC;
864static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000865#endif
866#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200867static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000868#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200869#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200870static int builtin_history(char **argv) FAST_FUNC;
871#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200872#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200873static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200874#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000875#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200876static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000877#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400878#if ENABLE_PRINTF
879static int builtin_printf(char **argv) FAST_FUNC;
880#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200881static int builtin_pwd(char **argv) FAST_FUNC;
882static int builtin_read(char **argv) FAST_FUNC;
883static int builtin_set(char **argv) FAST_FUNC;
884static int builtin_shift(char **argv) FAST_FUNC;
885static int builtin_source(char **argv) FAST_FUNC;
886static int builtin_test(char **argv) FAST_FUNC;
887static int builtin_trap(char **argv) FAST_FUNC;
888static int builtin_type(char **argv) FAST_FUNC;
889static int builtin_true(char **argv) FAST_FUNC;
890static int builtin_umask(char **argv) FAST_FUNC;
891static int builtin_unset(char **argv) FAST_FUNC;
892static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000893#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200894static int builtin_break(char **argv) FAST_FUNC;
895static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000896#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000897#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200898static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000899#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000900
901/* Table of built-in functions. They can be forked or not, depending on
902 * context: within pipes, they fork. As simple commands, they do not.
903 * When used in non-forking context, they can change global variables
904 * in the parent shell process. If forked, of course they cannot.
905 * For example, 'unset foo | whatever' will parse and run, but foo will
906 * still be set at the end. */
907struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100908 const char *b_cmd;
909 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000910#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100911 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200912# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000913#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200914# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000915#endif
916};
917
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200918static const struct built_in_command bltins1[] = {
919 BLTIN("." , builtin_source , "Run commands in a file"),
920 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000921#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200922 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000923#endif
924#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200925 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000926#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200927 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000928#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200929 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000930#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200931 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
932 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
933 BLTIN("exit" , builtin_exit , "Exit"),
934 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000935#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200936 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000937#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000938#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200939 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000940#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200941#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200942 BLTIN("history" , builtin_history , "Show command history"),
943#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000944#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200945 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000946#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200947#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200948 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200949#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000950#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200951 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000952#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200953 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000954#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200955 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000956#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200957 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
958 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200959#if ENABLE_HUSH_BASH_COMPAT
960 BLTIN("source" , builtin_source , "Run commands in a file"),
961#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200962 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko2bba5912014-03-14 12:43:57 +0100963 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100964 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100965 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200966 BLTIN("umask" , builtin_umask , "Set file creation mask"),
967 BLTIN("unset" , builtin_unset , "Unset variables"),
968 BLTIN("wait" , builtin_wait , "Wait for process"),
969};
970/* For now, echo and test are unconditionally enabled.
971 * Maybe make it configurable? */
972static const struct built_in_command bltins2[] = {
973 BLTIN("[" , builtin_test , NULL),
974 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400975#if ENABLE_PRINTF
976 BLTIN("printf" , builtin_printf , NULL),
977#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200978 BLTIN("pwd" , builtin_pwd , NULL),
979 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000980};
981
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000982
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000983/* Debug printouts.
984 */
985#if HUSH_DEBUG
986/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100987# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000988# define debug_enter() (G.debug_indent++)
989# define debug_leave() (G.debug_indent--)
990#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200991# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000992# define debug_enter() ((void)0)
993# define debug_leave() ((void)0)
994#endif
995
996#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100997# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000998#endif
999
1000#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001001# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001002#endif
1003
1004#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001005#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001006#endif
1007
1008#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001009# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001010#endif
1011
1012#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001013# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001014# define DEBUG_JOBS 1
1015#else
1016# define DEBUG_JOBS 0
1017#endif
1018
1019#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001020# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001021# define DEBUG_EXPAND 1
1022#else
1023# define DEBUG_EXPAND 0
1024#endif
1025
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001026#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001027# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001028#endif
1029
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001030#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001031# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001032# define DEBUG_GLOB 1
1033#else
1034# define DEBUG_GLOB 0
1035#endif
1036
1037#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001038# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001039#endif
1040
1041#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001042# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001043#endif
1044
1045#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001046# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001047# define DEBUG_CLEAN 1
1048#else
1049# define DEBUG_CLEAN 0
1050#endif
1051
1052#if DEBUG_EXPAND
1053static void debug_print_strings(const char *prefix, char **vv)
1054{
1055 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001056 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001057 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001058 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001059}
1060#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001061# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001062#endif
1063
1064
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001065/* Leak hunting. Use hush_leaktool.sh for post-processing.
1066 */
1067#if LEAK_HUNTING
1068static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001069{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001070 void *ptr = xmalloc((size + 0xff) & ~0xff);
1071 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1072 return ptr;
1073}
1074static void *xxrealloc(int lineno, void *ptr, size_t size)
1075{
1076 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1077 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1078 return ptr;
1079}
1080static char *xxstrdup(int lineno, const char *str)
1081{
1082 char *ptr = xstrdup(str);
1083 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1084 return ptr;
1085}
1086static void xxfree(void *ptr)
1087{
1088 fdprintf(2, "free %p\n", ptr);
1089 free(ptr);
1090}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001091# define xmalloc(s) xxmalloc(__LINE__, s)
1092# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1093# define xstrdup(s) xxstrdup(__LINE__, s)
1094# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001095#endif
1096
1097
1098/* Syntax and runtime errors. They always abort scripts.
1099 * In interactive use they usually discard unparsed and/or unexecuted commands
1100 * and return to the prompt.
1101 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1102 */
1103#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001104# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001105# define syntax_error(lineno, msg) syntax_error(msg)
1106# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1107# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1108# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1109# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001110#endif
1111
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001112static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001113{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001114 va_list p;
1115
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001116#if HUSH_DEBUG >= 2
1117 bb_error_msg("hush.c:%u", lineno);
1118#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001119 va_start(p, fmt);
1120 bb_verror_msg(fmt, p, NULL);
1121 va_end(p);
1122 if (!G_interactive_fd)
1123 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001124}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001125
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001126static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001127{
1128 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001129 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001130 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001131 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001132}
1133
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001134static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001135{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001136 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001137}
1138
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001139static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001140{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001141 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001142}
1143
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001144static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001145{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001146 char msg[2] = { ch, '\0' };
1147 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001148}
1149
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001150static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001151{
1152 char msg[2];
1153 msg[0] = ch;
1154 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001155 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001156}
1157
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001158#if HUSH_DEBUG < 2
1159# undef die_if_script
1160# undef syntax_error
1161# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001162# undef syntax_error_unterm_ch
1163# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001164# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001165#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001166# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001167# define syntax_error(msg) syntax_error(__LINE__, msg)
1168# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1169# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1170# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1171# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001172#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001173
Denis Vlasenko552433b2009-04-04 19:29:21 +00001174
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001175#if ENABLE_HUSH_INTERACTIVE
1176static void cmdedit_update_prompt(void);
1177#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001178# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001179#endif
1180
1181
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001182/* Utility functions
1183 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001184/* Replace each \x with x in place, return ptr past NUL. */
1185static char *unbackslash(char *src)
1186{
Denys Vlasenko71885402009-09-24 01:44:13 +02001187 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001188 while (1) {
1189 if (*src == '\\')
1190 src++;
1191 if ((*dst++ = *src++) == '\0')
1192 break;
1193 }
1194 return dst;
1195}
1196
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001197static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001198{
1199 int i;
1200 unsigned count1;
1201 unsigned count2;
1202 char **v;
1203
1204 v = strings;
1205 count1 = 0;
1206 if (v) {
1207 while (*v) {
1208 count1++;
1209 v++;
1210 }
1211 }
1212 count2 = 0;
1213 v = add;
1214 while (*v) {
1215 count2++;
1216 v++;
1217 }
1218 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1219 v[count1 + count2] = NULL;
1220 i = count2;
1221 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001222 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001223 return v;
1224}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001225#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001226static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1227{
1228 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1229 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1230 return ptr;
1231}
1232#define add_strings_to_strings(strings, add, need_to_dup) \
1233 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1234#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001235
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001236/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001237static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001238{
1239 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001240 v[0] = add;
1241 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001242 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001243}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001244#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001245static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1246{
1247 char **ptr = add_string_to_strings(strings, add);
1248 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1249 return ptr;
1250}
1251#define add_string_to_strings(strings, add) \
1252 xx_add_string_to_strings(__LINE__, strings, add)
1253#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001254
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001255static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001256{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001257 char **v;
1258
1259 if (!strings)
1260 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001261 v = strings;
1262 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001263 free(*v);
1264 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001265 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001266 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001267}
1268
Denis Vlasenko76d50412008-06-10 16:19:39 +00001269
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001270static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1271{
1272 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1273 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1274 if (newfd < 0) {
1275 /* fd was not open? */
1276 if (errno == EBADF)
1277 return fd;
1278 xfunc_die();
1279 }
1280 close(fd);
1281 return newfd;
1282}
1283
1284
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001285/* Manipulating the list of open FILEs */
1286static FILE *remember_FILE(FILE *fp)
1287{
1288 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001289 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001290 n->next = G.FILE_list;
1291 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001292 n->fp = fp;
1293 n->fd = fileno(fp);
1294 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001295 }
1296 return fp;
1297}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001298static void fclose_and_forget(FILE *fp)
1299{
1300 struct FILE_list **pp = &G.FILE_list;
1301 while (*pp) {
1302 struct FILE_list *cur = *pp;
1303 if (cur->fp == fp) {
1304 *pp = cur->next;
1305 free(cur);
1306 break;
1307 }
1308 pp = &cur->next;
1309 }
1310 fclose(fp);
1311}
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001312static int save_FILEs_on_redirect(int fd)
1313{
1314 struct FILE_list *fl = G.FILE_list;
1315 while (fl) {
1316 if (fd == fl->fd) {
1317 /* We use it only on script files, they are all CLOEXEC */
1318 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1319 return 1;
1320 }
1321 fl = fl->next;
1322 }
1323 return 0;
1324}
1325static void restore_redirected_FILEs(void)
1326{
1327 struct FILE_list *fl = G.FILE_list;
1328 while (fl) {
1329 int should_be = fileno(fl->fp);
1330 if (fl->fd != should_be) {
1331 xmove_fd(fl->fd, should_be);
1332 fl->fd = should_be;
1333 }
1334 fl = fl->next;
1335 }
1336}
1337#if ENABLE_FEATURE_SH_STANDALONE
1338static void close_all_FILE_list(void)
1339{
1340 struct FILE_list *fl = G.FILE_list;
1341 while (fl) {
1342 /* fclose would also free FILE object.
1343 * It is disastrous if we share memory with a vforked parent.
1344 * I'm not sure we never come here after vfork.
1345 * Therefore just close fd, nothing more.
1346 */
1347 /*fclose(fl->fp); - unsafe */
1348 close(fl->fd);
1349 fl = fl->next;
1350 }
1351}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001352#endif
1353
1354
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001355/* Helpers for setting new $n and restoring them back
1356 */
1357typedef struct save_arg_t {
1358 char *sv_argv0;
1359 char **sv_g_argv;
1360 int sv_g_argc;
1361 smallint sv_g_malloced;
1362} save_arg_t;
1363
1364static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1365{
1366 int n;
1367
1368 sv->sv_argv0 = argv[0];
1369 sv->sv_g_argv = G.global_argv;
1370 sv->sv_g_argc = G.global_argc;
1371 sv->sv_g_malloced = G.global_args_malloced;
1372
1373 argv[0] = G.global_argv[0]; /* retain $0 */
1374 G.global_argv = argv;
1375 G.global_args_malloced = 0;
1376
1377 n = 1;
1378 while (*++argv)
1379 n++;
1380 G.global_argc = n;
1381}
1382
1383static void restore_G_args(save_arg_t *sv, char **argv)
1384{
1385 char **pp;
1386
1387 if (G.global_args_malloced) {
1388 /* someone ran "set -- arg1 arg2 ...", undo */
1389 pp = G.global_argv;
1390 while (*++pp) /* note: does not free $0 */
1391 free(*pp);
1392 free(G.global_argv);
1393 }
1394 argv[0] = sv->sv_argv0;
1395 G.global_argv = sv->sv_g_argv;
1396 G.global_argc = sv->sv_g_argc;
1397 G.global_args_malloced = sv->sv_g_malloced;
1398}
1399
1400
Denis Vlasenkod5762932009-03-31 11:22:57 +00001401/* Basic theory of signal handling in shell
1402 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001403 * This does not describe what hush does, rather, it is current understanding
1404 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001405 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1406 *
1407 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1408 * is finished or backgrounded. It is the same in interactive and
1409 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001410 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001411 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001412 * backgrounds (i.e. stops) or kills all members of currently running
1413 * pipe.
1414 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001415 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001416 * or by SIGINT in interactive shell.
1417 *
1418 * Trap handlers will execute even within trap handlers. (right?)
1419 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001420 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1421 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001422 *
1423 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001424 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001425 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001426 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001427 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001428 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001429 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001430 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001431 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001432 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001433 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001434 *
1435 * SIGQUIT: ignore
1436 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001437 * SIGHUP (interactive):
1438 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001439 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001440 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1441 * that all pipe members are stopped. Try this in bash:
1442 * while :; do :; done - ^Z does not background it
1443 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001444 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001445 * of the command line, show prompt. NB: ^C does not send SIGINT
1446 * to interactive shell while shell is waiting for a pipe,
1447 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001448 * Example 1: this waits 5 sec, but does not execute ls:
1449 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1450 * Example 2: this does not wait and does not execute ls:
1451 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1452 * Example 3: this does not wait 5 sec, but executes ls:
1453 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001454 * Example 4: this does not wait and does not execute ls:
1455 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001456 *
1457 * (What happens to signals which are IGN on shell start?)
1458 * (What happens with signal mask on shell start?)
1459 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001460 * Old implementation
1461 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001462 * We use in-kernel pending signal mask to determine which signals were sent.
1463 * We block all signals which we don't want to take action immediately,
1464 * i.e. we block all signals which need to have special handling as described
1465 * above, and all signals which have traps set.
1466 * After each pipe execution, we extract any pending signals via sigtimedwait()
1467 * and act on them.
1468 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001469 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001470 * sigset_t blocked_set: current blocked signal set
1471 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001472 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001473 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001474 * "trap 'cmd' SIGxxx":
1475 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001476 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001477 * unblock signals with special interactive handling
1478 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001479 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001480 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001481 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001482 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001483 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001484 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001485 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001486 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001487 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001488 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001489 * Standard says "When a subshell is entered, traps that are not being ignored
1490 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001491 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001492 *
1493 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001494 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001495 * masked signals are not visible!
1496 *
1497 * New implementation
1498 * ==================
1499 * We record each signal we are interested in by installing signal handler
1500 * for them - a bit like emulating kernel pending signal mask in userspace.
1501 * We are interested in: signals which need to have special handling
1502 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001503 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001504 * After each pipe execution, we extract any pending signals
1505 * and act on them.
1506 *
1507 * unsigned special_sig_mask: a mask of shell-special signals.
1508 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1509 * char *traps[sig] if trap for sig is set (even if it's '').
1510 * sigset_t pending_set: set of sigs we received.
1511 *
1512 * "trap - SIGxxx":
1513 * if sig is in special_sig_mask, set handler back to:
1514 * record_pending_signo, or to IGN if it's a tty stop signal
1515 * if sig is in fatal_sig_mask, set handler back to sigexit.
1516 * else: set handler back to SIG_DFL
1517 * "trap 'cmd' SIGxxx":
1518 * set handler to record_pending_signo.
1519 * "trap '' SIGxxx":
1520 * set handler to SIG_IGN.
1521 * after [v]fork, if we plan to be a shell:
1522 * set signals with special interactive handling to SIG_DFL
1523 * (because child shell is not interactive),
1524 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1525 * after [v]fork, if we plan to exec:
1526 * POSIX says fork clears pending signal mask in child - no need to clear it.
1527 *
1528 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1529 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1530 *
1531 * Note (compat):
1532 * Standard says "When a subshell is entered, traps that are not being ignored
1533 * are set to the default actions". bash interprets it so that traps which
1534 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001535 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001536enum {
1537 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001538 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001539 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001540 | (1 << SIGHUP)
1541 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001542 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001543#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001544 | (1 << SIGTTIN)
1545 | (1 << SIGTTOU)
1546 | (1 << SIGTSTP)
1547#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001548 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001549};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001550
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001551static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001552{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001553 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001554#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001555 if (sig == SIGCHLD) {
1556 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001557//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 +02001558 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001559#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001560}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001561
Denys Vlasenko0806e402011-05-12 23:06:20 +02001562static sighandler_t install_sighandler(int sig, sighandler_t handler)
1563{
1564 struct sigaction old_sa;
1565
1566 /* We could use signal() to install handlers... almost:
1567 * except that we need to mask ALL signals while handlers run.
1568 * I saw signal nesting in strace, race window isn't small.
1569 * SA_RESTART is also needed, but in Linux, signal()
1570 * sets SA_RESTART too.
1571 */
1572 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1573 /* sigfillset(&G.sa.sa_mask); - already done */
1574 /* G.sa.sa_flags = SA_RESTART; - already done */
1575 G.sa.sa_handler = handler;
1576 sigaction(sig, &G.sa, &old_sa);
1577 return old_sa.sa_handler;
1578}
1579
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001580static void hush_exit(int exitcode) NORETURN;
1581static void fflush_and__exit(void) NORETURN;
1582static void restore_ttypgrp_and__exit(void) NORETURN;
1583
1584static void restore_ttypgrp_and__exit(void)
1585{
1586 /* xfunc has failed! die die die */
1587 /* no EXIT traps, this is an escape hatch! */
1588 G.exiting = 1;
1589 hush_exit(xfunc_error_retval);
1590}
1591
1592/* Needed only on some libc:
1593 * It was observed that on exit(), fgetc'ed buffered data
1594 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1595 * With the net effect that even after fork(), not vfork(),
1596 * exit() in NOEXECed applet in "sh SCRIPT":
1597 * noexec_applet_here
1598 * echo END_OF_SCRIPT
1599 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1600 * This makes "echo END_OF_SCRIPT" executed twice.
1601 * Similar problems can be seen with die_if_script() -> xfunc_die()
1602 * and in `cmd` handling.
1603 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1604 */
1605static void fflush_and__exit(void)
1606{
1607 fflush_all();
1608 _exit(xfunc_error_retval);
1609}
1610
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001611#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001612
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001613/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001614# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001615/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001616# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001617
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001618/* Restores tty foreground process group, and exits.
1619 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001620 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001621 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001622 * We also call it if xfunc is exiting.
1623 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001624static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001625static void sigexit(int sig)
1626{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001627 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001628 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001629 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1630 /* Disable all signals: job control, SIGPIPE, etc.
1631 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1632 */
1633 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001634 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001635 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001636
1637 /* Not a signal, just exit */
1638 if (sig <= 0)
1639 _exit(- sig);
1640
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001641 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001642}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001643#else
1644
Denys Vlasenko8391c482010-05-22 17:50:43 +02001645# define disable_restore_tty_pgrp_on_exit() ((void)0)
1646# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001647
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001648#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001649
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001650static sighandler_t pick_sighandler(unsigned sig)
1651{
1652 sighandler_t handler = SIG_DFL;
1653 if (sig < sizeof(unsigned)*8) {
1654 unsigned sigmask = (1 << sig);
1655
1656#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001657 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001658 if (G_fatal_sig_mask & sigmask)
1659 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001660 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001661#endif
1662 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001663 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001664 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001665 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001666 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001667 * in an endless loop when we try to do some
1668 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001669 */
1670 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1671 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001672 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001673 }
1674 return handler;
1675}
1676
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001677/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001678static void hush_exit(int exitcode)
1679{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001680#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1681 save_history(G.line_input_state);
1682#endif
1683
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001684 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001685 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001686 char *argv[3];
1687 /* argv[0] is unused */
1688 argv[1] = G.traps[0];
1689 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001690 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001691 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001692 * "trap" will still show it, if executed
1693 * in the handler */
1694 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001695 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001696
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001697#if ENABLE_FEATURE_CLEAN_UP
1698 {
1699 struct variable *cur_var;
1700 if (G.cwd != bb_msg_unknown)
1701 free((char*)G.cwd);
1702 cur_var = G.top_var;
1703 while (cur_var) {
1704 struct variable *tmp = cur_var;
1705 if (!cur_var->max_len)
1706 free(cur_var->varstr);
1707 cur_var = cur_var->next;
1708 free(tmp);
1709 }
1710 }
1711#endif
1712
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001713 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001714#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001715 sigexit(- (exitcode & 0xff));
1716#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001717 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001718#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001719}
1720
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001721
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001722//TODO: return a mask of ALL handled sigs?
1723static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001724{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001725 int last_sig = 0;
1726
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001727 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001728 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001729
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001730 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001731 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001732 sig = 0;
1733 do {
1734 sig++;
1735 if (sigismember(&G.pending_set, sig)) {
1736 sigdelset(&G.pending_set, sig);
1737 goto got_sig;
1738 }
1739 } while (sig < NSIG);
1740 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001741 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001742 if (G.traps && G.traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001743 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001744 if (G.traps[sig][0]) {
1745 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001746 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001747 char *argv[3];
1748 /* argv[0] is unused */
1749 argv[1] = G.traps[sig];
1750 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001751 save_rcode = G.last_exitcode;
1752 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001753 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001754 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001755 } /* else: "" trap, ignoring signal */
1756 continue;
1757 }
1758 /* not a trap: special action */
1759 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001760 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001761 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001762 /* Builtin was ^C'ed, make it look prettier: */
1763 bb_putchar('\n');
1764 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001765 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001766 break;
1767#if ENABLE_HUSH_JOB
1768 case SIGHUP: {
1769 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001770 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001771 /* bash is observed to signal whole process groups,
1772 * not individual processes */
1773 for (job = G.job_list; job; job = job->next) {
1774 if (job->pgrp <= 0)
1775 continue;
1776 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1777 if (kill(- job->pgrp, SIGHUP) == 0)
1778 kill(- job->pgrp, SIGCONT);
1779 }
1780 sigexit(SIGHUP);
1781 }
1782#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001783#if ENABLE_HUSH_FAST
1784 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001785 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001786 G.count_SIGCHLD++;
1787//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1788 /* Note:
1789 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1790 * This simplifies wait builtin a bit.
1791 */
1792 break;
1793#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001794 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001795 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001796 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001797 /* Note:
1798 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1799 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001800 * in interactive shell, because TERM is ignored.
1801 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001802 break;
1803 }
1804 }
1805 return last_sig;
1806}
1807
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001808
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001809static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001810{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001811 if (force || G.cwd == NULL) {
1812 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1813 * we must not try to free(bb_msg_unknown) */
1814 if (G.cwd == bb_msg_unknown)
1815 G.cwd = NULL;
1816 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1817 if (!G.cwd)
1818 G.cwd = bb_msg_unknown;
1819 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001820 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001821}
1822
Denis Vlasenko83506862007-11-23 13:11:42 +00001823
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001824/*
1825 * Shell and environment variable support
1826 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001827static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001828{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001829 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001830 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001831
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001832 pp = &G.top_var;
1833 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001834 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001835 return pp;
1836 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001837 }
1838 return NULL;
1839}
1840
Denys Vlasenko03dad222010-01-12 23:29:57 +01001841static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001842{
Denys Vlasenko29082232010-07-16 13:52:32 +02001843 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001844 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001845
1846 if (G.expanded_assignments) {
1847 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001848 while (*cpp) {
1849 char *cp = *cpp;
1850 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1851 return cp + len + 1;
1852 cpp++;
1853 }
1854 }
1855
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001856 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001857 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001858 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001859
Denys Vlasenkodea47882009-10-09 15:40:49 +02001860 if (strcmp(name, "PPID") == 0)
1861 return utoa(G.root_ppid);
1862 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001863#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001864 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001865 return utoa(next_random(&G.random_gen));
1866#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001867 return NULL;
1868}
1869
1870/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001871 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001872 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001873 * 0: do not change export flag
1874 * (if creating new variable, flag will be 0)
1875 * 1: set export flag and putenv the variable
1876 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001877 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001878 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001879#if !BB_MMU && ENABLE_HUSH_LOCAL
1880/* all params are used */
1881#elif BB_MMU && ENABLE_HUSH_LOCAL
1882#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1883 set_local_var(str, flg_export, local_lvl)
1884#elif BB_MMU && !ENABLE_HUSH_LOCAL
1885#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001886 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001887#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1888#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1889 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001890#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001891static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001892{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001893 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001894 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001895 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001896 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001897 int name_len;
1898
Denis Vlasenko950bd722009-04-21 11:23:56 +00001899 eq_sign = strchr(str, '=');
1900 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001901 free(str);
1902 return -1;
1903 }
1904
Denis Vlasenko950bd722009-04-21 11:23:56 +00001905 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001906 var_pp = &G.top_var;
1907 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001908 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001909 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001910 continue;
1911 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001912
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001913 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001914 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001915#if !BB_MMU
1916 if (!flg_read_only)
1917#endif
1918 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001919 free(str);
1920 return -1;
1921 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001922 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001923 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1924 *eq_sign = '\0';
1925 unsetenv(str);
1926 *eq_sign = '=';
1927 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001928#if ENABLE_HUSH_LOCAL
1929 if (cur->func_nest_level < local_lvl) {
1930 /* New variable is declared as local,
1931 * and existing one is global, or local
1932 * from enclosing function.
1933 * Remove and save old one: */
1934 *var_pp = cur->next;
1935 cur->next = *G.shadowed_vars_pp;
1936 *G.shadowed_vars_pp = cur;
1937 /* bash 3.2.33(1) and exported vars:
1938 * # export z=z
1939 * # f() { local z=a; env | grep ^z; }
1940 * # f
1941 * z=a
1942 * # env | grep ^z
1943 * z=z
1944 */
1945 if (cur->flg_export)
1946 flg_export = 1;
1947 break;
1948 }
1949#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001950 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001951 free_and_exp:
1952 free(str);
1953 goto exp;
1954 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001955 if (cur->max_len != 0) {
1956 if (cur->max_len >= strlen(str)) {
1957 /* This one is from startup env, reuse space */
1958 strcpy(cur->varstr, str);
1959 goto free_and_exp;
1960 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001961 /* Can't reuse */
1962 cur->max_len = 0;
1963 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02001964 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001965 /* max_len == 0 signifies "malloced" var, which we can
1966 * (and have to) free. But we can't free(cur->varstr) here:
1967 * if cur->flg_export is 1, it is in the environment.
1968 * We should either unsetenv+free, or wait until putenv,
1969 * then putenv(new)+free(old).
1970 */
1971 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001972 goto set_str_and_exp;
1973 }
1974
Denys Vlasenko295fef82009-06-03 12:47:26 +02001975 /* Not found - create new variable struct */
1976 cur = xzalloc(sizeof(*cur));
1977#if ENABLE_HUSH_LOCAL
1978 cur->func_nest_level = local_lvl;
1979#endif
1980 cur->next = *var_pp;
1981 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001982
1983 set_str_and_exp:
1984 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001985#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001986 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001987#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001988 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001989 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001990 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001991 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1992 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001993 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001994 if (flg_export == -1) {
1995 cur->flg_export = 0;
1996 /* unsetenv was already done */
1997 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001998 int i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001999 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002000 i = putenv(cur->varstr);
2001 /* only now we can free old exported malloced string */
2002 free(free_me);
2003 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002004 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002005 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002006 free(free_me);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002007 return 0;
2008}
2009
Denys Vlasenko6db47842009-09-05 20:15:17 +02002010/* Used at startup and after each cd */
2011static void set_pwd_var(int exp)
2012{
2013 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2014 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2015}
2016
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002017static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002018{
2019 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002020 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002021
2022 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002023 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002024 var_pp = &G.top_var;
2025 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002026 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2027 if (cur->flg_read_only) {
2028 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002029 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002030 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002031 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002032 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2033 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002034 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2035 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002036 if (!cur->max_len)
2037 free(cur->varstr);
2038 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002039 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002040 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002041 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002042 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002043 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002044}
2045
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002046static int unset_local_var(const char *name)
2047{
2048 return unset_local_var_len(name, strlen(name));
2049}
2050
2051static void unset_vars(char **strings)
2052{
2053 char **v;
2054
2055 if (!strings)
2056 return;
2057 v = strings;
2058 while (*v) {
2059 const char *eq = strchrnul(*v, '=');
2060 unset_local_var_len(*v, (int)(eq - *v));
2061 v++;
2062 }
2063 free(strings);
2064}
2065
Denys Vlasenko03dad222010-01-12 23:29:57 +01002066static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002067{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002068 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01002069 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002070}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002071
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002072
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002073/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002074 * Helpers for "var1=val1 var2=val2 cmd" feature
2075 */
2076static void add_vars(struct variable *var)
2077{
2078 struct variable *next;
2079
2080 while (var) {
2081 next = var->next;
2082 var->next = G.top_var;
2083 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002084 if (var->flg_export) {
2085 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002086 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002087 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002088 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002089 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002090 var = next;
2091 }
2092}
2093
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002094static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002095{
2096 char **s;
2097 struct variable *old = NULL;
2098
2099 if (!strings)
2100 return old;
2101 s = strings;
2102 while (*s) {
2103 struct variable *var_p;
2104 struct variable **var_pp;
2105 char *eq;
2106
2107 eq = strchr(*s, '=');
2108 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002109 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002110 if (var_pp) {
2111 /* Remove variable from global linked list */
2112 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002113 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002114 *var_pp = var_p->next;
2115 /* Add it to returned list */
2116 var_p->next = old;
2117 old = var_p;
2118 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002119 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002120 }
2121 s++;
2122 }
2123 return old;
2124}
2125
2126
2127/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002128 * Unicode helper
2129 */
2130static void reinit_unicode_for_hush(void)
2131{
2132 /* Unicode support should be activated even if LANG is set
2133 * _during_ shell execution, not only if it was set when
2134 * shell was started. Therefore, re-check LANG every time:
2135 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002136 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2137 || ENABLE_UNICODE_USING_LOCALE
2138 ) {
2139 const char *s = get_local_var_value("LC_ALL");
2140 if (!s) s = get_local_var_value("LC_CTYPE");
2141 if (!s) s = get_local_var_value("LANG");
2142 reinit_unicode(s);
2143 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002144}
2145
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002146/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002147 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002148 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002149
2150#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002151/* To test correct lineedit/interactive behavior, type from command line:
2152 * echo $P\
2153 * \
2154 * AT\
2155 * H\
2156 * \
2157 * It excercises a lot of corner cases.
2158 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002159static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002160{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002161 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002162 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002163 if (G.PS1 == NULL)
2164 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002165 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002166 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002167 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002168 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002169 if (G.PS2 == NULL)
2170 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002171}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002172static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002173{
2174 const char *prompt_str;
2175 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002176 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2177 /* Set up the prompt */
2178 if (promptmode == 0) { /* PS1 */
2179 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002180 /* bash uses $PWD value, even if it is set by user.
2181 * It uses current dir only if PWD is unset.
2182 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002183 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002184 prompt_str = G.PS1;
2185 } else
2186 prompt_str = G.PS2;
2187 } else
2188 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002189 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002190 return prompt_str;
2191}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002192static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002193{
2194 int r;
2195 const char *prompt_str;
2196
2197 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002198# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002199 do {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002200 reinit_unicode_for_hush();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002201 G.flag_SIGINT = 0;
2202 /* buglet: SIGINT will not make new prompt to appear _at once_,
2203 * only after <Enter>. (^C will work) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002204 r = read_line_input(G.line_input_state, prompt_str,
2205 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2206 /*timeout*/ -1
2207 );
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002208 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002209 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002210 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002211 if (r < 0) {
2212 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002213 i->p = NULL;
2214 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002215 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002216 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002217 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002218 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002219# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002220 do {
2221 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002222 if (i->last_char == '\0' || i->last_char == '\n') {
2223 /* Why check_and_run_traps here? Try this interactively:
2224 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2225 * $ <[enter], repeatedly...>
2226 * Without check_and_run_traps, handler never runs.
2227 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002228 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002229 fputs(prompt_str, stdout);
2230 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002231 fflush_all();
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002232 r = fgetc(i->file);
2233 } while (G.flag_SIGINT || r == '\0');
2234 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002235# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002236}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002237/* This is the magic location that prints prompts
2238 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002239static int fgetc_interactive(struct in_str *i)
2240{
2241 int ch;
2242 /* If it's interactive stdin, get new line. */
2243 if (G_interactive_fd && i->file == stdin) {
2244 /* Returns first char (or EOF), the rest is in i->p[] */
2245 ch = get_user_input(i);
2246 i->promptmode = 1; /* PS2 */
2247 } else {
2248 /* Not stdin: script file, sourced file, etc */
2249 do ch = fgetc(i->file); while (ch == '\0');
2250 }
2251 return ch;
2252}
2253#else
2254static inline int fgetc_interactive(struct in_str *i)
2255{
2256 int ch;
2257 do ch = fgetc(i->file); while (ch == '\0');
2258 return ch;
2259}
2260#endif /* INTERACTIVE */
2261
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002262static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002263{
2264 int ch;
2265
Denys Vlasenko4074d492016-09-30 01:49:53 +02002266#if ENABLE_FEATURE_EDITING
2267 /* This can be stdin, check line editing char[] buffer */
2268 if (i->p && *i->p != '\0') {
2269 ch = (unsigned char)*i->p++;
2270 goto out;
2271 }
2272#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002273 /* peek_buf[] is an int array, not char. Can contain EOF. */
2274 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002275 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002276 int ch2 = i->peek_buf[1];
2277 i->peek_buf[0] = ch2;
2278 if (ch2 == 0) /* very likely, avoid redundant write */
2279 goto out;
2280 i->peek_buf[1] = 0;
2281 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002282 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002283
Denys Vlasenko4074d492016-09-30 01:49:53 +02002284 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002285 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002286 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002287 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002288 return ch;
2289}
2290
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002291static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002292{
2293 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002294
Denys Vlasenko4074d492016-09-30 01:49:53 +02002295#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002296 /* This can be stdin, check line editing char[] buffer */
2297 if (i->p && *i->p != '\0')
2298 return (unsigned char)*i->p;
2299#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002300 /* peek_buf[] is an int array, not char. Can contain EOF. */
2301 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002302 if (ch != 0)
2303 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002304
Denys Vlasenko4074d492016-09-30 01:49:53 +02002305 /* Need to get a new char */
2306 ch = fgetc_interactive(i);
2307 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2308
2309 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2310#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2311 if (i->p) {
2312 i->p -= 1;
2313 return ch;
2314 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002315#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002316 i->peek_buf[0] = ch;
2317 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002318 return ch;
2319}
2320
2321static int FAST_FUNC static_get(struct in_str *i)
2322{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002323 int ch = (unsigned char)*i->p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002324 if (ch != '\0') {
2325 i->p++;
2326 i->last_char = ch;
2327 return ch;
2328 }
2329 return EOF;
2330}
2331
2332static int FAST_FUNC static_peek(struct in_str *i)
2333{
2334 /* Doesn't report EOF on NUL. None of the callers care. */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002335 return (unsigned char)*i->p;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002336}
2337
Denys Vlasenko4074d492016-09-30 01:49:53 +02002338/* Only ever called if i_peek() was called, and did not return EOF.
2339 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2340 * not end-of-line. Therefore we never need to read a new editing line here.
2341 */
2342static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002343{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002344 int ch;
2345
2346 /* There are two cases when i->p[] buffer exists.
2347 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002348 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002349 * In both cases, we know that i->p[0] exists and not NUL, and
2350 * the peek2 result is in i->p[1].
2351 */
2352 if (i->p)
2353 return (unsigned char)i->p[1];
2354
2355 /* Now we know it is a file-based in_str. */
2356
2357 /* peek_buf[] is an int array, not char. Can contain EOF. */
2358 /* Is there 2nd char? */
2359 ch = i->peek_buf[1];
2360 if (ch == 0) {
2361 /* We did not read it yet, get it now */
2362 do ch = fgetc(i->file); while (ch == '\0');
2363 i->peek_buf[1] = ch;
2364 }
2365
2366 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2367 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002368}
2369
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002370static void setup_file_in_str(struct in_str *i, FILE *f)
2371{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002372 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002373 i->get = file_get;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002374 i->peek = file_peek;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002375 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002376 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002377 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002378}
2379
2380static void setup_string_in_str(struct in_str *i, const char *s)
2381{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002382 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002383 i->get = static_get;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002384 i->peek = static_peek;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002385 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002386 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002387}
2388
2389
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002390/*
2391 * o_string support
2392 */
2393#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002394
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002395static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002396{
2397 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002398 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002399 if (o->data)
2400 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002401}
2402
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002403static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002404{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002405 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002406 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002407}
2408
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002409static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2410{
2411 free(o->data);
2412}
2413
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002414static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002415{
2416 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002417 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002418 o->data = xrealloc(o->data, 1 + o->maxlen);
2419 }
2420}
2421
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002422static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002423{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002424 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002425 if (o->length < o->maxlen) {
2426 /* likely. avoid o_grow_by() call */
2427 add:
2428 o->data[o->length] = ch;
2429 o->length++;
2430 o->data[o->length] = '\0';
2431 return;
2432 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002433 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002434 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002435}
2436
Denys Vlasenko657086a2016-09-29 18:07:42 +02002437#if 0
2438/* Valid only if we know o_string is not empty */
2439static void o_delchr(o_string *o)
2440{
2441 o->length--;
2442 o->data[o->length] = '\0';
2443}
2444#endif
2445
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002446static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002447{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002448 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002449 memcpy(&o->data[o->length], str, len);
2450 o->length += len;
2451 o->data[o->length] = '\0';
2452}
2453
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002454static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002455{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002456 o_addblock(o, str, strlen(str));
2457}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002458
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002459#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002460static void nommu_addchr(o_string *o, int ch)
2461{
2462 if (o)
2463 o_addchr(o, ch);
2464}
2465#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002466# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002467#endif
2468
2469static void o_addstr_with_NUL(o_string *o, const char *str)
2470{
2471 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002472}
2473
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002474/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002475 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002476 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2477 * Apparently, on unquoted $v bash still does globbing
2478 * ("v='*.txt'; echo $v" prints all .txt files),
2479 * but NOT brace expansion! Thus, there should be TWO independent
2480 * quoting mechanisms on $v expansion side: one protects
2481 * $v from brace expansion, and other additionally protects "$v" against globbing.
2482 * We have only second one.
2483 */
2484
Denys Vlasenko9e800222010-10-03 14:28:04 +02002485#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002486# define MAYBE_BRACES "{}"
2487#else
2488# define MAYBE_BRACES ""
2489#endif
2490
Eric Andersen25f27032001-04-26 23:22:31 +00002491/* My analysis of quoting semantics tells me that state information
2492 * is associated with a destination, not a source.
2493 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002494static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002495{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002496 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002497 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002498 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002499 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002500 o_grow_by(o, sz);
2501 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002502 o->data[o->length] = '\\';
2503 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002504 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002505 o->data[o->length] = ch;
2506 o->length++;
2507 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002508}
2509
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002510static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002511{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002512 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002513 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2514 && strchr("*?[\\" MAYBE_BRACES, ch)
2515 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002516 sz++;
2517 o->data[o->length] = '\\';
2518 o->length++;
2519 }
2520 o_grow_by(o, sz);
2521 o->data[o->length] = ch;
2522 o->length++;
2523 o->data[o->length] = '\0';
2524}
2525
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002526static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002527{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002528 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002529 char ch;
2530 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002531 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002532 if (ordinary_cnt > len) /* paranoia */
2533 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002534 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002535 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002536 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002537 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002538 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002539
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002540 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002541 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002542 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002543 sz++;
2544 o->data[o->length] = '\\';
2545 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002546 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002547 o_grow_by(o, sz);
2548 o->data[o->length] = ch;
2549 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002550 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002551 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002552}
2553
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002554static void o_addQblock(o_string *o, const char *str, int len)
2555{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002556 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002557 o_addblock(o, str, len);
2558 return;
2559 }
2560 o_addqblock(o, str, len);
2561}
2562
Denys Vlasenko38292b62010-09-05 14:49:40 +02002563static void o_addQstr(o_string *o, const char *str)
2564{
2565 o_addQblock(o, str, strlen(str));
2566}
2567
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002568/* A special kind of o_string for $VAR and `cmd` expansion.
2569 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002570 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002571 * list[i] contains an INDEX (int!) into this string data.
2572 * It means that if list[] needs to grow, data needs to be moved higher up
2573 * but list[i]'s need not be modified.
2574 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002575 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002576 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2577 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002578#if DEBUG_EXPAND || DEBUG_GLOB
2579static void debug_print_list(const char *prefix, o_string *o, int n)
2580{
2581 char **list = (char**)o->data;
2582 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2583 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002584
2585 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002586 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 +02002587 prefix, list, n, string_start, o->length, o->maxlen,
2588 !!(o->o_expflags & EXP_FLAG_GLOB),
2589 o->has_quoted_part,
2590 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002591 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002592 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002593 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2594 o->data + (int)(uintptr_t)list[i] + string_start,
2595 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002596 i++;
2597 }
2598 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002599 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002600 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002601 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002602 }
2603}
2604#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002605# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002606#endif
2607
2608/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2609 * in list[n] so that it points past last stored byte so far.
2610 * It returns n+1. */
2611static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002612{
2613 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002614 int string_start;
2615 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002616
2617 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002618 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2619 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002620 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002621 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002622 /* list[n] points to string_start, make space for 16 more pointers */
2623 o->maxlen += 0x10 * sizeof(list[0]);
2624 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002625 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002626 memmove(list + n + 0x10, list + n, string_len);
2627 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002628 } else {
2629 debug_printf_list("list[%d]=%d string_start=%d\n",
2630 n, string_len, string_start);
2631 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002632 } else {
2633 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002634 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2635 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002636 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2637 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002638 o->has_empty_slot = 0;
2639 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002640 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002641 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002642 return n + 1;
2643}
2644
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002645/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002646static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002647{
2648 char **list = (char**)o->data;
2649 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2650
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002651 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002652}
2653
Denys Vlasenko9e800222010-10-03 14:28:04 +02002654#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002655/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2656 * first, it processes even {a} (no commas), second,
2657 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002658 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002659 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002660
2661/* Helper */
2662static int glob_needed(const char *s)
2663{
2664 while (*s) {
2665 if (*s == '\\') {
2666 if (!s[1])
2667 return 0;
2668 s += 2;
2669 continue;
2670 }
2671 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2672 return 1;
2673 s++;
2674 }
2675 return 0;
2676}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002677/* Return pointer to next closing brace or to comma */
2678static const char *next_brace_sub(const char *cp)
2679{
2680 unsigned depth = 0;
2681 cp++;
2682 while (*cp != '\0') {
2683 if (*cp == '\\') {
2684 if (*++cp == '\0')
2685 break;
2686 cp++;
2687 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002688 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002689 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002690 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002691 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002692 depth++;
2693 }
2694
2695 return *cp != '\0' ? cp : NULL;
2696}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002697/* Recursive brace globber. Note: may garble pattern[]. */
2698static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002699{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002700 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002701 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002702 const char *next;
2703 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002704 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002705 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002706
2707 debug_printf_glob("glob_brace('%s')\n", pattern);
2708
2709 begin = pattern;
2710 while (1) {
2711 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002712 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002713 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002714 /* Find the first sub-pattern and at the same time
2715 * find the rest after the closing brace */
2716 next = next_brace_sub(begin);
2717 if (next == NULL) {
2718 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002719 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002720 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002721 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002722 /* "{abc}" with no commas - illegal
2723 * brace expr, disregard and skip it */
2724 begin = next + 1;
2725 continue;
2726 }
2727 break;
2728 }
2729 if (*begin == '\\' && begin[1] != '\0')
2730 begin++;
2731 begin++;
2732 }
2733 debug_printf_glob("begin:%s\n", begin);
2734 debug_printf_glob("next:%s\n", next);
2735
2736 /* Now find the end of the whole brace expression */
2737 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002738 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002739 rest = next_brace_sub(rest);
2740 if (rest == NULL) {
2741 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002742 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002743 }
2744 debug_printf_glob("rest:%s\n", rest);
2745 }
2746 rest_len = strlen(++rest) + 1;
2747
2748 /* We are sure the brace expression is well-formed */
2749
2750 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002751 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002752
2753 /* We have a brace expression. BEGIN points to the opening {,
2754 * NEXT points past the terminator of the first element, and REST
2755 * points past the final }. We will accumulate result names from
2756 * recursive runs for each brace alternative in the buffer using
2757 * GLOB_APPEND. */
2758
2759 p = begin + 1;
2760 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002761 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002762 memcpy(
2763 mempcpy(
2764 mempcpy(new_pattern_buf,
2765 /* We know the prefix for all sub-patterns */
2766 pattern, begin - pattern),
2767 p, next - p),
2768 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002769
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002770 /* Note: glob_brace() may garble new_pattern_buf[].
2771 * That's why we re-copy prefix every time (1st memcpy above).
2772 */
2773 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002774 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002775 /* We saw the last entry */
2776 break;
2777 }
2778 p = next + 1;
2779 next = next_brace_sub(next);
2780 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002781 free(new_pattern_buf);
2782 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002783
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002784 simple_glob:
2785 {
2786 int gr;
2787 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002788
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002789 memset(&globdata, 0, sizeof(globdata));
2790 gr = glob(pattern, 0, NULL, &globdata);
2791 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2792 if (gr != 0) {
2793 if (gr == GLOB_NOMATCH) {
2794 globfree(&globdata);
2795 /* NB: garbles parameter */
2796 unbackslash(pattern);
2797 o_addstr_with_NUL(o, pattern);
2798 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2799 return o_save_ptr_helper(o, n);
2800 }
2801 if (gr == GLOB_NOSPACE)
2802 bb_error_msg_and_die(bb_msg_memory_exhausted);
2803 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2804 * but we didn't specify it. Paranoia again. */
2805 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2806 }
2807 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2808 char **argv = globdata.gl_pathv;
2809 while (1) {
2810 o_addstr_with_NUL(o, *argv);
2811 n = o_save_ptr_helper(o, n);
2812 argv++;
2813 if (!*argv)
2814 break;
2815 }
2816 }
2817 globfree(&globdata);
2818 }
2819 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002820}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002821/* Performs globbing on last list[],
2822 * saving each result as a new list[].
2823 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002824static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002825{
2826 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002827
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002828 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002829 if (!o->data)
2830 return o_save_ptr_helper(o, n);
2831 pattern = o->data + o_get_last_ptr(o, n);
2832 debug_printf_glob("glob pattern '%s'\n", pattern);
2833 if (!glob_needed(pattern)) {
2834 /* unbackslash last string in o in place, fix length */
2835 o->length = unbackslash(pattern) - o->data;
2836 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2837 return o_save_ptr_helper(o, n);
2838 }
2839
2840 copy = xstrdup(pattern);
2841 /* "forget" pattern in o */
2842 o->length = pattern - o->data;
2843 n = glob_brace(copy, o, n);
2844 free(copy);
2845 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002846 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002847 return n;
2848}
2849
Denys Vlasenko238081f2010-10-03 14:26:26 +02002850#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002851
2852/* Helper */
2853static int glob_needed(const char *s)
2854{
2855 while (*s) {
2856 if (*s == '\\') {
2857 if (!s[1])
2858 return 0;
2859 s += 2;
2860 continue;
2861 }
2862 if (*s == '*' || *s == '[' || *s == '?')
2863 return 1;
2864 s++;
2865 }
2866 return 0;
2867}
2868/* Performs globbing on last list[],
2869 * saving each result as a new list[].
2870 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002871static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002872{
2873 glob_t globdata;
2874 int gr;
2875 char *pattern;
2876
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002877 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002878 if (!o->data)
2879 return o_save_ptr_helper(o, n);
2880 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002881 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002882 if (!glob_needed(pattern)) {
2883 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002884 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002885 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002886 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002887 return o_save_ptr_helper(o, n);
2888 }
2889
2890 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002891 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2892 * If we glob "*.\*" and don't find anything, we need
2893 * to fall back to using literal "*.*", but GLOB_NOCHECK
2894 * will return "*.\*"!
2895 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002896 gr = glob(pattern, 0, NULL, &globdata);
2897 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002898 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002899 if (gr == GLOB_NOMATCH) {
2900 globfree(&globdata);
2901 goto literal;
2902 }
2903 if (gr == GLOB_NOSPACE)
2904 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002905 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2906 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002907 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002908 }
2909 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2910 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002911 /* "forget" pattern in o */
2912 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002913 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002914 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002915 n = o_save_ptr_helper(o, n);
2916 argv++;
2917 if (!*argv)
2918 break;
2919 }
2920 }
2921 globfree(&globdata);
2922 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002923 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002924 return n;
2925}
2926
Denys Vlasenko238081f2010-10-03 14:26:26 +02002927#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002928
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002929/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002930 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002931static int o_save_ptr(o_string *o, int n)
2932{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002933 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002934 /* If o->has_empty_slot, list[n] was already globbed
2935 * (if it was requested back then when it was filled)
2936 * so don't do that again! */
2937 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002938 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002939 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002940 return o_save_ptr_helper(o, n);
2941}
2942
2943/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002944static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002945{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002946 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002947 int string_start;
2948
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002949 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2950 if (DEBUG_EXPAND)
2951 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002952 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002953 list = (char**)o->data;
2954 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2955 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002956 while (n) {
2957 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002958 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002959 }
2960 return list;
2961}
2962
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002963static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002964
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002965/* Returns pi->next - next pipe in the list */
2966static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002967{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002968 struct pipe *next;
2969 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002970
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002971 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002972 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002973 struct command *command;
2974 struct redir_struct *r, *rnext;
2975
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002976 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002977 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002978 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002979 if (DEBUG_CLEAN) {
2980 int a;
2981 char **p;
2982 for (a = 0, p = command->argv; *p; a++, p++) {
2983 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2984 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002985 }
2986 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002987 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002988 }
2989 /* not "else if": on syntax error, we may have both! */
2990 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002991 debug_printf_clean(" begin group (cmd_type:%d)\n",
2992 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002993 free_pipe_list(command->group);
2994 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002995 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002996 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002997 /* else is crucial here.
2998 * If group != NULL, child_func is meaningless */
2999#if ENABLE_HUSH_FUNCTIONS
3000 else if (command->child_func) {
3001 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3002 command->child_func->parent_cmd = NULL;
3003 }
3004#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003005#if !BB_MMU
3006 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003007 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003008#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003009 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003010 debug_printf_clean(" redirect %d%s",
3011 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003012 /* guard against the case >$FOO, where foo is unset or blank */
3013 if (r->rd_filename) {
3014 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3015 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003016 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003017 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003018 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003019 rnext = r->next;
3020 free(r);
3021 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003022 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003023 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003024 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003025 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003026#if ENABLE_HUSH_JOB
3027 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003028 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003029#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003030
3031 next = pi->next;
3032 free(pi);
3033 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003034}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003035
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003036static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003037{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003038 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003039#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003040 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003041#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003042 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003043 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003044 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003045}
3046
3047
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003048/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003049
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003050#ifndef debug_print_tree
3051static void debug_print_tree(struct pipe *pi, int lvl)
3052{
3053 static const char *const PIPE[] = {
3054 [PIPE_SEQ] = "SEQ",
3055 [PIPE_AND] = "AND",
3056 [PIPE_OR ] = "OR" ,
3057 [PIPE_BG ] = "BG" ,
3058 };
3059 static const char *RES[] = {
3060 [RES_NONE ] = "NONE" ,
3061# if ENABLE_HUSH_IF
3062 [RES_IF ] = "IF" ,
3063 [RES_THEN ] = "THEN" ,
3064 [RES_ELIF ] = "ELIF" ,
3065 [RES_ELSE ] = "ELSE" ,
3066 [RES_FI ] = "FI" ,
3067# endif
3068# if ENABLE_HUSH_LOOPS
3069 [RES_FOR ] = "FOR" ,
3070 [RES_WHILE] = "WHILE",
3071 [RES_UNTIL] = "UNTIL",
3072 [RES_DO ] = "DO" ,
3073 [RES_DONE ] = "DONE" ,
3074# endif
3075# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3076 [RES_IN ] = "IN" ,
3077# endif
3078# if ENABLE_HUSH_CASE
3079 [RES_CASE ] = "CASE" ,
3080 [RES_CASE_IN ] = "CASE_IN" ,
3081 [RES_MATCH] = "MATCH",
3082 [RES_CASE_BODY] = "CASE_BODY",
3083 [RES_ESAC ] = "ESAC" ,
3084# endif
3085 [RES_XXXX ] = "XXXX" ,
3086 [RES_SNTX ] = "SNTX" ,
3087 };
3088 static const char *const CMDTYPE[] = {
3089 "{}",
3090 "()",
3091 "[noglob]",
3092# if ENABLE_HUSH_FUNCTIONS
3093 "func()",
3094# endif
3095 };
3096
3097 int pin, prn;
3098
3099 pin = 0;
3100 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003101 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003102 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3103 prn = 0;
3104 while (prn < pi->num_cmds) {
3105 struct command *command = &pi->cmds[prn];
3106 char **argv = command->argv;
3107
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003108 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003109 lvl*2, "", prn,
3110 command->assignment_cnt);
3111 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003112 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003113 CMDTYPE[command->cmd_type],
3114 argv
3115# if !BB_MMU
3116 , " group_as_string:", command->group_as_string
3117# else
3118 , "", ""
3119# endif
3120 );
3121 debug_print_tree(command->group, lvl+1);
3122 prn++;
3123 continue;
3124 }
3125 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003126 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003127 argv++;
3128 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003129 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003130 prn++;
3131 }
3132 pi = pi->next;
3133 pin++;
3134 }
3135}
3136#endif /* debug_print_tree */
3137
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003138static struct pipe *new_pipe(void)
3139{
Eric Andersen25f27032001-04-26 23:22:31 +00003140 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003141 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003142 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003143 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003144 return pi;
3145}
3146
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003147/* Command (member of a pipe) is complete, or we start a new pipe
3148 * if ctx->command is NULL.
3149 * No errors possible here.
3150 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003151static int done_command(struct parse_context *ctx)
3152{
3153 /* The command is really already in the pipe structure, so
3154 * advance the pipe counter and make a new, null command. */
3155 struct pipe *pi = ctx->pipe;
3156 struct command *command = ctx->command;
3157
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003158#if 0 /* Instead we emit error message at run time */
3159 if (ctx->pending_redirect) {
3160 /* For example, "cmd >" (no filename to redirect to) */
3161 die_if_script("syntax error: %s", "invalid redirect");
3162 ctx->pending_redirect = NULL;
3163 }
3164#endif
3165
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003166 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003167 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003168 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003169 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003170 }
3171 pi->num_cmds++;
3172 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003173 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003174 } else {
3175 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3176 }
3177
3178 /* Only real trickiness here is that the uncommitted
3179 * command structure is not counted in pi->num_cmds. */
3180 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003181 ctx->command = command = &pi->cmds[pi->num_cmds];
3182 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003183 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003184 return pi->num_cmds; /* used only for 0/nonzero check */
3185}
3186
3187static void done_pipe(struct parse_context *ctx, pipe_style type)
3188{
3189 int not_null;
3190
3191 debug_printf_parse("done_pipe entered, followup %d\n", type);
3192 /* Close previous command */
3193 not_null = done_command(ctx);
3194 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003195#if HAS_KEYWORDS
3196 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3197 ctx->ctx_inverted = 0;
3198 ctx->pipe->res_word = ctx->ctx_res_w;
3199#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003200
3201 /* Without this check, even just <enter> on command line generates
3202 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003203 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003204 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003205#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003206 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003207#endif
3208#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003209 || ctx->ctx_res_w == RES_DONE
3210 || ctx->ctx_res_w == RES_FOR
3211 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003212#endif
3213#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003214 || ctx->ctx_res_w == RES_ESAC
3215#endif
3216 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003217 struct pipe *new_p;
3218 debug_printf_parse("done_pipe: adding new pipe: "
3219 "not_null:%d ctx->ctx_res_w:%d\n",
3220 not_null, ctx->ctx_res_w);
3221 new_p = new_pipe();
3222 ctx->pipe->next = new_p;
3223 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003224 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003225 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003226 * This is used to control execution.
3227 * RES_FOR and RES_IN are NOT sticky (needed to support
3228 * cases where variable or value happens to match a keyword):
3229 */
3230#if ENABLE_HUSH_LOOPS
3231 if (ctx->ctx_res_w == RES_FOR
3232 || ctx->ctx_res_w == RES_IN)
3233 ctx->ctx_res_w = RES_NONE;
3234#endif
3235#if ENABLE_HUSH_CASE
3236 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003237 ctx->ctx_res_w = RES_CASE_BODY;
3238 if (ctx->ctx_res_w == RES_CASE)
3239 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003240#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003241 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003242 /* Create the memory for command, roughly:
3243 * ctx->pipe->cmds = new struct command;
3244 * ctx->command = &ctx->pipe->cmds[0];
3245 */
3246 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003247 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003248 }
3249 debug_printf_parse("done_pipe return\n");
3250}
3251
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003252static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003253{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003254 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003255 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003256 /* Create the memory for command, roughly:
3257 * ctx->pipe->cmds = new struct command;
3258 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003259 */
3260 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003261}
3262
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003263/* If a reserved word is found and processed, parse context is modified
3264 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003265 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003266#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003267struct reserved_combo {
3268 char literal[6];
3269 unsigned char res;
3270 unsigned char assignment_flag;
3271 int flag;
3272};
3273enum {
3274 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003275# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003276 FLAG_IF = (1 << RES_IF ),
3277 FLAG_THEN = (1 << RES_THEN ),
3278 FLAG_ELIF = (1 << RES_ELIF ),
3279 FLAG_ELSE = (1 << RES_ELSE ),
3280 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003281# endif
3282# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003283 FLAG_FOR = (1 << RES_FOR ),
3284 FLAG_WHILE = (1 << RES_WHILE),
3285 FLAG_UNTIL = (1 << RES_UNTIL),
3286 FLAG_DO = (1 << RES_DO ),
3287 FLAG_DONE = (1 << RES_DONE ),
3288 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003289# endif
3290# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003291 FLAG_MATCH = (1 << RES_MATCH),
3292 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003293# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003294 FLAG_START = (1 << RES_XXXX ),
3295};
3296
3297static const struct reserved_combo* match_reserved_word(o_string *word)
3298{
Eric Andersen25f27032001-04-26 23:22:31 +00003299 /* Mostly a list of accepted follow-up reserved words.
3300 * FLAG_END means we are done with the sequence, and are ready
3301 * to turn the compound list into a command.
3302 * FLAG_START means the word must start a new compound list.
3303 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003304 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003305# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003306 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3307 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3308 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3309 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3310 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3311 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003312# endif
3313# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003314 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3315 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3316 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3317 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3318 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3319 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003320# endif
3321# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003322 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3323 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003324# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003325 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003326 const struct reserved_combo *r;
3327
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003328 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003329 if (strcmp(word->data, r->literal) == 0)
3330 return r;
3331 }
3332 return NULL;
3333}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003334/* Return 0: not a keyword, 1: keyword
3335 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003336static int reserved_word(o_string *word, struct parse_context *ctx)
3337{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003338# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003339 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003340 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003341 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003342# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003343 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003344
Denys Vlasenko38292b62010-09-05 14:49:40 +02003345 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003346 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003347 r = match_reserved_word(word);
3348 if (!r)
3349 return 0;
3350
3351 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003352# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003353 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3354 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003355 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003356 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003357# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003358 if (r->flag == 0) { /* '!' */
3359 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003360 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003361 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003362 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003363 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003364 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003365 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003366 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003367 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003368
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003369 old = xmalloc(sizeof(*old));
3370 debug_printf_parse("push stack %p\n", old);
3371 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003372 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003373 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003374 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003375 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003376 ctx->ctx_res_w = RES_SNTX;
3377 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003378 } else {
3379 /* "{...} fi" is ok. "{...} if" is not
3380 * Example:
3381 * if { echo foo; } then { echo bar; } fi */
3382 if (ctx->command->group)
3383 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003384 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003385
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003386 ctx->ctx_res_w = r->res;
3387 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003388 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003389 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003390
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003391 if (ctx->old_flag & FLAG_END) {
3392 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003393
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003394 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003395 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003396 old = ctx->stack;
3397 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003398 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003399# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003400 /* At this point, the compound command's string is in
3401 * ctx->as_string... except for the leading keyword!
3402 * Consider this example: "echo a | if true; then echo a; fi"
3403 * ctx->as_string will contain "true; then echo a; fi",
3404 * with "if " remaining in old->as_string!
3405 */
3406 {
3407 char *str;
3408 int len = old->as_string.length;
3409 /* Concatenate halves */
3410 o_addstr(&old->as_string, ctx->as_string.data);
3411 o_free_unsafe(&ctx->as_string);
3412 /* Find where leading keyword starts in first half */
3413 str = old->as_string.data + len;
3414 if (str > old->as_string.data)
3415 str--; /* skip whitespace after keyword */
3416 while (str > old->as_string.data && isalpha(str[-1]))
3417 str--;
3418 /* Ugh, we're done with this horrid hack */
3419 old->command->group_as_string = xstrdup(str);
3420 debug_printf_parse("pop, remembering as:'%s'\n",
3421 old->command->group_as_string);
3422 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003423# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003424 *ctx = *old; /* physical copy */
3425 free(old);
3426 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003427 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003428}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003429#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003430
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003431/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003432 * Normal return is 0. Syntax errors return 1.
3433 * Note: on return, word is reset, but not o_free'd!
3434 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003435static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003436{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003437 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003438
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003439 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003440 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003441 debug_printf_parse("done_word return 0: true null, ignored\n");
3442 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003443 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003444
Eric Andersen25f27032001-04-26 23:22:31 +00003445 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003446 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3447 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003448 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3449 * "2.7 Redirection
3450 * ...the word that follows the redirection operator
3451 * shall be subjected to tilde expansion, parameter expansion,
3452 * command substitution, arithmetic expansion, and quote
3453 * removal. Pathname expansion shall not be performed
3454 * on the word by a non-interactive shell; an interactive
3455 * shell may perform it, but shall do so only when
3456 * the expansion would result in one word."
3457 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003458 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003459 /* Cater for >\file case:
3460 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3461 * Same with heredocs:
3462 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3463 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003464 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3465 unbackslash(ctx->pending_redirect->rd_filename);
3466 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003467 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003468 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3469 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003470 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003471 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003472 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003473 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003474#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003475# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003476 if (ctx->ctx_dsemicolon
3477 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3478 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003479 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003480 /* ctx->ctx_res_w = RES_MATCH; */
3481 ctx->ctx_dsemicolon = 0;
3482 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003483# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003484 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003485# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003486 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3487 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003488# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003489# if ENABLE_HUSH_CASE
3490 && ctx->ctx_res_w != RES_CASE
3491# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003492 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003493 int reserved = reserved_word(word, ctx);
3494 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3495 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003496 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003497 debug_printf_parse("done_word return %d\n",
3498 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003499 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003500 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003501# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003502 if (strcmp(word->data, "[[") == 0) {
3503 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3504 }
3505 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003506# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003507 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003508#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003509 if (command->group) {
3510 /* "{ echo foo; } echo bar" - bad */
3511 syntax_error_at(word->data);
3512 debug_printf_parse("done_word return 1: syntax error, "
3513 "groups and arglists don't mix\n");
3514 return 1;
3515 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003516
3517 /* If this word wasn't an assignment, next ones definitely
3518 * can't be assignments. Even if they look like ones. */
3519 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3520 && word->o_assignment != WORD_IS_KEYWORD
3521 ) {
3522 word->o_assignment = NOT_ASSIGNMENT;
3523 } else {
3524 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3525 command->assignment_cnt++;
3526 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3527 }
3528 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3529 word->o_assignment = MAYBE_ASSIGNMENT;
3530 }
3531 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3532
Denys Vlasenko38292b62010-09-05 14:49:40 +02003533 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003534 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3535 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003536 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003537 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003538 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003539 char *p = word->data;
3540 while (p[0] == SPECIAL_VAR_SYMBOL
3541 && (p[1] & 0x7f) == '@'
3542 && p[2] == SPECIAL_VAR_SYMBOL
3543 ) {
3544 p += 3;
3545 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003546 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003547 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003548 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003549 }
Eric Andersen25f27032001-04-26 23:22:31 +00003550
Denis Vlasenko06810332007-05-21 23:30:54 +00003551#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003552 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003553 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003554 || !is_well_formed_var_name(command->argv[0], '\0')
3555 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003556 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003557 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003558 return 1;
3559 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003560 /* Force FOR to have just one word (variable name) */
3561 /* NB: basically, this makes hush see "for v in ..."
3562 * syntax as if it is "for v; in ...". FOR and IN become
3563 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003564 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003565 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003566#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003567#if ENABLE_HUSH_CASE
3568 /* Force CASE to have just one word */
3569 if (ctx->ctx_res_w == RES_CASE) {
3570 done_pipe(ctx, PIPE_SEQ);
3571 }
3572#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003573
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003574 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003575
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003576 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003577 return 0;
3578}
3579
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003580
3581/* Peek ahead in the input to find out if we have a "&n" construct,
3582 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003583 * Return:
3584 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3585 * REDIRFD_SYNTAX_ERR if syntax error,
3586 * REDIRFD_TO_FILE if no & was seen,
3587 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003588 */
3589#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003590#define parse_redir_right_fd(as_string, input) \
3591 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003592#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003593static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003594{
3595 int ch, d, ok;
3596
3597 ch = i_peek(input);
3598 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003599 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003600
3601 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003602 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003603 ch = i_peek(input);
3604 if (ch == '-') {
3605 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003606 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003607 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003608 }
3609 d = 0;
3610 ok = 0;
3611 while (ch != EOF && isdigit(ch)) {
3612 d = d*10 + (ch-'0');
3613 ok = 1;
3614 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003615 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003616 ch = i_peek(input);
3617 }
3618 if (ok) return d;
3619
3620//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3621
3622 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003623 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003624}
3625
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003626/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003627 */
3628static int parse_redirect(struct parse_context *ctx,
3629 int fd,
3630 redir_type style,
3631 struct in_str *input)
3632{
3633 struct command *command = ctx->command;
3634 struct redir_struct *redir;
3635 struct redir_struct **redirp;
3636 int dup_num;
3637
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003638 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003639 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003640 /* Check for a '>&1' type redirect */
3641 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3642 if (dup_num == REDIRFD_SYNTAX_ERR)
3643 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003644 } else {
3645 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003646 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003647 if (dup_num) { /* <<-... */
3648 ch = i_getch(input);
3649 nommu_addchr(&ctx->as_string, ch);
3650 ch = i_peek(input);
3651 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003652 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003653
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003654 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003655 int ch = i_peek(input);
3656 if (ch == '|') {
3657 /* >|FILE redirect ("clobbering" >).
3658 * Since we do not support "set -o noclobber" yet,
3659 * >| and > are the same for now. Just eat |.
3660 */
3661 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003662 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003663 }
3664 }
3665
3666 /* Create a new redir_struct and append it to the linked list */
3667 redirp = &command->redirects;
3668 while ((redir = *redirp) != NULL) {
3669 redirp = &(redir->next);
3670 }
3671 *redirp = redir = xzalloc(sizeof(*redir));
3672 /* redir->next = NULL; */
3673 /* redir->rd_filename = NULL; */
3674 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003675 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003676
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003677 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3678 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003679
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003680 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003681 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003682 /* Erik had a check here that the file descriptor in question
3683 * is legit; I postpone that to "run time"
3684 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003685 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3686 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003687 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003688#if 0 /* Instead we emit error message at run time */
3689 if (ctx->pending_redirect) {
3690 /* For example, "cmd > <file" */
3691 die_if_script("syntax error: %s", "invalid redirect");
3692 }
3693#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003694 /* Set ctx->pending_redirect, so we know what to do at the
3695 * end of the next parsed word. */
3696 ctx->pending_redirect = redir;
3697 }
3698 return 0;
3699}
3700
Eric Andersen25f27032001-04-26 23:22:31 +00003701/* If a redirect is immediately preceded by a number, that number is
3702 * supposed to tell which file descriptor to redirect. This routine
3703 * looks for such preceding numbers. In an ideal world this routine
3704 * needs to handle all the following classes of redirects...
3705 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3706 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3707 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3708 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003709 *
3710 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3711 * "2.7 Redirection
3712 * ... If n is quoted, the number shall not be recognized as part of
3713 * the redirection expression. For example:
3714 * echo \2>a
3715 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003716 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003717 *
3718 * A -1 return means no valid number was found,
3719 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003720 */
3721static int redirect_opt_num(o_string *o)
3722{
3723 int num;
3724
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003725 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003726 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003727 num = bb_strtou(o->data, NULL, 10);
3728 if (errno || num < 0)
3729 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003730 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003731 return num;
3732}
3733
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003734#if BB_MMU
3735#define fetch_till_str(as_string, input, word, skip_tabs) \
3736 fetch_till_str(input, word, skip_tabs)
3737#endif
3738static char *fetch_till_str(o_string *as_string,
3739 struct in_str *input,
3740 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003741 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003742{
3743 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003744 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003745 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003746 int ch;
3747
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003748 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003749
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003750 while (1) {
3751 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003752 if (ch != EOF)
3753 nommu_addchr(as_string, ch);
3754 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003755 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3756 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003757 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3758 heredoc.data[past_EOL] = '\0';
3759 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3760 return heredoc.data;
3761 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003762 while (ch == '\n') {
3763 o_addchr(&heredoc, ch);
3764 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003765 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003766 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003767 do {
3768 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003769 if (ch != EOF)
3770 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003771 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003772 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003773 }
3774 if (ch == EOF) {
3775 o_free_unsafe(&heredoc);
3776 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003777 }
3778 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003779 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003780 if (prev == '\\' && ch == '\\')
3781 /* Correctly handle foo\\<eol> (not a line cont.) */
3782 prev = 0; /* not \ */
3783 else
3784 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003785 }
3786}
3787
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003788/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3789 * and load them all. There should be exactly heredoc_cnt of them.
3790 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003791static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3792{
3793 struct pipe *pi = ctx->list_head;
3794
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003795 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003796 int i;
3797 struct command *cmd = pi->cmds;
3798
3799 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3800 pi->num_cmds,
3801 cmd->argv ? cmd->argv[0] : "NONE");
3802 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003803 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003804
3805 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3806 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003807 while (redir) {
3808 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003809 char *p;
3810
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003811 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003812 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003813 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003814 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003815 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003816 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003817 return 1;
3818 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003819 free(redir->rd_filename);
3820 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003821 heredoc_cnt--;
3822 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003823 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003824 }
3825 cmd++;
3826 }
3827 pi = pi->next;
3828 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003829#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003830 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003831 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003832 bb_error_msg_and_die("heredoc BUG 2");
3833#endif
3834 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003835}
3836
3837
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003838static int run_list(struct pipe *pi);
3839#if BB_MMU
3840#define parse_stream(pstring, input, end_trigger) \
3841 parse_stream(input, end_trigger)
3842#endif
3843static struct pipe *parse_stream(char **pstring,
3844 struct in_str *input,
3845 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003846
Eric Andersen25f27032001-04-26 23:22:31 +00003847
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003848#if !ENABLE_HUSH_FUNCTIONS
3849#define parse_group(dest, ctx, input, ch) \
3850 parse_group(ctx, input, ch)
3851#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003852static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003853 struct in_str *input, int ch)
3854{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003855 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003856 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003857 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003858 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003859 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003860 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003861
3862 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003863#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003864 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003865 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003866 if (done_word(dest, ctx))
3867 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003868 if (!command->argv)
3869 goto skip; /* (... */
3870 if (command->argv[1]) { /* word word ... (... */
3871 syntax_error_unexpected_ch('(');
3872 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003873 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003874 /* it is "word(..." or "word (..." */
3875 do
3876 ch = i_getch(input);
3877 while (ch == ' ' || ch == '\t');
3878 if (ch != ')') {
3879 syntax_error_unexpected_ch(ch);
3880 return 1;
3881 }
3882 nommu_addchr(&ctx->as_string, ch);
3883 do
3884 ch = i_getch(input);
3885 while (ch == ' ' || ch == '\t' || ch == '\n');
3886 if (ch != '{') {
3887 syntax_error_unexpected_ch(ch);
3888 return 1;
3889 }
3890 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003891 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003892 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003893 }
3894#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003895
3896#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003897 if (command->argv /* word [word]{... */
3898 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003899 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003900 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003901 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003902 debug_printf_parse("parse_group return 1: "
3903 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003904 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003905 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003906#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003907
3908#if ENABLE_HUSH_FUNCTIONS
3909 skip:
3910#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003911 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003912 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003913 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003914 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003915 } else {
3916 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01003917 ch = i_peek(input);
3918 if (ch != ' ' && ch != '\t' && ch != '\n'
3919 && ch != '(' /* but "{(..." is allowed (without whitespace) */
3920 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003921 syntax_error_unexpected_ch(ch);
3922 return 1;
3923 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01003924 if (ch != '(') {
3925 ch = i_getch(input);
3926 nommu_addchr(&ctx->as_string, ch);
3927 }
Eric Andersen25f27032001-04-26 23:22:31 +00003928 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003929
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003930 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003931#if BB_MMU
3932# define as_string NULL
3933#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003934 char *as_string = NULL;
3935#endif
3936 pipe_list = parse_stream(&as_string, input, endch);
3937#if !BB_MMU
3938 if (as_string)
3939 o_addstr(&ctx->as_string, as_string);
3940#endif
3941 /* empty ()/{} or parse error? */
3942 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003943 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003944 if (!BB_MMU)
3945 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003946 debug_printf_parse("parse_group return 1: "
3947 "parse_stream returned %p\n", pipe_list);
3948 return 1;
3949 }
3950 command->group = pipe_list;
3951#if !BB_MMU
3952 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3953 command->group_as_string = as_string;
3954 debug_printf_parse("end of group, remembering as:'%s'\n",
3955 command->group_as_string);
3956#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003957#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003958 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003959 debug_printf_parse("parse_group return 0\n");
3960 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003961 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003962}
3963
Denys Vlasenko46e64982016-09-29 19:50:55 +02003964static int i_getch_and_eat_bkslash_nl(struct in_str *input)
3965{
3966 for (;;) {
3967 int ch, ch2;
3968
3969 ch = i_getch(input);
3970 if (ch != '\\')
3971 return ch;
3972 ch2 = i_peek(input);
3973 if (ch2 != '\n')
3974 return ch;
3975 /* backslash+newline, skip it */
3976 i_getch(input);
3977 }
3978}
3979
Denys Vlasenko657086a2016-09-29 18:07:42 +02003980static int i_peek_and_eat_bkslash_nl(struct in_str *input)
3981{
3982 for (;;) {
3983 int ch, ch2;
3984
3985 ch = i_peek(input);
3986 if (ch != '\\')
3987 return ch;
3988 ch2 = i_peek2(input);
3989 if (ch2 != '\n')
3990 return ch;
3991 /* backslash+newline, skip it */
3992 i_getch(input);
3993 i_getch(input);
3994 }
3995}
3996
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003997#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003998/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003999static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004000/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004001static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004002{
4003 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004004 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004005 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004006 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004007 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004008 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004009 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004010 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004011 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004012 }
4013}
4014/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004015static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004016{
4017 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004018 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004019 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004020 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004021 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004022 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004023 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004024 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004025 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004026 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004027 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004028 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004029 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004030 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004031 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4032 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004033 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004034 continue;
4035 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004036 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004037 }
4038}
4039/* Process `cmd` - copy contents until "`" is seen. Complicated by
4040 * \` quoting.
4041 * "Within the backquoted style of command substitution, backslash
4042 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4043 * The search for the matching backquote shall be satisfied by the first
4044 * backquote found without a preceding backslash; during this search,
4045 * if a non-escaped backquote is encountered within a shell comment,
4046 * a here-document, an embedded command substitution of the $(command)
4047 * form, or a quoted string, undefined results occur. A single-quoted
4048 * or double-quoted string that begins, but does not end, within the
4049 * "`...`" sequence produces undefined results."
4050 * Example Output
4051 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4052 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004053static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004054{
4055 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004056 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004057 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004058 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004059 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004060 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4061 ch = i_getch(input);
4062 if (ch != '`'
4063 && ch != '$'
4064 && ch != '\\'
4065 && (!in_dquote || ch != '"')
4066 ) {
4067 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004068 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004069 }
4070 if (ch == EOF) {
4071 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004072 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004073 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004074 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004075 }
4076}
4077/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4078 * quoting and nested ()s.
4079 * "With the $(command) style of command substitution, all characters
4080 * following the open parenthesis to the matching closing parenthesis
4081 * constitute the command. Any valid shell script can be used for command,
4082 * except a script consisting solely of redirections which produces
4083 * unspecified results."
4084 * Example Output
4085 * echo $(echo '(TEST)' BEST) (TEST) BEST
4086 * echo $(echo 'TEST)' BEST) TEST) BEST
4087 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004088 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004089 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004090 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004091 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4092 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004093 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004094#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004095static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004096{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004097 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004098 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004099# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004100 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004101# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004102 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4103
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004104 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004105 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004106 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004107 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004108 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004109 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004110 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004111 if (!dbl)
4112 break;
4113 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004114 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004115 i_getch(input); /* eat second ')' */
4116 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004117 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004118 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004119 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004120 if (ch == '(' || ch == '{') {
4121 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004122 if (!add_till_closing_bracket(dest, input, ch))
4123 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004124 o_addchr(dest, ch);
4125 continue;
4126 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004127 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004128 if (!add_till_single_quote(dest, input))
4129 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004130 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004131 continue;
4132 }
4133 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004134 if (!add_till_double_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 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004139 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004140 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4141 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004142 o_addchr(dest, ch);
4143 continue;
4144 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004145 if (ch == '\\') {
4146 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004147 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004148 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004149 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004150 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004151 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004152#if 0
4153 if (ch == '\n') {
4154 /* "backslash+newline", ignore both */
4155 o_delchr(dest); /* undo insertion of '\' */
4156 continue;
4157 }
4158#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004159 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004160 continue;
4161 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004162 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004163 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004164}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004165#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004166
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004167/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004168#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004169#define parse_dollar(as_string, dest, input, quote_mask) \
4170 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004171#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004172#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004173static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004174 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004175 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004176{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004177 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004178
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004179 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004180 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004181 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004182 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004183 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004184 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004185 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004186 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004187 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004188 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004189 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004190 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004191 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004192 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004193 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004194 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004195 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004196 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004197 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004198 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004199 make_one_char_var:
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);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004202 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004203 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004204 o_addchr(dest, ch | quote_mask);
4205 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004206 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004207 case '$': /* pid */
4208 case '!': /* last bg pid */
4209 case '?': /* last exit code */
4210 case '#': /* number of args */
4211 case '*': /* args */
4212 case '@': /* args */
4213 goto make_one_char_var;
4214 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004215 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4216
Denys Vlasenko74369502010-05-21 19:52:01 +02004217 ch = i_getch(input); /* eat '{' */
4218 nommu_addchr(as_string, ch);
4219
Denys Vlasenko46e64982016-09-29 19:50:55 +02004220 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004221 /* It should be ${?}, or ${#var},
4222 * or even ${?+subst} - operator acting on a special variable,
4223 * or the beginning of variable name.
4224 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004225 if (ch == EOF
4226 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4227 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004228 bad_dollar_syntax:
4229 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004230 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4231 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004232 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004233 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004234 ch |= quote_mask;
4235
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004236 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004237 * However, this regresses some of our testsuite cases
4238 * which check invalid constructs like ${%}.
4239 * Oh well... let's check that the var name part is fine... */
4240
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004241 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004242 unsigned pos;
4243
Denys Vlasenko74369502010-05-21 19:52:01 +02004244 o_addchr(dest, ch);
4245 debug_printf_parse(": '%c'\n", ch);
4246
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004247 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004248 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004249 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004250 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004251
Denys Vlasenko74369502010-05-21 19:52:01 +02004252 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004253 unsigned end_ch;
4254 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004255 /* handle parameter expansions
4256 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4257 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004258 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02004259 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004260
4261 /* Eat everything until closing '}' (or ':') */
4262 end_ch = '}';
4263 if (ENABLE_HUSH_BASH_COMPAT
4264 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004265 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004266 ) {
4267 /* It's ${var:N[:M]} thing */
4268 end_ch = '}' * 0x100 + ':';
4269 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004270 if (ENABLE_HUSH_BASH_COMPAT
4271 && ch == '/'
4272 ) {
4273 /* It's ${var/[/]pattern[/repl]} thing */
4274 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4275 i_getch(input);
4276 nommu_addchr(as_string, '/');
4277 ch = '\\';
4278 }
4279 end_ch = '}' * 0x100 + '/';
4280 }
4281 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004282 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004283 if (!BB_MMU)
4284 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004285#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004286 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004287 if (last_ch == 0) /* error? */
4288 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004289#else
4290#error Simple code to only allow ${var} is not implemented
4291#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004292 if (as_string) {
4293 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004294 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004295 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004296
4297 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4298 /* close the first block: */
4299 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004300 /* while parsing N from ${var:N[:M]}
4301 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004302 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004303 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004304 end_ch = '}';
4305 goto again;
4306 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004307 /* got '}' */
4308 if (end_ch == '}' * 0x100 + ':') {
4309 /* it's ${var:N} - emulate :999999999 */
4310 o_addstr(dest, "999999999");
4311 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004312 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004313 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004314 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004315 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004316 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4317 break;
4318 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004319#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004320 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004321 unsigned pos;
4322
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004323 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004324 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004325# if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko657086a2016-09-29 18:07:42 +02004326 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004327 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004328 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004329 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4330 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004331 if (!BB_MMU)
4332 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004333 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4334 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004335 if (as_string) {
4336 o_addstr(as_string, dest->data + pos);
4337 o_addchr(as_string, ')');
4338 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004339 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004340 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004341 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004342 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004343# endif
4344# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004345 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4346 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004347 if (!BB_MMU)
4348 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004349 if (!add_till_closing_bracket(dest, input, ')'))
4350 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004351 if (as_string) {
4352 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004353 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004354 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004355 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004356# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004357 break;
4358 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004359#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004360 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004361 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004362 nommu_addchr(as_string, ch);
Denys Vlasenko657086a2016-09-29 18:07:42 +02004363 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004364 if (isalnum(ch)) { /* it's $_name or $_123 */
4365 ch = '_';
4366 goto make_var;
4367 }
4368 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004369 /* TODO: $_ and $-: */
4370 /* $_ Shell or shell script name; or last argument of last command
4371 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4372 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004373 /* $- Option flags set by set builtin or shell options (-i etc) */
4374 default:
4375 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004376 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004377 debug_printf_parse("parse_dollar return 1 (ok)\n");
4378 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004379#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004380}
4381
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004382#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004383# if ENABLE_HUSH_BASH_COMPAT
4384#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4385 encode_string(dest, input, dquote_end, process_bkslash)
4386# else
4387/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4388#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4389 encode_string(dest, input, dquote_end)
4390# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004391#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004392
4393#else /* !MMU */
4394
4395# if ENABLE_HUSH_BASH_COMPAT
4396/* all parameters are needed, no macro tricks */
4397# else
4398#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4399 encode_string(as_string, dest, input, dquote_end)
4400# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004401#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004402static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004403 o_string *dest,
4404 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004405 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004406 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004407{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004408#if !ENABLE_HUSH_BASH_COMPAT
4409 const int process_bkslash = 1;
4410#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004411 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004412 int next;
4413
4414 again:
4415 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004416 if (ch != EOF)
4417 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004418 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004419 debug_printf_parse("encode_string return 1 (ok)\n");
4420 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004421 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004422 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004423 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004424 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004425 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004426 }
4427 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004428 if (ch != '\n') {
4429 next = i_peek(input);
4430 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004431 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004432 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004433 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004434 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004435 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004436 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004437 }
4438 /* bash:
4439 * "The backslash retains its special meaning [in "..."]
4440 * only when followed by one of the following characters:
4441 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004442 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004443 * NB: in (unquoted) heredoc, above does not apply to ",
4444 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004445 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004446 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004447 ch = i_getch(input); /* eat next */
4448 if (ch == '\n')
4449 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004450 } /* else: ch remains == '\\', and we double it below: */
4451 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004452 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004453 goto again;
4454 }
4455 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004456 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4457 debug_printf_parse("encode_string return 0: "
4458 "parse_dollar returned 0 (error)\n");
4459 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004460 }
4461 goto again;
4462 }
4463#if ENABLE_HUSH_TICK
4464 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004465 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004466 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4467 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004468 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4469 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004470 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4471 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004472 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004473 }
4474#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004475 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004476 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004477#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004478}
4479
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004480/*
4481 * Scan input until EOF or end_trigger char.
4482 * Return a list of pipes to execute, or NULL on EOF
4483 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004484 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004485 * reset parsing machinery and start parsing anew,
4486 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004487 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004488static struct pipe *parse_stream(char **pstring,
4489 struct in_str *input,
4490 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004491{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004492 struct parse_context ctx;
4493 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004494 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004495
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004496 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004497 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004498 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004499 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004500 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004501 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004502
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004503 /* If very first arg is "" or '', dest.data may end up NULL.
4504 * Preventing this: */
4505 o_addchr(&dest, '\0');
4506 dest.length = 0;
4507
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004508 /* We used to separate words on $IFS here. This was wrong.
4509 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004510 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004511 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004512
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004513 if (MAYBE_ASSIGNMENT != 0)
4514 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004515 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004516 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004517 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004518 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004519 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004520 int ch;
4521 int next;
4522 int redir_fd;
4523 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004524
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004525 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004526 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004527 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004528 if (ch == EOF) {
4529 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004530
4531 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004532 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004533 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004534 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004535 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004536 syntax_error_unterm_ch('(');
4537 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004538 }
Denys Vlasenko42246472016-11-07 16:22:35 +01004539 if (end_trigger == '}') {
4540 syntax_error_unterm_ch('{');
4541 goto parse_error;
4542 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004543
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004544 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004545 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004546 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004547 o_free(&dest);
4548 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004549 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004550 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004551 /* (this makes bare "&" cmd a no-op.
4552 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004553 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004554 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004555 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004556 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004557 pi = NULL;
4558 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004559#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004560 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004561 if (pstring)
4562 *pstring = ctx.as_string.data;
4563 else
4564 o_free_unsafe(&ctx.as_string);
4565#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004566 debug_leave();
4567 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004568 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004569 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004570 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004571
4572 next = '\0';
4573 if (ch != '\n')
4574 next = i_peek(input);
4575
4576 is_special = "{}<>;&|()#'" /* special outside of "str" */
4577 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4578 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004579 if (ctx.command->argv /* word [word]{... - non-special */
4580 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004581 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004582 || (next != ';' /* }; - special */
4583 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004584 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004585 && next != '&' /* }& and }&& ... - special */
4586 && next != '|' /* }|| ... - special */
4587 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004588 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004589 ) {
4590 /* They are not special, skip "{}" */
4591 is_special += 2;
4592 }
4593 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004594 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004595
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004596 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004597 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004598 o_addQchr(&dest, ch);
4599 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4600 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004601 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004602 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004603 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004604 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004605 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004606 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004607 continue;
4608 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004609
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004610 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004611 if (done_word(&dest, &ctx)) {
4612 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004613 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004614 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004615 /* Is this a case when newline is simply ignored?
4616 * Some examples:
4617 * "cmd | <newline> cmd ..."
4618 * "case ... in <newline> word) ..."
4619 */
4620 if (IS_NULL_CMD(ctx.command)
4621 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004622 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004623 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004624 * Without check #1, interactive shell
4625 * ignores even bare <newline>,
4626 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004627 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004628 * ps2> _ <=== wrong, should be ps1
4629 * Without check #2, "cmd & <newline>"
4630 * is similarly mistreated.
4631 * (BTW, this makes "cmd & cmd"
4632 * and "cmd && cmd" non-orthogonal.
4633 * Really, ask yourself, why
4634 * "cmd && <newline>" doesn't start
4635 * cmd but waits for more input?
4636 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004637 */
4638 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004639 if (pi->num_cmds != 0 /* check #1 */
4640 && pi->followup != PIPE_BG /* check #2 */
4641 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004642 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004643 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004644 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004645 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004646 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004647 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4648 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004649 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004650 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004651 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004652 heredoc_cnt = 0;
4653 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004654 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004655 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004656 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004657 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004658 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004659 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004660 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004661
4662 /* "cmd}" or "cmd }..." without semicolon or &:
4663 * } is an ordinary char in this case, even inside { cmd; }
4664 * Pathological example: { ""}; } should exec "}" cmd
4665 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004666 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004667 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004668 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004669 ) {
4670 goto ordinary_char;
4671 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004672 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4673 /* Generally, there should be semicolon: "cmd; }"
4674 * However, bash allows to omit it if "cmd" is
4675 * a group. Examples:
4676 * { { echo 1; } }
4677 * {(echo 1)}
4678 * { echo 0 >&2 | { echo 1; } }
4679 * { while false; do :; done }
4680 * { case a in b) ;; esac }
4681 */
4682 if (ctx.command->group)
4683 goto term_group;
4684 goto ordinary_char;
4685 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004686 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004687 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004688 goto skip_end_trigger;
4689 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004690 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004691 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004692 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004693 && (ch != ';' || heredoc_cnt == 0)
4694#if ENABLE_HUSH_CASE
4695 && (ch != ')'
4696 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004697 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004698 )
4699#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004700 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004701 if (heredoc_cnt) {
4702 /* This is technically valid:
4703 * { cat <<HERE; }; echo Ok
4704 * heredoc
4705 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004706 * HERE
4707 * but we don't support this.
4708 * We require heredoc to be in enclosing {}/(),
4709 * if any.
4710 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004711 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004712 goto parse_error;
4713 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004714 if (done_word(&dest, &ctx)) {
4715 goto parse_error;
4716 }
4717 done_pipe(&ctx, PIPE_SEQ);
4718 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004719 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004720 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004721 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004722 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004723 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004724 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004725#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004726 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004727 if (pstring)
4728 *pstring = ctx.as_string.data;
4729 else
4730 o_free_unsafe(&ctx.as_string);
4731#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004732 debug_leave();
4733 debug_printf_parse("parse_stream return %p: "
4734 "end_trigger char found\n",
4735 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004736 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004737 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004738 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004739 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004740 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004741 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004742
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004743 /* Catch <, > before deciding whether this word is
4744 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4745 switch (ch) {
4746 case '>':
4747 redir_fd = redirect_opt_num(&dest);
4748 if (done_word(&dest, &ctx)) {
4749 goto parse_error;
4750 }
4751 redir_style = REDIRECT_OVERWRITE;
4752 if (next == '>') {
4753 redir_style = REDIRECT_APPEND;
4754 ch = i_getch(input);
4755 nommu_addchr(&ctx.as_string, ch);
4756 }
4757#if 0
4758 else if (next == '(') {
4759 syntax_error(">(process) not supported");
4760 goto parse_error;
4761 }
4762#endif
4763 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4764 goto parse_error;
4765 continue; /* back to top of while (1) */
4766 case '<':
4767 redir_fd = redirect_opt_num(&dest);
4768 if (done_word(&dest, &ctx)) {
4769 goto parse_error;
4770 }
4771 redir_style = REDIRECT_INPUT;
4772 if (next == '<') {
4773 redir_style = REDIRECT_HEREDOC;
4774 heredoc_cnt++;
4775 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4776 ch = i_getch(input);
4777 nommu_addchr(&ctx.as_string, ch);
4778 } else if (next == '>') {
4779 redir_style = REDIRECT_IO;
4780 ch = i_getch(input);
4781 nommu_addchr(&ctx.as_string, ch);
4782 }
4783#if 0
4784 else if (next == '(') {
4785 syntax_error("<(process) not supported");
4786 goto parse_error;
4787 }
4788#endif
4789 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4790 goto parse_error;
4791 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004792 case '#':
4793 if (dest.length == 0 && !dest.has_quoted_part) {
4794 /* skip "#comment" */
4795 while (1) {
4796 ch = i_peek(input);
4797 if (ch == EOF || ch == '\n')
4798 break;
4799 i_getch(input);
4800 /* note: we do not add it to &ctx.as_string */
4801 }
4802 nommu_addchr(&ctx.as_string, '\n');
4803 continue; /* back to top of while (1) */
4804 }
4805 break;
4806 case '\\':
4807 if (next == '\n') {
4808 /* It's "\<newline>" */
4809#if !BB_MMU
4810 /* Remove trailing '\' from ctx.as_string */
4811 ctx.as_string.data[--ctx.as_string.length] = '\0';
4812#endif
4813 ch = i_getch(input); /* eat it */
4814 continue; /* back to top of while (1) */
4815 }
4816 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004817 }
4818
4819 if (dest.o_assignment == MAYBE_ASSIGNMENT
4820 /* check that we are not in word in "a=1 2>word b=1": */
4821 && !ctx.pending_redirect
4822 ) {
4823 /* ch is a special char and thus this word
4824 * cannot be an assignment */
4825 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004826 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004827 }
4828
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004829 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4830
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004831 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004832 case '#': /* non-comment #: "echo a#b" etc */
4833 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004834 break;
4835 case '\\':
4836 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004837 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004838 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004839 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004840 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004841 /* note: ch != '\n' (that case does not reach this place) */
4842 o_addchr(&dest, '\\');
4843 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4844 o_addchr(&dest, ch);
4845 nommu_addchr(&ctx.as_string, ch);
4846 /* Example: echo Hello \2>file
4847 * we need to know that word 2 is quoted */
4848 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004849 break;
4850 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004851 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004852 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004853 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004854 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004855 }
Eric Andersen25f27032001-04-26 23:22:31 +00004856 break;
4857 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004858 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004859 if (next == '\'' && !ctx.pending_redirect) {
4860 insert_empty_quoted_str_marker:
4861 nommu_addchr(&ctx.as_string, next);
4862 i_getch(input); /* eat second ' */
4863 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4864 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4865 } else {
4866 while (1) {
4867 ch = i_getch(input);
4868 if (ch == EOF) {
4869 syntax_error_unterm_ch('\'');
4870 goto parse_error;
4871 }
4872 nommu_addchr(&ctx.as_string, ch);
4873 if (ch == '\'')
4874 break;
4875 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004876 }
Eric Andersen25f27032001-04-26 23:22:31 +00004877 }
Eric Andersen25f27032001-04-26 23:22:31 +00004878 break;
4879 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004880 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004881 if (next == '"' && !ctx.pending_redirect)
4882 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004883 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004884 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004885 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004886 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004887 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004888 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004889#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004890 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004891 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004892
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004893 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4894 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004895 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004896 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4897 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004898# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004899 o_addstr(&ctx.as_string, dest.data + pos);
4900 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004901# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004902 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4903 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004904 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004905 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004906#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004907 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004908#if ENABLE_HUSH_CASE
4909 case_semi:
4910#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004911 if (done_word(&dest, &ctx)) {
4912 goto parse_error;
4913 }
4914 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004915#if ENABLE_HUSH_CASE
4916 /* Eat multiple semicolons, detect
4917 * whether it means something special */
4918 while (1) {
4919 ch = i_peek(input);
4920 if (ch != ';')
4921 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004922 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004923 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004924 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004925 ctx.ctx_dsemicolon = 1;
4926 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004927 break;
4928 }
4929 }
4930#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004931 new_cmd:
4932 /* We just finished a cmd. New one may start
4933 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004934 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004935 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004936 break;
4937 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004938 if (done_word(&dest, &ctx)) {
4939 goto parse_error;
4940 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004941 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004942 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004943 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004944 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004945 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004946 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004947 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004948 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004949 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004950 if (done_word(&dest, &ctx)) {
4951 goto parse_error;
4952 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004953#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004954 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004955 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004956#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004957 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004958 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004959 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004960 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004961 } else {
4962 /* we could pick up a file descriptor choice here
4963 * with redirect_opt_num(), but bash doesn't do it.
4964 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004965 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004966 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004967 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004968 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004969#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004970 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004971 if (ctx.ctx_res_w == RES_MATCH
4972 && ctx.command->argv == NULL /* not (word|(... */
4973 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004974 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004975 ) {
4976 continue;
4977 }
4978#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004979 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004980 if (parse_group(&dest, &ctx, input, ch) != 0) {
4981 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004982 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004983 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004984 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004985#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004986 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004987 goto case_semi;
4988#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004989 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004990 /* proper use of this character is caught by end_trigger:
4991 * if we see {, we call parse_group(..., end_trigger='}')
4992 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004993 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004994 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004995 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004996 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004997 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004998 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004999 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005000
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005001 parse_error:
5002 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005003 struct parse_context *pctx;
5004 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005005
5006 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005007 * Sample for finding leaks on syntax error recovery path.
5008 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005009 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005010 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005011 * while if (true | { true;}); then echo ok; fi; do break; done
5012 * 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 +00005013 */
5014 pctx = &ctx;
5015 do {
5016 /* Update pipe/command counts,
5017 * otherwise freeing may miss some */
5018 done_pipe(pctx, PIPE_SEQ);
5019 debug_printf_clean("freeing list %p from ctx %p\n",
5020 pctx->list_head, pctx);
5021 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005022 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005023 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005024#if !BB_MMU
5025 o_free_unsafe(&pctx->as_string);
5026#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005027 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005028 if (pctx != &ctx) {
5029 free(pctx);
5030 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005031 IF_HAS_KEYWORDS(pctx = p2;)
5032 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005033
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005034 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005035 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005036#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005037 if (pstring)
5038 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005039#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005040 debug_leave();
5041 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005042 }
Eric Andersen25f27032001-04-26 23:22:31 +00005043}
5044
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005045
5046/*** Execution routines ***/
5047
5048/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005049#if !ENABLE_HUSH_BASH_COMPAT
5050/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5051#define expand_string_to_string(str, do_unbackslash) \
5052 expand_string_to_string(str)
5053#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005054static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005055#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005056static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005057#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005058
5059/* expand_strvec_to_strvec() takes a list of strings, expands
5060 * all variable references within and returns a pointer to
5061 * a list of expanded strings, possibly with larger number
5062 * of strings. (Think VAR="a b"; echo $VAR).
5063 * This new list is allocated as a single malloc block.
5064 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005065 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005066 * Caller can deallocate entire list by single free(list). */
5067
Denys Vlasenko238081f2010-10-03 14:26:26 +02005068/* A horde of its helpers come first: */
5069
5070static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5071{
5072 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005073 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005074
Denys Vlasenko9e800222010-10-03 14:28:04 +02005075#if ENABLE_HUSH_BRACE_EXPANSION
5076 if (c == '{' || c == '}') {
5077 /* { -> \{, } -> \} */
5078 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005079 /* And now we want to add { or } and continue:
5080 * o_addchr(o, c);
5081 * continue;
5082 * luckily, just falling throught achieves this.
5083 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005084 }
5085#endif
5086 o_addchr(o, c);
5087 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005088 /* \z -> \\\z; \<eol> -> \\<eol> */
5089 o_addchr(o, '\\');
5090 if (len) {
5091 len--;
5092 o_addchr(o, '\\');
5093 o_addchr(o, *str++);
5094 }
5095 }
5096 }
5097}
5098
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005099/* Store given string, finalizing the word and starting new one whenever
5100 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005101 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5102 * Return in *ended_with_ifs:
5103 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5104 */
5105static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005106{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005107 int last_is_ifs = 0;
5108
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005109 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005110 int word_len;
5111
5112 if (!*str) /* EOL - do not finalize word */
5113 break;
5114 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005115 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005116 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005117 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005118 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005119 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005120 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005121 * Example: "v='\*'; echo b$v" prints "b\*"
5122 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005123 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005124 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005125 /*/ Why can't we do it easier? */
5126 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5127 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5128 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005129 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005130 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005131 if (!*str) /* EOL - do not finalize word */
5132 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005133 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005134
5135 /* We know str here points to at least one IFS char */
5136 last_is_ifs = 1;
5137 str += strspn(str, G.ifs); /* skip IFS chars */
5138 if (!*str) /* EOL - do not finalize word */
5139 break;
5140
5141 /* Start new word... but not always! */
5142 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005143 if (output->has_quoted_part
5144 /* Case "v=' a'; echo $v":
5145 * here nothing precedes the space in $v expansion,
5146 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005147 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005148 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005149 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005150 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005151 o_addchr(output, '\0');
5152 debug_print_list("expand_on_ifs", output, n);
5153 n = o_save_ptr(output, n);
5154 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005155 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005156
5157 if (ended_with_ifs)
5158 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005159 debug_print_list("expand_on_ifs[1]", output, n);
5160 return n;
5161}
5162
5163/* Helper to expand $((...)) and heredoc body. These act as if
5164 * they are in double quotes, with the exception that they are not :).
5165 * Just the rules are similar: "expand only $var and `cmd`"
5166 *
5167 * Returns malloced string.
5168 * As an optimization, we return NULL if expansion is not needed.
5169 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005170#if !ENABLE_HUSH_BASH_COMPAT
5171/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5172#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5173 encode_then_expand_string(str)
5174#endif
5175static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005176{
5177 char *exp_str;
5178 struct in_str input;
5179 o_string dest = NULL_O_STRING;
5180
5181 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005182 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005183#if ENABLE_HUSH_TICK
5184 && !strchr(str, '`')
5185#endif
5186 ) {
5187 return NULL;
5188 }
5189
5190 /* We need to expand. Example:
5191 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5192 */
5193 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005194 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005195//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005196 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005197 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005198 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5199 o_free_unsafe(&dest);
5200 return exp_str;
5201}
5202
5203#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02005204static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005205{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005206 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005207 arith_t res;
5208 char *exp_str;
5209
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005210 math_state.lookupvar = get_local_var_value;
5211 math_state.setvar = set_local_var_from_halves;
5212 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005213 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005214 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005215 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005216 if (errmsg_p)
5217 *errmsg_p = math_state.errmsg;
5218 if (math_state.errmsg)
5219 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005220 return res;
5221}
5222#endif
5223
5224#if ENABLE_HUSH_BASH_COMPAT
5225/* ${var/[/]pattern[/repl]} helpers */
5226static char *strstr_pattern(char *val, const char *pattern, int *size)
5227{
5228 while (1) {
5229 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5230 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5231 if (end) {
5232 *size = end - val;
5233 return val;
5234 }
5235 if (*val == '\0')
5236 return NULL;
5237 /* Optimization: if "*pat" did not match the start of "string",
5238 * we know that "tring", "ring" etc will not match too:
5239 */
5240 if (pattern[0] == '*')
5241 return NULL;
5242 val++;
5243 }
5244}
5245static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5246{
5247 char *result = NULL;
5248 unsigned res_len = 0;
5249 unsigned repl_len = strlen(repl);
5250
5251 while (1) {
5252 int size;
5253 char *s = strstr_pattern(val, pattern, &size);
5254 if (!s)
5255 break;
5256
5257 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5258 memcpy(result + res_len, val, s - val);
5259 res_len += s - val;
5260 strcpy(result + res_len, repl);
5261 res_len += repl_len;
5262 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5263
5264 val = s + size;
5265 if (exp_op == '/')
5266 break;
5267 }
5268 if (val[0] && result) {
5269 result = xrealloc(result, res_len + strlen(val) + 1);
5270 strcpy(result + res_len, val);
5271 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5272 }
5273 debug_printf_varexp("result:'%s'\n", result);
5274 return result;
5275}
5276#endif
5277
5278/* Helper:
5279 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5280 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005281static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005282{
5283 const char *val = NULL;
5284 char *to_be_freed = NULL;
5285 char *p = *pp;
5286 char *var;
5287 char first_char;
5288 char exp_op;
5289 char exp_save = exp_save; /* for compiler */
5290 char *exp_saveptr; /* points to expansion operator */
5291 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005292 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005293
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005294 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005295 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005296 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005297 arg0 = arg[0];
5298 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005299 exp_op = 0;
5300
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005301 if (first_char == '#' /* ${#... */
5302 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5303 ) {
5304 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005305 var++;
5306 exp_op = 'L';
5307 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005308 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005309 if (exp_saveptr /* if 2nd char is one of expansion operators */
5310 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5311 ) {
5312 /* ${?:0}, ${#[:]%0} etc */
5313 exp_saveptr = var + 1;
5314 } else {
5315 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5316 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5317 }
5318 exp_op = exp_save = *exp_saveptr;
5319 if (exp_op) {
5320 exp_word = exp_saveptr + 1;
5321 if (exp_op == ':') {
5322 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005323//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005324 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005325 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005326 ) {
5327 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5328 exp_op = ':';
5329 exp_word--;
5330 }
5331 }
5332 *exp_saveptr = '\0';
5333 } /* else: it's not an expansion op, but bare ${var} */
5334 }
5335
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005336 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005337 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005338 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005339 int n = xatoi_positive(var);
5340 if (n < G.global_argc)
5341 val = G.global_argv[n];
5342 /* else val remains NULL: $N with too big N */
5343 } else {
5344 switch (var[0]) {
5345 case '$': /* pid */
5346 val = utoa(G.root_pid);
5347 break;
5348 case '!': /* bg pid */
5349 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5350 break;
5351 case '?': /* exitcode */
5352 val = utoa(G.last_exitcode);
5353 break;
5354 case '#': /* argc */
5355 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5356 break;
5357 default:
5358 val = get_local_var_value(var);
5359 }
5360 }
5361
5362 /* Handle any expansions */
5363 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005364 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005365 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005366 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005367 debug_printf_expand("%s\n", val);
5368 } else if (exp_op) {
5369 if (exp_op == '%' || exp_op == '#') {
5370 /* Standard-mandated substring removal ops:
5371 * ${parameter%word} - remove smallest suffix pattern
5372 * ${parameter%%word} - remove largest suffix pattern
5373 * ${parameter#word} - remove smallest prefix pattern
5374 * ${parameter##word} - remove largest prefix pattern
5375 *
5376 * Word is expanded to produce a glob pattern.
5377 * Then var's value is matched to it and matching part removed.
5378 */
5379 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005380 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005381 char *exp_exp_word;
5382 char *loc;
5383 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005384 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005385 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005386 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005387 if (exp_exp_word)
5388 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005389 /* HACK ALERT. We depend here on the fact that
5390 * G.global_argv and results of utoa and get_local_var_value
5391 * are actually in writable memory:
5392 * scan_and_match momentarily stores NULs there. */
5393 t = (char*)val;
5394 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005395 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005396 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005397 free(exp_exp_word);
5398 if (loc) { /* match was found */
5399 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005400 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005401 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005402 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005403 }
5404 }
5405 }
5406#if ENABLE_HUSH_BASH_COMPAT
5407 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005408 /* It's ${var/[/]pattern[/repl]} thing.
5409 * Note that in encoded form it has TWO parts:
5410 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005411 * and if // is used, it is encoded as \:
5412 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005413 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005414 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005415 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005416 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005417 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005418 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005419 * by the usual expansion rules:
5420 * >az; >bz;
5421 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5422 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5423 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5424 * v='a bz'; echo ${v/a*z/\z} prints "z"
5425 * (note that a*z _pattern_ is never globbed!)
5426 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005427 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005428 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005429 if (!pattern)
5430 pattern = xstrdup(exp_word);
5431 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5432 *p++ = SPECIAL_VAR_SYMBOL;
5433 exp_word = p;
5434 p = strchr(p, SPECIAL_VAR_SYMBOL);
5435 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005436 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005437 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5438 /* HACK ALERT. We depend here on the fact that
5439 * G.global_argv and results of utoa and get_local_var_value
5440 * are actually in writable memory:
5441 * replace_pattern momentarily stores NULs there. */
5442 t = (char*)val;
5443 to_be_freed = replace_pattern(t,
5444 pattern,
5445 (repl ? repl : exp_word),
5446 exp_op);
5447 if (to_be_freed) /* at least one replace happened */
5448 val = to_be_freed;
5449 free(pattern);
5450 free(repl);
5451 }
5452 }
5453#endif
5454 else if (exp_op == ':') {
5455#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5456 /* It's ${var:N[:M]} bashism.
5457 * Note that in encoded form it has TWO parts:
5458 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5459 */
5460 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005461 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005462
Denys Vlasenko063847d2010-09-15 13:33:02 +02005463 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5464 if (errmsg)
5465 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005466 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5467 *p++ = SPECIAL_VAR_SYMBOL;
5468 exp_word = p;
5469 p = strchr(p, SPECIAL_VAR_SYMBOL);
5470 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005471 len = expand_and_evaluate_arith(exp_word, &errmsg);
5472 if (errmsg)
5473 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005474 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005475 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005476 if (beg < 0) /* bash compat */
5477 beg = 0;
5478 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005479 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005480 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005481 val = NULL;
5482 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005483 /* Paranoia. What if user entered 9999999999999
5484 * which fits in arith_t but not int? */
5485 if (len >= INT_MAX)
5486 len = INT_MAX;
5487 val = to_be_freed = xstrndup(val + beg, len);
5488 }
5489 debug_printf_varexp("val:'%s'\n", val);
5490 } else
5491#endif
5492 {
5493 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005494 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005495 }
5496 } else { /* one of "-=+?" */
5497 /* Standard-mandated substitution ops:
5498 * ${var?word} - indicate error if unset
5499 * If var is unset, word (or a message indicating it is unset
5500 * if word is null) is written to standard error
5501 * and the shell exits with a non-zero exit status.
5502 * Otherwise, the value of var is substituted.
5503 * ${var-word} - use default value
5504 * If var is unset, word is substituted.
5505 * ${var=word} - assign and use default value
5506 * If var is unset, word is assigned to var.
5507 * In all cases, final value of var is substituted.
5508 * ${var+word} - use alternative value
5509 * If var is unset, null is substituted.
5510 * Otherwise, word is substituted.
5511 *
5512 * Word is subjected to tilde expansion, parameter expansion,
5513 * command substitution, and arithmetic expansion.
5514 * If word is not needed, it is not expanded.
5515 *
5516 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5517 * but also treat null var as if it is unset.
5518 */
5519 int use_word = (!val || ((exp_save == ':') && !val[0]));
5520 if (exp_op == '+')
5521 use_word = !use_word;
5522 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5523 (exp_save == ':') ? "true" : "false", use_word);
5524 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005525 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005526 if (to_be_freed)
5527 exp_word = to_be_freed;
5528 if (exp_op == '?') {
5529 /* mimic bash message */
5530 die_if_script("%s: %s",
5531 var,
5532 exp_word[0] ? exp_word : "parameter null or not set"
5533 );
5534//TODO: how interactive bash aborts expansion mid-command?
5535 } else {
5536 val = exp_word;
5537 }
5538
5539 if (exp_op == '=') {
5540 /* ${var=[word]} or ${var:=[word]} */
5541 if (isdigit(var[0]) || var[0] == '#') {
5542 /* mimic bash message */
5543 die_if_script("$%s: cannot assign in this way", var);
5544 val = NULL;
5545 } else {
5546 char *new_var = xasprintf("%s=%s", var, val);
5547 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5548 }
5549 }
5550 }
5551 } /* one of "-=+?" */
5552
5553 *exp_saveptr = exp_save;
5554 } /* if (exp_op) */
5555
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005556 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005557
5558 *pp = p;
5559 *to_be_freed_pp = to_be_freed;
5560 return val;
5561}
5562
5563/* Expand all variable references in given string, adding words to list[]
5564 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5565 * to be filled). This routine is extremely tricky: has to deal with
5566 * variables/parameters with whitespace, $* and $@, and constructs like
5567 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005568static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005569{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005570 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005571 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005572 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005573 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005574 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005575 char *p;
5576
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005577 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5578 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005579 debug_print_list("expand_vars_to_list", output, n);
5580 n = o_save_ptr(output, n);
5581 debug_print_list("expand_vars_to_list[0]", output, n);
5582
5583 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5584 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005585 char *to_be_freed = NULL;
5586 const char *val = NULL;
5587#if ENABLE_HUSH_TICK
5588 o_string subst_result = NULL_O_STRING;
5589#endif
5590#if ENABLE_SH_MATH_SUPPORT
5591 char arith_buf[sizeof(arith_t)*3 + 2];
5592#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005593
5594 if (ended_in_ifs) {
5595 o_addchr(output, '\0');
5596 n = o_save_ptr(output, n);
5597 ended_in_ifs = 0;
5598 }
5599
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005600 o_addblock(output, arg, p - arg);
5601 debug_print_list("expand_vars_to_list[1]", output, n);
5602 arg = ++p;
5603 p = strchr(p, SPECIAL_VAR_SYMBOL);
5604
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005605 /* Fetch special var name (if it is indeed one of them)
5606 * and quote bit, force the bit on if singleword expansion -
5607 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005608 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005609
5610 /* Is this variable quoted and thus expansion can't be null?
5611 * "$@" is special. Even if quoted, it can still
5612 * expand to nothing (not even an empty string),
5613 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005614 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005615 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005616
5617 switch (first_ch & 0x7f) {
5618 /* Highest bit in first_ch indicates that var is double-quoted */
5619 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005620 case '@': {
5621 int i;
5622 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005623 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005624 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005625 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005626 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005627 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005628 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005629 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5630 if (G.global_argv[i++][0] && G.global_argv[i]) {
5631 /* this argv[] is not empty and not last:
5632 * put terminating NUL, start new word */
5633 o_addchr(output, '\0');
5634 debug_print_list("expand_vars_to_list[2]", output, n);
5635 n = o_save_ptr(output, n);
5636 debug_print_list("expand_vars_to_list[3]", output, n);
5637 }
5638 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005639 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005640 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005641 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005642 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005643 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005644 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005645 while (1) {
5646 o_addQstr(output, G.global_argv[i]);
5647 if (++i >= G.global_argc)
5648 break;
5649 o_addchr(output, '\0');
5650 debug_print_list("expand_vars_to_list[4]", output, n);
5651 n = o_save_ptr(output, n);
5652 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005653 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005654 while (1) {
5655 o_addQstr(output, G.global_argv[i]);
5656 if (!G.global_argv[++i])
5657 break;
5658 if (G.ifs[0])
5659 o_addchr(output, G.ifs[0]);
5660 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005661 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005662 }
5663 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005664 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005665 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5666 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005667 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005668 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005669 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005670 break;
5671#if ENABLE_HUSH_TICK
5672 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005673 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005674 arg++;
5675 /* Can't just stuff it into output o_string,
5676 * expanded result may need to be globbed
5677 * and $IFS-splitted */
5678 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5679 G.last_exitcode = process_command_subs(&subst_result, arg);
5680 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5681 val = subst_result.data;
5682 goto store_val;
5683#endif
5684#if ENABLE_SH_MATH_SUPPORT
5685 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5686 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005687
5688 arg++; /* skip '+' */
5689 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5690 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005691 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005692 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5693 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005694 val = arith_buf;
5695 break;
5696 }
5697#endif
5698 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005699 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005700 IF_HUSH_TICK(store_val:)
5701 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005702 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5703 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005704 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005705 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005706 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005707 }
5708 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005709 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005710 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5711 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005712 }
5713 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005714 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5715
5716 if (val && val[0]) {
5717 o_addQstr(output, val);
5718 }
5719 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005720
5721 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5722 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005723 if (*p != SPECIAL_VAR_SYMBOL)
5724 *p = SPECIAL_VAR_SYMBOL;
5725
5726#if ENABLE_HUSH_TICK
5727 o_free(&subst_result);
5728#endif
5729 arg = ++p;
5730 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5731
5732 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005733 if (ended_in_ifs) {
5734 o_addchr(output, '\0');
5735 n = o_save_ptr(output, n);
5736 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005737 debug_print_list("expand_vars_to_list[a]", output, n);
5738 /* this part is literal, and it was already pre-quoted
5739 * if needed (much earlier), do not use o_addQstr here! */
5740 o_addstr_with_NUL(output, arg);
5741 debug_print_list("expand_vars_to_list[b]", output, n);
5742 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005743 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005744 ) {
5745 n--;
5746 /* allow to reuse list[n] later without re-growth */
5747 output->has_empty_slot = 1;
5748 } else {
5749 o_addchr(output, '\0');
5750 }
5751
5752 return n;
5753}
5754
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005755static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005756{
5757 int n;
5758 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005759 o_string output = NULL_O_STRING;
5760
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005761 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005762
5763 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005764 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005765 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005766 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005767 }
5768 debug_print_list("expand_variables", &output, n);
5769
5770 /* output.data (malloced in one block) gets returned in "list" */
5771 list = o_finalize_list(&output, n);
5772 debug_print_strings("expand_variables[1]", list);
5773 return list;
5774}
5775
5776static char **expand_strvec_to_strvec(char **argv)
5777{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005778 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005779}
5780
5781#if ENABLE_HUSH_BASH_COMPAT
5782static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5783{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005784 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005785}
5786#endif
5787
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005788/* Used for expansion of right hand of assignments,
5789 * $((...)), heredocs, variable espansion parts.
5790 *
5791 * NB: should NOT do globbing!
5792 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5793 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005794static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005795{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005796#if !ENABLE_HUSH_BASH_COMPAT
5797 const int do_unbackslash = 1;
5798#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005799 char *argv[2], **list;
5800
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005801 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005802 /* This is generally an optimization, but it also
5803 * handles "", which otherwise trips over !list[0] check below.
5804 * (is this ever happens that we actually get str="" here?)
5805 */
5806 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5807 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005808 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005809 return xstrdup(str);
5810 }
5811
5812 argv[0] = (char*)str;
5813 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005814 list = expand_variables(argv, do_unbackslash
5815 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5816 : EXP_FLAG_SINGLEWORD
5817 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005818 if (HUSH_DEBUG)
5819 if (!list[0] || list[1])
5820 bb_error_msg_and_die("BUG in varexp2");
5821 /* actually, just move string 2*sizeof(char*) bytes back */
5822 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005823 if (do_unbackslash)
5824 unbackslash((char*)list);
5825 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005826 return (char*)list;
5827}
5828
5829/* Used for "eval" builtin */
5830static char* expand_strvec_to_string(char **argv)
5831{
5832 char **list;
5833
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005834 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005835 /* Convert all NULs to spaces */
5836 if (list[0]) {
5837 int n = 1;
5838 while (list[n]) {
5839 if (HUSH_DEBUG)
5840 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5841 bb_error_msg_and_die("BUG in varexp3");
5842 /* bash uses ' ' regardless of $IFS contents */
5843 list[n][-1] = ' ';
5844 n++;
5845 }
5846 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02005847 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005848 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5849 return (char*)list;
5850}
5851
5852static char **expand_assignments(char **argv, int count)
5853{
5854 int i;
5855 char **p;
5856
5857 G.expanded_assignments = p = NULL;
5858 /* Expand assignments into one string each */
5859 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005860 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005861 }
5862 G.expanded_assignments = NULL;
5863 return p;
5864}
5865
5866
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005867static void switch_off_special_sigs(unsigned mask)
5868{
5869 unsigned sig = 0;
5870 while ((mask >>= 1) != 0) {
5871 sig++;
5872 if (!(mask & 1))
5873 continue;
5874 if (G.traps) {
5875 if (G.traps[sig] && !G.traps[sig][0])
5876 /* trap is '', has to remain SIG_IGN */
5877 continue;
5878 free(G.traps[sig]);
5879 G.traps[sig] = NULL;
5880 }
5881 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005882 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005883 }
5884}
5885
Denys Vlasenkob347df92011-08-09 22:49:15 +02005886#if BB_MMU
5887/* never called */
5888void re_execute_shell(char ***to_free, const char *s,
5889 char *g_argv0, char **g_argv,
5890 char **builtin_argv) NORETURN;
5891
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005892static void reset_traps_to_defaults(void)
5893{
5894 /* This function is always called in a child shell
5895 * after fork (not vfork, NOMMU doesn't use this function).
5896 */
5897 unsigned sig;
5898 unsigned mask;
5899
5900 /* Child shells are not interactive.
5901 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5902 * Testcase: (while :; do :; done) + ^Z should background.
5903 * Same goes for SIGTERM, SIGHUP, SIGINT.
5904 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005905 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5906 if (!G.traps && !mask)
5907 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005908
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005909 /* Switch off special sigs */
5910 switch_off_special_sigs(mask);
5911#if ENABLE_HUSH_JOB
5912 G_fatal_sig_mask = 0;
5913#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005914 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005915 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5916 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005917
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005918 if (!G.traps)
5919 return;
5920
5921 /* Reset all sigs to default except ones with empty traps */
5922 for (sig = 0; sig < NSIG; sig++) {
5923 if (!G.traps[sig])
5924 continue; /* no trap: nothing to do */
5925 if (!G.traps[sig][0])
5926 continue; /* empty trap: has to remain SIG_IGN */
5927 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005928 free(G.traps[sig]);
5929 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005930 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005931 if (sig == 0)
5932 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005933 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005934 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005935}
5936
5937#else /* !BB_MMU */
5938
5939static void re_execute_shell(char ***to_free, const char *s,
5940 char *g_argv0, char **g_argv,
5941 char **builtin_argv) NORETURN;
5942static void re_execute_shell(char ***to_free, const char *s,
5943 char *g_argv0, char **g_argv,
5944 char **builtin_argv)
5945{
5946# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5947 /* delims + 2 * (number of bytes in printed hex numbers) */
5948 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5949 char *heredoc_argv[4];
5950 struct variable *cur;
5951# if ENABLE_HUSH_FUNCTIONS
5952 struct function *funcp;
5953# endif
5954 char **argv, **pp;
5955 unsigned cnt;
5956 unsigned long long empty_trap_mask;
5957
5958 if (!g_argv0) { /* heredoc */
5959 argv = heredoc_argv;
5960 argv[0] = (char *) G.argv0_for_re_execing;
5961 argv[1] = (char *) "-<";
5962 argv[2] = (char *) s;
5963 argv[3] = NULL;
5964 pp = &argv[3]; /* used as pointer to empty environment */
5965 goto do_exec;
5966 }
5967
5968 cnt = 0;
5969 pp = builtin_argv;
5970 if (pp) while (*pp++)
5971 cnt++;
5972
5973 empty_trap_mask = 0;
5974 if (G.traps) {
5975 int sig;
5976 for (sig = 1; sig < NSIG; sig++) {
5977 if (G.traps[sig] && !G.traps[sig][0])
5978 empty_trap_mask |= 1LL << sig;
5979 }
5980 }
5981
5982 sprintf(param_buf, NOMMU_HACK_FMT
5983 , (unsigned) G.root_pid
5984 , (unsigned) G.root_ppid
5985 , (unsigned) G.last_bg_pid
5986 , (unsigned) G.last_exitcode
5987 , cnt
5988 , empty_trap_mask
5989 IF_HUSH_LOOPS(, G.depth_of_loop)
5990 );
5991# undef NOMMU_HACK_FMT
5992 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5993 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5994 */
5995 cnt += 6;
5996 for (cur = G.top_var; cur; cur = cur->next) {
5997 if (!cur->flg_export || cur->flg_read_only)
5998 cnt += 2;
5999 }
6000# if ENABLE_HUSH_FUNCTIONS
6001 for (funcp = G.top_func; funcp; funcp = funcp->next)
6002 cnt += 3;
6003# endif
6004 pp = g_argv;
6005 while (*pp++)
6006 cnt++;
6007 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6008 *pp++ = (char *) G.argv0_for_re_execing;
6009 *pp++ = param_buf;
6010 for (cur = G.top_var; cur; cur = cur->next) {
6011 if (strcmp(cur->varstr, hush_version_str) == 0)
6012 continue;
6013 if (cur->flg_read_only) {
6014 *pp++ = (char *) "-R";
6015 *pp++ = cur->varstr;
6016 } else if (!cur->flg_export) {
6017 *pp++ = (char *) "-V";
6018 *pp++ = cur->varstr;
6019 }
6020 }
6021# if ENABLE_HUSH_FUNCTIONS
6022 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6023 *pp++ = (char *) "-F";
6024 *pp++ = funcp->name;
6025 *pp++ = funcp->body_as_string;
6026 }
6027# endif
6028 /* We can pass activated traps here. Say, -Tnn:trap_string
6029 *
6030 * However, POSIX says that subshells reset signals with traps
6031 * to SIG_DFL.
6032 * I tested bash-3.2 and it not only does that with true subshells
6033 * of the form ( list ), but with any forked children shells.
6034 * I set trap "echo W" WINCH; and then tried:
6035 *
6036 * { echo 1; sleep 20; echo 2; } &
6037 * while true; do echo 1; sleep 20; echo 2; break; done &
6038 * true | { echo 1; sleep 20; echo 2; } | cat
6039 *
6040 * In all these cases sending SIGWINCH to the child shell
6041 * did not run the trap. If I add trap "echo V" WINCH;
6042 * _inside_ group (just before echo 1), it works.
6043 *
6044 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006045 */
6046 *pp++ = (char *) "-c";
6047 *pp++ = (char *) s;
6048 if (builtin_argv) {
6049 while (*++builtin_argv)
6050 *pp++ = *builtin_argv;
6051 *pp++ = (char *) "";
6052 }
6053 *pp++ = g_argv0;
6054 while (*g_argv)
6055 *pp++ = *g_argv++;
6056 /* *pp = NULL; - is already there */
6057 pp = environ;
6058
6059 do_exec:
6060 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006061 /* Don't propagate SIG_IGN to the child */
6062 if (SPECIAL_JOBSTOP_SIGS != 0)
6063 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006064 execve(bb_busybox_exec_path, argv, pp);
6065 /* Fallback. Useful for init=/bin/hush usage etc */
6066 if (argv[0][0] == '/')
6067 execve(argv[0], argv, pp);
6068 xfunc_error_retval = 127;
6069 bb_error_msg_and_die("can't re-execute the shell");
6070}
6071#endif /* !BB_MMU */
6072
6073
6074static int run_and_free_list(struct pipe *pi);
6075
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006076/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006077 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6078 * end_trigger controls how often we stop parsing
6079 * NUL: parse all, execute, return
6080 * ';': parse till ';' or newline, execute, repeat till EOF
6081 */
6082static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006083{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006084 /* Why we need empty flag?
6085 * An obscure corner case "false; ``; echo $?":
6086 * empty command in `` should still set $? to 0.
6087 * But we can't just set $? to 0 at the start,
6088 * this breaks "false; echo `echo $?`" case.
6089 */
6090 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006091 while (1) {
6092 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006093
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006094#if ENABLE_HUSH_INTERACTIVE
6095 if (end_trigger == ';')
6096 inp->promptmode = 0; /* PS1 */
6097#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006098 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006099 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6100 /* If we are in "big" script
6101 * (not in `cmd` or something similar)...
6102 */
6103 if (pipe_list == ERR_PTR && end_trigger == ';') {
6104 /* Discard cached input (rest of line) */
6105 int ch = inp->last_char;
6106 while (ch != EOF && ch != '\n') {
6107 //bb_error_msg("Discarded:'%c'", ch);
6108 ch = i_getch(inp);
6109 }
6110 /* Force prompt */
6111 inp->p = NULL;
6112 /* This stream isn't empty */
6113 empty = 0;
6114 continue;
6115 }
6116 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006117 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006118 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006119 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006120 debug_print_tree(pipe_list, 0);
6121 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6122 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006123 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006124 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006125 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006126 }
Eric Andersen25f27032001-04-26 23:22:31 +00006127}
6128
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006129static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006130{
6131 struct in_str input;
6132 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006133 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006134}
6135
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006136static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006137{
Eric Andersen25f27032001-04-26 23:22:31 +00006138 struct in_str input;
6139 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006140 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006141}
6142
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006143#if ENABLE_HUSH_TICK
6144static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6145{
6146 pid_t pid;
6147 int channel[2];
6148# if !BB_MMU
6149 char **to_free = NULL;
6150# endif
6151
6152 xpipe(channel);
6153 pid = BB_MMU ? xfork() : xvfork();
6154 if (pid == 0) { /* child */
6155 disable_restore_tty_pgrp_on_exit();
6156 /* Process substitution is not considered to be usual
6157 * 'command execution'.
6158 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6159 */
6160 bb_signals(0
6161 + (1 << SIGTSTP)
6162 + (1 << SIGTTIN)
6163 + (1 << SIGTTOU)
6164 , SIG_IGN);
6165 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6166 close(channel[0]); /* NB: close _first_, then move fd! */
6167 xmove_fd(channel[1], 1);
6168 /* Prevent it from trying to handle ctrl-z etc */
6169 IF_HUSH_JOB(G.run_list_level = 1;)
6170 /* Awful hack for `trap` or $(trap).
6171 *
6172 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6173 * contains an example where "trap" is executed in a subshell:
6174 *
6175 * save_traps=$(trap)
6176 * ...
6177 * eval "$save_traps"
6178 *
6179 * Standard does not say that "trap" in subshell shall print
6180 * parent shell's traps. It only says that its output
6181 * must have suitable form, but then, in the above example
6182 * (which is not supposed to be normative), it implies that.
6183 *
6184 * bash (and probably other shell) does implement it
6185 * (traps are reset to defaults, but "trap" still shows them),
6186 * but as a result, "trap" logic is hopelessly messed up:
6187 *
6188 * # trap
6189 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6190 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6191 * # true | trap <--- trap is in subshell - no output (ditto)
6192 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6193 * trap -- 'echo Ho' SIGWINCH
6194 * # echo `(trap)` <--- in subshell in subshell - output
6195 * trap -- 'echo Ho' SIGWINCH
6196 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6197 * trap -- 'echo Ho' SIGWINCH
6198 *
6199 * The rules when to forget and when to not forget traps
6200 * get really complex and nonsensical.
6201 *
6202 * Our solution: ONLY bare $(trap) or `trap` is special.
6203 */
6204 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006205 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006206 && skip_whitespace(s + 4)[0] == '\0'
6207 ) {
6208 static const char *const argv[] = { NULL, NULL };
6209 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006210 fflush_all(); /* important */
6211 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006212 }
6213# if BB_MMU
6214 reset_traps_to_defaults();
6215 parse_and_run_string(s);
6216 _exit(G.last_exitcode);
6217# else
6218 /* We re-execute after vfork on NOMMU. This makes this script safe:
6219 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6220 * huge=`cat BIG` # was blocking here forever
6221 * echo OK
6222 */
6223 re_execute_shell(&to_free,
6224 s,
6225 G.global_argv[0],
6226 G.global_argv + 1,
6227 NULL);
6228# endif
6229 }
6230
6231 /* parent */
6232 *pid_p = pid;
6233# if ENABLE_HUSH_FAST
6234 G.count_SIGCHLD++;
6235//bb_error_msg("[%d] fork in generate_stream_from_string:"
6236// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6237// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6238# endif
6239 enable_restore_tty_pgrp_on_exit();
6240# if !BB_MMU
6241 free(to_free);
6242# endif
6243 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006244 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006245}
6246
6247/* Return code is exit status of the process that is run. */
6248static int process_command_subs(o_string *dest, const char *s)
6249{
6250 FILE *fp;
6251 struct in_str pipe_str;
6252 pid_t pid;
6253 int status, ch, eol_cnt;
6254
6255 fp = generate_stream_from_string(s, &pid);
6256
6257 /* Now send results of command back into original context */
6258 setup_file_in_str(&pipe_str, fp);
6259 eol_cnt = 0;
6260 while ((ch = i_getch(&pipe_str)) != EOF) {
6261 if (ch == '\n') {
6262 eol_cnt++;
6263 continue;
6264 }
6265 while (eol_cnt) {
6266 o_addchr(dest, '\n');
6267 eol_cnt--;
6268 }
6269 o_addQchr(dest, ch);
6270 }
6271
6272 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006273 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006274 /* We need to extract exitcode. Test case
6275 * "true; echo `sleep 1; false` $?"
6276 * should print 1 */
6277 safe_waitpid(pid, &status, 0);
6278 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6279 return WEXITSTATUS(status);
6280}
6281#endif /* ENABLE_HUSH_TICK */
6282
6283
6284static void setup_heredoc(struct redir_struct *redir)
6285{
6286 struct fd_pair pair;
6287 pid_t pid;
6288 int len, written;
6289 /* the _body_ of heredoc (misleading field name) */
6290 const char *heredoc = redir->rd_filename;
6291 char *expanded;
6292#if !BB_MMU
6293 char **to_free;
6294#endif
6295
6296 expanded = NULL;
6297 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006298 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006299 if (expanded)
6300 heredoc = expanded;
6301 }
6302 len = strlen(heredoc);
6303
6304 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6305 xpiped_pair(pair);
6306 xmove_fd(pair.rd, redir->rd_fd);
6307
6308 /* Try writing without forking. Newer kernels have
6309 * dynamically growing pipes. Must use non-blocking write! */
6310 ndelay_on(pair.wr);
6311 while (1) {
6312 written = write(pair.wr, heredoc, len);
6313 if (written <= 0)
6314 break;
6315 len -= written;
6316 if (len == 0) {
6317 close(pair.wr);
6318 free(expanded);
6319 return;
6320 }
6321 heredoc += written;
6322 }
6323 ndelay_off(pair.wr);
6324
6325 /* Okay, pipe buffer was not big enough */
6326 /* Note: we must not create a stray child (bastard? :)
6327 * for the unsuspecting parent process. Child creates a grandchild
6328 * and exits before parent execs the process which consumes heredoc
6329 * (that exec happens after we return from this function) */
6330#if !BB_MMU
6331 to_free = NULL;
6332#endif
6333 pid = xvfork();
6334 if (pid == 0) {
6335 /* child */
6336 disable_restore_tty_pgrp_on_exit();
6337 pid = BB_MMU ? xfork() : xvfork();
6338 if (pid != 0)
6339 _exit(0);
6340 /* grandchild */
6341 close(redir->rd_fd); /* read side of the pipe */
6342#if BB_MMU
6343 full_write(pair.wr, heredoc, len); /* may loop or block */
6344 _exit(0);
6345#else
6346 /* Delegate blocking writes to another process */
6347 xmove_fd(pair.wr, STDOUT_FILENO);
6348 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6349#endif
6350 }
6351 /* parent */
6352#if ENABLE_HUSH_FAST
6353 G.count_SIGCHLD++;
6354//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6355#endif
6356 enable_restore_tty_pgrp_on_exit();
6357#if !BB_MMU
6358 free(to_free);
6359#endif
6360 close(pair.wr);
6361 free(expanded);
6362 wait(NULL); /* wait till child has died */
6363}
6364
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006365/* fd: redirect wants this fd to be used (e.g. 3>file).
6366 * Move all conflicting internally used fds,
6367 * and remember them so that we can restore them later.
6368 */
6369static int save_fds_on_redirect(int fd, int squirrel[3])
6370{
6371 if (squirrel) {
6372 /* Handle redirects of fds 0,1,2 */
6373
6374 /* If we collide with an already moved stdio fd... */
6375 if (fd == squirrel[0]) {
6376 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6377 return 1;
6378 }
6379 if (fd == squirrel[1]) {
6380 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6381 return 1;
6382 }
6383 if (fd == squirrel[2]) {
6384 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6385 return 1;
6386 }
6387 /* If we are about to redirect stdio fd, and did not yet move it... */
6388 if (fd <= 2 && squirrel[fd] < 0) {
6389 /* We avoid taking stdio fds */
6390 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6391 if (squirrel[fd] < 0 && errno != EBADF)
6392 xfunc_die();
6393 return 0; /* "we did not close fd" */
6394 }
6395 }
6396
6397#if ENABLE_HUSH_INTERACTIVE
6398 if (fd != 0 && fd == G.interactive_fd) {
6399 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6400 return 1;
6401 }
6402#endif
6403
6404 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6405 * (1) Redirect in a forked child. No need to save FILEs' fds,
6406 * we aren't going to use them anymore, ok to trash.
6407 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6408 * but how are we doing to use them?
6409 * "fileno(fd) = new_fd" can't be done.
6410 */
6411 if (!squirrel)
6412 return 0;
6413
6414 return save_FILEs_on_redirect(fd);
6415}
6416
6417static void restore_redirects(int squirrel[3])
6418{
6419 int i, fd;
6420 for (i = 0; i <= 2; i++) {
6421 fd = squirrel[i];
6422 if (fd != -1) {
6423 /* We simply die on error */
6424 xmove_fd(fd, i);
6425 }
6426 }
6427
6428 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6429
6430 restore_redirected_FILEs();
6431}
6432
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006433/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6434 * and stderr if they are redirected. */
6435static int setup_redirects(struct command *prog, int squirrel[])
6436{
6437 int openfd, mode;
6438 struct redir_struct *redir;
6439
6440 for (redir = prog->redirects; redir; redir = redir->next) {
6441 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006442 /* "rd_fd<<HERE" case */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006443 save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006444 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6445 * of the heredoc */
6446 debug_printf_parse("set heredoc '%s'\n",
6447 redir->rd_filename);
6448 setup_heredoc(redir);
6449 continue;
6450 }
6451
6452 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006453 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006454 char *p;
6455 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02006456 /*
6457 * Examples:
6458 * "cmd >" (no filename)
6459 * "cmd > <file" (2nd redirect starts too early)
6460 */
6461 die_if_script("syntax error: %s", "invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006462 continue;
6463 }
6464 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006465 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006466 openfd = open_or_warn(p, mode);
6467 free(p);
6468 if (openfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006469 /* Error message from open_or_warn can be lost
6470 * if stderr has been redirected, but bash
6471 * and ash both lose it as well
6472 * (though zsh doesn't!)
6473 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006474 return 1;
6475 }
6476 } else {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006477 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006478 openfd = redir->rd_dup;
6479 }
6480
6481 if (openfd != redir->rd_fd) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006482 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006483 if (openfd == REDIRFD_CLOSE) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006484 /* "rd_fd >&-" means "close me" */
6485 if (!closed) {
6486 /* ^^^ optimization: saving may already
6487 * have closed it. If not... */
6488 close(redir->rd_fd);
6489 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006490 } else {
6491 xdup2(openfd, redir->rd_fd);
6492 if (redir->rd_dup == REDIRFD_TO_FILE)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006493 /* "rd_fd > FILE" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006494 close(openfd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006495 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006496 }
6497 }
6498 }
6499 return 0;
6500}
6501
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006502static char *find_in_path(const char *arg)
6503{
6504 char *ret = NULL;
6505 const char *PATH = get_local_var_value("PATH");
6506
6507 if (!PATH)
6508 return NULL;
6509
6510 while (1) {
6511 const char *end = strchrnul(PATH, ':');
6512 int sz = end - PATH; /* must be int! */
6513
6514 free(ret);
6515 if (sz != 0) {
6516 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6517 } else {
6518 /* We have xxx::yyyy in $PATH,
6519 * it means "use current dir" */
6520 ret = xstrdup(arg);
6521 }
6522 if (access(ret, F_OK) == 0)
6523 break;
6524
6525 if (*end == '\0') {
6526 free(ret);
6527 return NULL;
6528 }
6529 PATH = end + 1;
6530 }
6531
6532 return ret;
6533}
6534
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006535static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006536 const struct built_in_command *x,
6537 const struct built_in_command *end)
6538{
6539 while (x != end) {
6540 if (strcmp(name, x->b_cmd) != 0) {
6541 x++;
6542 continue;
6543 }
6544 debug_printf_exec("found builtin '%s'\n", name);
6545 return x;
6546 }
6547 return NULL;
6548}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006549static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006550{
6551 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6552}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006553static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006554{
6555 const struct built_in_command *x = find_builtin1(name);
6556 if (x)
6557 return x;
6558 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6559}
6560
6561#if ENABLE_HUSH_FUNCTIONS
6562static struct function **find_function_slot(const char *name)
6563{
6564 struct function **funcpp = &G.top_func;
6565 while (*funcpp) {
6566 if (strcmp(name, (*funcpp)->name) == 0) {
6567 break;
6568 }
6569 funcpp = &(*funcpp)->next;
6570 }
6571 return funcpp;
6572}
6573
6574static const struct function *find_function(const char *name)
6575{
6576 const struct function *funcp = *find_function_slot(name);
6577 if (funcp)
6578 debug_printf_exec("found function '%s'\n", name);
6579 return funcp;
6580}
6581
6582/* Note: takes ownership on name ptr */
6583static struct function *new_function(char *name)
6584{
6585 struct function **funcpp = find_function_slot(name);
6586 struct function *funcp = *funcpp;
6587
6588 if (funcp != NULL) {
6589 struct command *cmd = funcp->parent_cmd;
6590 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6591 if (!cmd) {
6592 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6593 free(funcp->name);
6594 /* Note: if !funcp->body, do not free body_as_string!
6595 * This is a special case of "-F name body" function:
6596 * body_as_string was not malloced! */
6597 if (funcp->body) {
6598 free_pipe_list(funcp->body);
6599# if !BB_MMU
6600 free(funcp->body_as_string);
6601# endif
6602 }
6603 } else {
6604 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6605 cmd->argv[0] = funcp->name;
6606 cmd->group = funcp->body;
6607# if !BB_MMU
6608 cmd->group_as_string = funcp->body_as_string;
6609# endif
6610 }
6611 } else {
6612 debug_printf_exec("remembering new function '%s'\n", name);
6613 funcp = *funcpp = xzalloc(sizeof(*funcp));
6614 /*funcp->next = NULL;*/
6615 }
6616
6617 funcp->name = name;
6618 return funcp;
6619}
6620
6621static void unset_func(const char *name)
6622{
6623 struct function **funcpp = find_function_slot(name);
6624 struct function *funcp = *funcpp;
6625
6626 if (funcp != NULL) {
6627 debug_printf_exec("freeing function '%s'\n", funcp->name);
6628 *funcpp = funcp->next;
6629 /* funcp is unlinked now, deleting it.
6630 * Note: if !funcp->body, the function was created by
6631 * "-F name body", do not free ->body_as_string
6632 * and ->name as they were not malloced. */
6633 if (funcp->body) {
6634 free_pipe_list(funcp->body);
6635 free(funcp->name);
6636# if !BB_MMU
6637 free(funcp->body_as_string);
6638# endif
6639 }
6640 free(funcp);
6641 }
6642}
6643
6644# if BB_MMU
6645#define exec_function(to_free, funcp, argv) \
6646 exec_function(funcp, argv)
6647# endif
6648static void exec_function(char ***to_free,
6649 const struct function *funcp,
6650 char **argv) NORETURN;
6651static void exec_function(char ***to_free,
6652 const struct function *funcp,
6653 char **argv)
6654{
6655# if BB_MMU
6656 int n = 1;
6657
6658 argv[0] = G.global_argv[0];
6659 G.global_argv = argv;
6660 while (*++argv)
6661 n++;
6662 G.global_argc = n;
6663 /* On MMU, funcp->body is always non-NULL */
6664 n = run_list(funcp->body);
6665 fflush_all();
6666 _exit(n);
6667# else
6668 re_execute_shell(to_free,
6669 funcp->body_as_string,
6670 G.global_argv[0],
6671 argv + 1,
6672 NULL);
6673# endif
6674}
6675
6676static int run_function(const struct function *funcp, char **argv)
6677{
6678 int rc;
6679 save_arg_t sv;
6680 smallint sv_flg;
6681
6682 save_and_replace_G_args(&sv, argv);
6683
6684 /* "we are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006685 sv_flg = G_flag_return_in_progress;
6686 G_flag_return_in_progress = -1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006687# if ENABLE_HUSH_LOCAL
6688 G.func_nest_level++;
6689# endif
6690
6691 /* On MMU, funcp->body is always non-NULL */
6692# if !BB_MMU
6693 if (!funcp->body) {
6694 /* Function defined by -F */
6695 parse_and_run_string(funcp->body_as_string);
6696 rc = G.last_exitcode;
6697 } else
6698# endif
6699 {
6700 rc = run_list(funcp->body);
6701 }
6702
6703# if ENABLE_HUSH_LOCAL
6704 {
6705 struct variable *var;
6706 struct variable **var_pp;
6707
6708 var_pp = &G.top_var;
6709 while ((var = *var_pp) != NULL) {
6710 if (var->func_nest_level < G.func_nest_level) {
6711 var_pp = &var->next;
6712 continue;
6713 }
6714 /* Unexport */
6715 if (var->flg_export)
6716 bb_unsetenv(var->varstr);
6717 /* Remove from global list */
6718 *var_pp = var->next;
6719 /* Free */
6720 if (!var->max_len)
6721 free(var->varstr);
6722 free(var);
6723 }
6724 G.func_nest_level--;
6725 }
6726# endif
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006727 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006728
6729 restore_G_args(&sv, argv);
6730
6731 return rc;
6732}
6733#endif /* ENABLE_HUSH_FUNCTIONS */
6734
6735
6736#if BB_MMU
6737#define exec_builtin(to_free, x, argv) \
6738 exec_builtin(x, argv)
6739#else
6740#define exec_builtin(to_free, x, argv) \
6741 exec_builtin(to_free, argv)
6742#endif
6743static void exec_builtin(char ***to_free,
6744 const struct built_in_command *x,
6745 char **argv) NORETURN;
6746static void exec_builtin(char ***to_free,
6747 const struct built_in_command *x,
6748 char **argv)
6749{
6750#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006751 int rcode;
6752 fflush_all();
6753 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006754 fflush_all();
6755 _exit(rcode);
6756#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006757 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006758 /* On NOMMU, we must never block!
6759 * Example: { sleep 99 | read line; } & echo Ok
6760 */
6761 re_execute_shell(to_free,
6762 argv[0],
6763 G.global_argv[0],
6764 G.global_argv + 1,
6765 argv);
6766#endif
6767}
6768
6769
6770static void execvp_or_die(char **argv) NORETURN;
6771static void execvp_or_die(char **argv)
6772{
Denys Vlasenko04465da2016-10-03 01:01:15 +02006773 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006774 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006775 /* Don't propagate SIG_IGN to the child */
6776 if (SPECIAL_JOBSTOP_SIGS != 0)
6777 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006778 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02006779 e = 2;
6780 if (errno == EACCES) e = 126;
6781 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006782 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02006783 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006784}
6785
6786#if ENABLE_HUSH_MODE_X
6787static void dump_cmd_in_x_mode(char **argv)
6788{
6789 if (G_x_mode && argv) {
6790 /* We want to output the line in one write op */
6791 char *buf, *p;
6792 int len;
6793 int n;
6794
6795 len = 3;
6796 n = 0;
6797 while (argv[n])
6798 len += strlen(argv[n++]) + 1;
6799 buf = xmalloc(len);
6800 buf[0] = '+';
6801 p = buf + 1;
6802 n = 0;
6803 while (argv[n])
6804 p += sprintf(p, " %s", argv[n++]);
6805 *p++ = '\n';
6806 *p = '\0';
6807 fputs(buf, stderr);
6808 free(buf);
6809 }
6810}
6811#else
6812# define dump_cmd_in_x_mode(argv) ((void)0)
6813#endif
6814
6815#if BB_MMU
6816#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6817 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6818#define pseudo_exec(nommu_save, command, argv_expanded) \
6819 pseudo_exec(command, argv_expanded)
6820#endif
6821
6822/* Called after [v]fork() in run_pipe, or from builtin_exec.
6823 * Never returns.
6824 * Don't exit() here. If you don't exec, use _exit instead.
6825 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006826 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006827 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006828static void pseudo_exec_argv(nommu_save_t *nommu_save,
6829 char **argv, int assignment_cnt,
6830 char **argv_expanded) NORETURN;
6831static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6832 char **argv, int assignment_cnt,
6833 char **argv_expanded)
6834{
6835 char **new_env;
6836
6837 new_env = expand_assignments(argv, assignment_cnt);
6838 dump_cmd_in_x_mode(new_env);
6839
6840 if (!argv[assignment_cnt]) {
6841 /* Case when we are here: ... | var=val | ...
6842 * (note that we do not exit early, i.e., do not optimize out
6843 * expand_assignments(): think about ... | var=`sleep 1` | ...
6844 */
6845 free_strings(new_env);
6846 _exit(EXIT_SUCCESS);
6847 }
6848
6849#if BB_MMU
6850 set_vars_and_save_old(new_env);
6851 free(new_env); /* optional */
6852 /* we can also destroy set_vars_and_save_old's return value,
6853 * to save memory */
6854#else
6855 nommu_save->new_env = new_env;
6856 nommu_save->old_vars = set_vars_and_save_old(new_env);
6857#endif
6858
6859 if (argv_expanded) {
6860 argv = argv_expanded;
6861 } else {
6862 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6863#if !BB_MMU
6864 nommu_save->argv = argv;
6865#endif
6866 }
6867 dump_cmd_in_x_mode(argv);
6868
6869#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6870 if (strchr(argv[0], '/') != NULL)
6871 goto skip;
6872#endif
6873
6874 /* Check if the command matches any of the builtins.
6875 * Depending on context, this might be redundant. But it's
6876 * easier to waste a few CPU cycles than it is to figure out
6877 * if this is one of those cases.
6878 */
6879 {
6880 /* On NOMMU, it is more expensive to re-execute shell
6881 * just in order to run echo or test builtin.
6882 * It's better to skip it here and run corresponding
6883 * non-builtin later. */
6884 const struct built_in_command *x;
6885 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6886 if (x) {
6887 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6888 }
6889 }
6890#if ENABLE_HUSH_FUNCTIONS
6891 /* Check if the command matches any functions */
6892 {
6893 const struct function *funcp = find_function(argv[0]);
6894 if (funcp) {
6895 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6896 }
6897 }
6898#endif
6899
6900#if ENABLE_FEATURE_SH_STANDALONE
6901 /* Check if the command matches any busybox applets */
6902 {
6903 int a = find_applet_by_name(argv[0]);
6904 if (a >= 0) {
6905# if BB_MMU /* see above why on NOMMU it is not allowed */
6906 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006907 /* Do not leak open fds from opened script files etc */
6908 close_all_FILE_list();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006909 debug_printf_exec("running applet '%s'\n", argv[0]);
6910 run_applet_no_and_exit(a, argv);
6911 }
6912# endif
6913 /* Re-exec ourselves */
6914 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006915 /* Don't propagate SIG_IGN to the child */
6916 if (SPECIAL_JOBSTOP_SIGS != 0)
6917 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006918 execv(bb_busybox_exec_path, argv);
6919 /* If they called chroot or otherwise made the binary no longer
6920 * executable, fall through */
6921 }
6922 }
6923#endif
6924
6925#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6926 skip:
6927#endif
6928 execvp_or_die(argv);
6929}
6930
6931/* Called after [v]fork() in run_pipe
6932 */
6933static void pseudo_exec(nommu_save_t *nommu_save,
6934 struct command *command,
6935 char **argv_expanded) NORETURN;
6936static void pseudo_exec(nommu_save_t *nommu_save,
6937 struct command *command,
6938 char **argv_expanded)
6939{
6940 if (command->argv) {
6941 pseudo_exec_argv(nommu_save, command->argv,
6942 command->assignment_cnt, argv_expanded);
6943 }
6944
6945 if (command->group) {
6946 /* Cases when we are here:
6947 * ( list )
6948 * { list } &
6949 * ... | ( list ) | ...
6950 * ... | { list } | ...
6951 */
6952#if BB_MMU
6953 int rcode;
6954 debug_printf_exec("pseudo_exec: run_list\n");
6955 reset_traps_to_defaults();
6956 rcode = run_list(command->group);
6957 /* OK to leak memory by not calling free_pipe_list,
6958 * since this process is about to exit */
6959 _exit(rcode);
6960#else
6961 re_execute_shell(&nommu_save->argv_from_re_execing,
6962 command->group_as_string,
6963 G.global_argv[0],
6964 G.global_argv + 1,
6965 NULL);
6966#endif
6967 }
6968
6969 /* Case when we are here: ... | >file */
6970 debug_printf_exec("pseudo_exec'ed null command\n");
6971 _exit(EXIT_SUCCESS);
6972}
6973
6974#if ENABLE_HUSH_JOB
6975static const char *get_cmdtext(struct pipe *pi)
6976{
6977 char **argv;
6978 char *p;
6979 int len;
6980
6981 /* This is subtle. ->cmdtext is created only on first backgrounding.
6982 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6983 * On subsequent bg argv is trashed, but we won't use it */
6984 if (pi->cmdtext)
6985 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01006986
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006987 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01006988 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006989 pi->cmdtext = xzalloc(1);
6990 return pi->cmdtext;
6991 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006992 len = 0;
6993 do {
6994 len += strlen(*argv) + 1;
6995 } while (*++argv);
6996 p = xmalloc(len);
6997 pi->cmdtext = p;
6998 argv = pi->cmds[0].argv;
6999 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007000 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007001 *p++ = ' ';
7002 } while (*++argv);
7003 p[-1] = '\0';
7004 return pi->cmdtext;
7005}
7006
7007static void insert_bg_job(struct pipe *pi)
7008{
7009 struct pipe *job, **jobp;
7010 int i;
7011
7012 /* Linear search for the ID of the job to use */
7013 pi->jobid = 1;
7014 for (job = G.job_list; job; job = job->next)
7015 if (job->jobid >= pi->jobid)
7016 pi->jobid = job->jobid + 1;
7017
7018 /* Add job to the list of running jobs */
7019 jobp = &G.job_list;
7020 while ((job = *jobp) != NULL)
7021 jobp = &job->next;
7022 job = *jobp = xmalloc(sizeof(*job));
7023
7024 *job = *pi; /* physical copy */
7025 job->next = NULL;
7026 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7027 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7028 for (i = 0; i < pi->num_cmds; i++) {
7029 job->cmds[i].pid = pi->cmds[i].pid;
7030 /* all other fields are not used and stay zero */
7031 }
7032 job->cmdtext = xstrdup(get_cmdtext(pi));
7033
7034 if (G_interactive_fd)
7035 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
7036 G.last_jobid = job->jobid;
7037}
7038
7039static void remove_bg_job(struct pipe *pi)
7040{
7041 struct pipe *prev_pipe;
7042
7043 if (pi == G.job_list) {
7044 G.job_list = pi->next;
7045 } else {
7046 prev_pipe = G.job_list;
7047 while (prev_pipe->next != pi)
7048 prev_pipe = prev_pipe->next;
7049 prev_pipe->next = pi->next;
7050 }
7051 if (G.job_list)
7052 G.last_jobid = G.job_list->jobid;
7053 else
7054 G.last_jobid = 0;
7055}
7056
7057/* Remove a backgrounded job */
7058static void delete_finished_bg_job(struct pipe *pi)
7059{
7060 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007061 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007062}
7063#endif /* JOB */
7064
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007065static int job_exited_or_stopped(struct pipe *pi)
7066{
7067 int rcode, i;
7068
7069 if (pi->alive_cmds != pi->stopped_cmds)
7070 return -1;
7071
7072 /* All processes in fg pipe have exited or stopped */
7073 rcode = 0;
7074 i = pi->num_cmds;
7075 while (--i >= 0) {
7076 rcode = pi->cmds[i].cmd_exitcode;
7077 /* usually last process gives overall exitstatus,
7078 * but with "set -o pipefail", last *failed* process does */
7079 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7080 break;
7081 }
7082 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7083 return rcode;
7084}
7085
Denys Vlasenko7e675362016-10-28 21:57:31 +02007086static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007087{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007088#if ENABLE_HUSH_JOB
7089 struct pipe *pi;
7090#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007091 int i, dead;
7092
7093 dead = WIFEXITED(status) || WIFSIGNALED(status);
7094
7095#if DEBUG_JOBS
7096 if (WIFSTOPPED(status))
7097 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7098 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7099 if (WIFSIGNALED(status))
7100 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7101 childpid, WTERMSIG(status), WEXITSTATUS(status));
7102 if (WIFEXITED(status))
7103 debug_printf_jobs("pid %d exited, exitcode %d\n",
7104 childpid, WEXITSTATUS(status));
7105#endif
7106 /* Were we asked to wait for a fg pipe? */
7107 if (fg_pipe) {
7108 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007109
Denys Vlasenko7e675362016-10-28 21:57:31 +02007110 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007111 int rcode;
7112
Denys Vlasenko7e675362016-10-28 21:57:31 +02007113 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7114 if (fg_pipe->cmds[i].pid != childpid)
7115 continue;
7116 if (dead) {
7117 int ex;
7118 fg_pipe->cmds[i].pid = 0;
7119 fg_pipe->alive_cmds--;
7120 ex = WEXITSTATUS(status);
7121 /* bash prints killer signal's name for *last*
7122 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7123 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7124 */
7125 if (WIFSIGNALED(status)) {
7126 int sig = WTERMSIG(status);
7127 if (i == fg_pipe->num_cmds-1)
7128 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7129 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7130 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7131 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7132 * Maybe we need to use sig | 128? */
7133 ex = sig + 128;
7134 }
7135 fg_pipe->cmds[i].cmd_exitcode = ex;
7136 } else {
7137 fg_pipe->stopped_cmds++;
7138 }
7139 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7140 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007141 rcode = job_exited_or_stopped(fg_pipe);
7142 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007143/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7144 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7145 * and "killall -STOP cat" */
7146 if (G_interactive_fd) {
7147#if ENABLE_HUSH_JOB
7148 if (fg_pipe->alive_cmds != 0)
7149 insert_bg_job(fg_pipe);
7150#endif
7151 return rcode;
7152 }
7153 if (fg_pipe->alive_cmds == 0)
7154 return rcode;
7155 }
7156 /* There are still running processes in the fg_pipe */
7157 return -1;
7158 }
7159 /* It wasnt in fg_pipe, look for process in bg pipes */
7160 }
7161
7162#if ENABLE_HUSH_JOB
7163 /* We were asked to wait for bg or orphaned children */
7164 /* No need to remember exitcode in this case */
7165 for (pi = G.job_list; pi; pi = pi->next) {
7166 for (i = 0; i < pi->num_cmds; i++) {
7167 if (pi->cmds[i].pid == childpid)
7168 goto found_pi_and_prognum;
7169 }
7170 }
7171 /* Happens when shell is used as init process (init=/bin/sh) */
7172 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7173 return -1; /* this wasn't a process from fg_pipe */
7174
7175 found_pi_and_prognum:
7176 if (dead) {
7177 /* child exited */
7178 pi->cmds[i].pid = 0;
7179 pi->cmds[i].cmd_exitcode = WEXITSTATUS(status);
7180 if (WIFSIGNALED(status))
7181 pi->cmds[i].cmd_exitcode = 128 + WTERMSIG(status);
7182 pi->alive_cmds--;
7183 if (!pi->alive_cmds) {
7184 if (G_interactive_fd)
7185 printf(JOB_STATUS_FORMAT, pi->jobid,
7186 "Done", pi->cmdtext);
7187 delete_finished_bg_job(pi);
7188 }
7189 } else {
7190 /* child stopped */
7191 pi->stopped_cmds++;
7192 }
7193#endif
7194 return -1; /* this wasn't a process from fg_pipe */
7195}
7196
7197/* Check to see if any processes have exited -- if they have,
7198 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007199 *
7200 * If non-NULL fg_pipe: wait for its completion or stop.
7201 * Return its exitcode or zero if stopped.
7202 *
7203 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7204 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7205 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7206 * or 0 if no children changed status.
7207 *
7208 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7209 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7210 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02007211 */
7212static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7213{
7214 int attributes;
7215 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007216 int rcode = 0;
7217
7218 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7219
7220 attributes = WUNTRACED;
7221 if (fg_pipe == NULL)
7222 attributes |= WNOHANG;
7223
7224 errno = 0;
7225#if ENABLE_HUSH_FAST
7226 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7227//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7228//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7229 /* There was neither fork nor SIGCHLD since last waitpid */
7230 /* Avoid doing waitpid syscall if possible */
7231 if (!G.we_have_children) {
7232 errno = ECHILD;
7233 return -1;
7234 }
7235 if (fg_pipe == NULL) { /* is WNOHANG set? */
7236 /* We have children, but they did not exit
7237 * or stop yet (we saw no SIGCHLD) */
7238 return 0;
7239 }
7240 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7241 }
7242#endif
7243
7244/* Do we do this right?
7245 * bash-3.00# sleep 20 | false
7246 * <ctrl-Z pressed>
7247 * [3]+ Stopped sleep 20 | false
7248 * bash-3.00# echo $?
7249 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7250 * [hush 1.14.0: yes we do it right]
7251 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007252 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007253 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007254#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02007255 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007256 i = G.count_SIGCHLD;
7257#endif
7258 childpid = waitpid(-1, &status, attributes);
7259 if (childpid <= 0) {
7260 if (childpid && errno != ECHILD)
7261 bb_perror_msg("waitpid");
7262#if ENABLE_HUSH_FAST
7263 else { /* Until next SIGCHLD, waitpid's are useless */
7264 G.we_have_children = (childpid == 0);
7265 G.handled_SIGCHLD = i;
7266//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7267 }
7268#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007269 /* ECHILD (no children), or 0 (no change in children status) */
7270 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007271 break;
7272 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007273 rcode = process_wait_result(fg_pipe, childpid, status);
7274 if (rcode >= 0) {
7275 /* fg_pipe exited or stopped */
7276 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007277 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007278 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007279 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007280 rcode = WEXITSTATUS(status);
7281 if (WIFSIGNALED(status))
7282 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007283 if (WIFSTOPPED(status))
7284 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7285 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007286 rcode++;
7287 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007288 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007289 /* This wasn't one of our processes, or */
7290 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007291 } /* while (waitpid succeeds)... */
7292
7293 return rcode;
7294}
7295
7296#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007297static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007298{
7299 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007300 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007301 if (G_saved_tty_pgrp) {
7302 /* Job finished, move the shell to the foreground */
7303 p = getpgrp(); /* our process group id */
7304 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7305 tcsetpgrp(G_interactive_fd, p);
7306 }
7307 return rcode;
7308}
7309#endif
7310
7311/* Start all the jobs, but don't wait for anything to finish.
7312 * See checkjobs().
7313 *
7314 * Return code is normally -1, when the caller has to wait for children
7315 * to finish to determine the exit status of the pipe. If the pipe
7316 * is a simple builtin command, however, the action is done by the
7317 * time run_pipe returns, and the exit code is provided as the
7318 * return value.
7319 *
7320 * Returns -1 only if started some children. IOW: we have to
7321 * mask out retvals of builtins etc with 0xff!
7322 *
7323 * The only case when we do not need to [v]fork is when the pipe
7324 * is single, non-backgrounded, non-subshell command. Examples:
7325 * cmd ; ... { list } ; ...
7326 * cmd && ... { list } && ...
7327 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007328 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007329 * or (if SH_STANDALONE) an applet, and we can run the { list }
7330 * with run_list. If it isn't one of these, we fork and exec cmd.
7331 *
7332 * Cases when we must fork:
7333 * non-single: cmd | cmd
7334 * backgrounded: cmd & { list } &
7335 * subshell: ( list ) [&]
7336 */
7337#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01007338#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007339 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7340#endif
7341static int redirect_and_varexp_helper(char ***new_env_p,
7342 struct variable **old_vars_p,
7343 struct command *command,
7344 int squirrel[3],
7345 char **argv_expanded)
7346{
7347 /* setup_redirects acts on file descriptors, not FILEs.
7348 * This is perfect for work that comes after exec().
7349 * Is it really safe for inline use? Experimentally,
7350 * things seem to work. */
7351 int rcode = setup_redirects(command, squirrel);
7352 if (rcode == 0) {
7353 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7354 *new_env_p = new_env;
7355 dump_cmd_in_x_mode(new_env);
7356 dump_cmd_in_x_mode(argv_expanded);
7357 if (old_vars_p)
7358 *old_vars_p = set_vars_and_save_old(new_env);
7359 }
7360 return rcode;
7361}
7362static NOINLINE int run_pipe(struct pipe *pi)
7363{
7364 static const char *const null_ptr = NULL;
7365
7366 int cmd_no;
7367 int next_infd;
7368 struct command *command;
7369 char **argv_expanded;
7370 char **argv;
7371 /* it is not always needed, but we aim to smaller code */
7372 int squirrel[] = { -1, -1, -1 };
7373 int rcode;
7374
7375 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7376 debug_enter();
7377
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007378 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7379 * Result should be 3 lines: q w e, qwe, q w e
7380 */
7381 G.ifs = get_local_var_value("IFS");
7382 if (!G.ifs)
7383 G.ifs = defifs;
7384
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007385 IF_HUSH_JOB(pi->pgrp = -1;)
7386 pi->stopped_cmds = 0;
7387 command = &pi->cmds[0];
7388 argv_expanded = NULL;
7389
7390 if (pi->num_cmds != 1
7391 || pi->followup == PIPE_BG
7392 || command->cmd_type == CMD_SUBSHELL
7393 ) {
7394 goto must_fork;
7395 }
7396
7397 pi->alive_cmds = 1;
7398
7399 debug_printf_exec(": group:%p argv:'%s'\n",
7400 command->group, command->argv ? command->argv[0] : "NONE");
7401
7402 if (command->group) {
7403#if ENABLE_HUSH_FUNCTIONS
7404 if (command->cmd_type == CMD_FUNCDEF) {
7405 /* "executing" func () { list } */
7406 struct function *funcp;
7407
7408 funcp = new_function(command->argv[0]);
7409 /* funcp->name is already set to argv[0] */
7410 funcp->body = command->group;
7411# if !BB_MMU
7412 funcp->body_as_string = command->group_as_string;
7413 command->group_as_string = NULL;
7414# endif
7415 command->group = NULL;
7416 command->argv[0] = NULL;
7417 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7418 funcp->parent_cmd = command;
7419 command->child_func = funcp;
7420
7421 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7422 debug_leave();
7423 return EXIT_SUCCESS;
7424 }
7425#endif
7426 /* { list } */
7427 debug_printf("non-subshell group\n");
7428 rcode = 1; /* exitcode if redir failed */
7429 if (setup_redirects(command, squirrel) == 0) {
7430 debug_printf_exec(": run_list\n");
7431 rcode = run_list(command->group) & 0xff;
7432 }
7433 restore_redirects(squirrel);
7434 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7435 debug_leave();
7436 debug_printf_exec("run_pipe: return %d\n", rcode);
7437 return rcode;
7438 }
7439
7440 argv = command->argv ? command->argv : (char **) &null_ptr;
7441 {
7442 const struct built_in_command *x;
7443#if ENABLE_HUSH_FUNCTIONS
7444 const struct function *funcp;
7445#else
7446 enum { funcp = 0 };
7447#endif
7448 char **new_env = NULL;
7449 struct variable *old_vars = NULL;
7450
7451 if (argv[command->assignment_cnt] == NULL) {
7452 /* Assignments, but no command */
7453 /* Ensure redirects take effect (that is, create files).
7454 * Try "a=t >file" */
7455#if 0 /* A few cases in testsuite fail with this code. FIXME */
7456 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7457 /* Set shell variables */
7458 if (new_env) {
7459 argv = new_env;
7460 while (*argv) {
7461 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7462 /* Do we need to flag set_local_var() errors?
7463 * "assignment to readonly var" and "putenv error"
7464 */
7465 argv++;
7466 }
7467 }
7468 /* Redirect error sets $? to 1. Otherwise,
7469 * if evaluating assignment value set $?, retain it.
7470 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7471 if (rcode == 0)
7472 rcode = G.last_exitcode;
7473 /* Exit, _skipping_ variable restoring code: */
7474 goto clean_up_and_ret0;
7475
7476#else /* Older, bigger, but more correct code */
7477
7478 rcode = setup_redirects(command, squirrel);
7479 restore_redirects(squirrel);
7480 /* Set shell variables */
7481 if (G_x_mode)
7482 bb_putchar_stderr('+');
7483 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007484 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007485 if (G_x_mode)
7486 fprintf(stderr, " %s", p);
7487 debug_printf_exec("set shell var:'%s'->'%s'\n",
7488 *argv, p);
7489 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7490 /* Do we need to flag set_local_var() errors?
7491 * "assignment to readonly var" and "putenv error"
7492 */
7493 argv++;
7494 }
7495 if (G_x_mode)
7496 bb_putchar_stderr('\n');
7497 /* Redirect error sets $? to 1. Otherwise,
7498 * if evaluating assignment value set $?, retain it.
7499 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7500 if (rcode == 0)
7501 rcode = G.last_exitcode;
7502 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7503 debug_leave();
7504 debug_printf_exec("run_pipe: return %d\n", rcode);
7505 return rcode;
7506#endif
7507 }
7508
7509 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007510#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007511 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007512 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007513 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007514#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007515 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007516 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7517 }
7518
7519 /* if someone gives us an empty string: `cmd with empty output` */
7520 if (!argv_expanded[0]) {
7521 free(argv_expanded);
7522 debug_leave();
7523 return G.last_exitcode;
7524 }
7525
7526 x = find_builtin(argv_expanded[0]);
7527#if ENABLE_HUSH_FUNCTIONS
7528 funcp = NULL;
7529 if (!x)
7530 funcp = find_function(argv_expanded[0]);
7531#endif
7532 if (x || funcp) {
7533 if (!funcp) {
7534 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7535 debug_printf("exec with redirects only\n");
7536 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007537 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007538 goto clean_up_and_ret1;
7539 }
7540 }
7541 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7542 if (rcode == 0) {
7543 if (!funcp) {
7544 debug_printf_exec(": builtin '%s' '%s'...\n",
7545 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007546 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007547 rcode = x->b_function(argv_expanded) & 0xff;
7548 fflush_all();
7549 }
7550#if ENABLE_HUSH_FUNCTIONS
7551 else {
7552# if ENABLE_HUSH_LOCAL
7553 struct variable **sv;
7554 sv = G.shadowed_vars_pp;
7555 G.shadowed_vars_pp = &old_vars;
7556# endif
7557 debug_printf_exec(": function '%s' '%s'...\n",
7558 funcp->name, argv_expanded[1]);
7559 rcode = run_function(funcp, argv_expanded) & 0xff;
7560# if ENABLE_HUSH_LOCAL
7561 G.shadowed_vars_pp = sv;
7562# endif
7563 }
7564#endif
7565 }
7566 clean_up_and_ret:
7567 unset_vars(new_env);
7568 add_vars(old_vars);
7569/* clean_up_and_ret0: */
7570 restore_redirects(squirrel);
7571 clean_up_and_ret1:
7572 free(argv_expanded);
7573 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7574 debug_leave();
7575 debug_printf_exec("run_pipe return %d\n", rcode);
7576 return rcode;
7577 }
7578
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007579 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007580 int n = find_applet_by_name(argv_expanded[0]);
7581 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7582 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7583 if (rcode == 0) {
7584 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7585 argv_expanded[0], argv_expanded[1]);
7586 rcode = run_nofork_applet(n, argv_expanded);
7587 }
7588 goto clean_up_and_ret;
7589 }
7590 }
7591 /* It is neither builtin nor applet. We must fork. */
7592 }
7593
7594 must_fork:
7595 /* NB: argv_expanded may already be created, and that
7596 * might include `cmd` runs! Do not rerun it! We *must*
7597 * use argv_expanded if it's non-NULL */
7598
7599 /* Going to fork a child per each pipe member */
7600 pi->alive_cmds = 0;
7601 next_infd = 0;
7602
7603 cmd_no = 0;
7604 while (cmd_no < pi->num_cmds) {
7605 struct fd_pair pipefds;
7606#if !BB_MMU
7607 volatile nommu_save_t nommu_save;
7608 nommu_save.new_env = NULL;
7609 nommu_save.old_vars = NULL;
7610 nommu_save.argv = NULL;
7611 nommu_save.argv_from_re_execing = NULL;
7612#endif
7613 command = &pi->cmds[cmd_no];
7614 cmd_no++;
7615 if (command->argv) {
7616 debug_printf_exec(": pipe member '%s' '%s'...\n",
7617 command->argv[0], command->argv[1]);
7618 } else {
7619 debug_printf_exec(": pipe member with no argv\n");
7620 }
7621
7622 /* pipes are inserted between pairs of commands */
7623 pipefds.rd = 0;
7624 pipefds.wr = 1;
7625 if (cmd_no < pi->num_cmds)
7626 xpiped_pair(pipefds);
7627
7628 command->pid = BB_MMU ? fork() : vfork();
7629 if (!command->pid) { /* child */
7630#if ENABLE_HUSH_JOB
7631 disable_restore_tty_pgrp_on_exit();
7632 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7633
7634 /* Every child adds itself to new process group
7635 * with pgid == pid_of_first_child_in_pipe */
7636 if (G.run_list_level == 1 && G_interactive_fd) {
7637 pid_t pgrp;
7638 pgrp = pi->pgrp;
7639 if (pgrp < 0) /* true for 1st process only */
7640 pgrp = getpid();
7641 if (setpgid(0, pgrp) == 0
7642 && pi->followup != PIPE_BG
7643 && G_saved_tty_pgrp /* we have ctty */
7644 ) {
7645 /* We do it in *every* child, not just first,
7646 * to avoid races */
7647 tcsetpgrp(G_interactive_fd, pgrp);
7648 }
7649 }
7650#endif
7651 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7652 /* 1st cmd in backgrounded pipe
7653 * should have its stdin /dev/null'ed */
7654 close(0);
7655 if (open(bb_dev_null, O_RDONLY))
7656 xopen("/", O_RDONLY);
7657 } else {
7658 xmove_fd(next_infd, 0);
7659 }
7660 xmove_fd(pipefds.wr, 1);
7661 if (pipefds.rd > 1)
7662 close(pipefds.rd);
7663 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02007664 * and the pipe fd (fd#1) is available for dup'ing:
7665 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7666 * of cmd1 goes into pipe.
7667 */
7668 if (setup_redirects(command, NULL)) {
7669 /* Happens when redir file can't be opened:
7670 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7671 * FOO
7672 * hush: can't open '/qwe/rty': No such file or directory
7673 * BAZ
7674 * (echo BAR is not executed, it hits _exit(1) below)
7675 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007676 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007677 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007678
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007679 /* Stores to nommu_save list of env vars putenv'ed
7680 * (NOMMU, on MMU we don't need that) */
7681 /* cast away volatility... */
7682 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7683 /* pseudo_exec() does not return */
7684 }
7685
7686 /* parent or error */
7687#if ENABLE_HUSH_FAST
7688 G.count_SIGCHLD++;
7689//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7690#endif
7691 enable_restore_tty_pgrp_on_exit();
7692#if !BB_MMU
7693 /* Clean up after vforked child */
7694 free(nommu_save.argv);
7695 free(nommu_save.argv_from_re_execing);
7696 unset_vars(nommu_save.new_env);
7697 add_vars(nommu_save.old_vars);
7698#endif
7699 free(argv_expanded);
7700 argv_expanded = NULL;
7701 if (command->pid < 0) { /* [v]fork failed */
7702 /* Clearly indicate, was it fork or vfork */
7703 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7704 } else {
7705 pi->alive_cmds++;
7706#if ENABLE_HUSH_JOB
7707 /* Second and next children need to know pid of first one */
7708 if (pi->pgrp < 0)
7709 pi->pgrp = command->pid;
7710#endif
7711 }
7712
7713 if (cmd_no > 1)
7714 close(next_infd);
7715 if (cmd_no < pi->num_cmds)
7716 close(pipefds.wr);
7717 /* Pass read (output) pipe end to next iteration */
7718 next_infd = pipefds.rd;
7719 }
7720
7721 if (!pi->alive_cmds) {
7722 debug_leave();
7723 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7724 return 1;
7725 }
7726
7727 debug_leave();
7728 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7729 return -1;
7730}
7731
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007732/* NB: called by pseudo_exec, and therefore must not modify any
7733 * global data until exec/_exit (we can be a child after vfork!) */
7734static int run_list(struct pipe *pi)
7735{
7736#if ENABLE_HUSH_CASE
7737 char *case_word = NULL;
7738#endif
7739#if ENABLE_HUSH_LOOPS
7740 struct pipe *loop_top = NULL;
7741 char **for_lcur = NULL;
7742 char **for_list = NULL;
7743#endif
7744 smallint last_followup;
7745 smalluint rcode;
7746#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7747 smalluint cond_code = 0;
7748#else
7749 enum { cond_code = 0 };
7750#endif
7751#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007752 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007753 smallint last_rword; /* ditto */
7754#endif
7755
7756 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7757 debug_enter();
7758
7759#if ENABLE_HUSH_LOOPS
7760 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007761 {
7762 struct pipe *cpipe;
7763 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7764 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7765 continue;
7766 /* current word is FOR or IN (BOLD in comments below) */
7767 if (cpipe->next == NULL) {
7768 syntax_error("malformed for");
7769 debug_leave();
7770 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7771 return 1;
7772 }
7773 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7774 if (cpipe->next->res_word == RES_DO)
7775 continue;
7776 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7777 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7778 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7779 ) {
7780 syntax_error("malformed for");
7781 debug_leave();
7782 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7783 return 1;
7784 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007785 }
7786 }
7787#endif
7788
7789 /* Past this point, all code paths should jump to ret: label
7790 * in order to return, no direct "return" statements please.
7791 * This helps to ensure that no memory is leaked. */
7792
7793#if ENABLE_HUSH_JOB
7794 G.run_list_level++;
7795#endif
7796
7797#if HAS_KEYWORDS
7798 rword = RES_NONE;
7799 last_rword = RES_XXXX;
7800#endif
7801 last_followup = PIPE_SEQ;
7802 rcode = G.last_exitcode;
7803
7804 /* Go through list of pipes, (maybe) executing them. */
7805 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007806 int r;
7807
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007808 if (G.flag_SIGINT)
7809 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007810 if (G_flag_return_in_progress == 1)
7811 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007812
7813 IF_HAS_KEYWORDS(rword = pi->res_word;)
7814 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7815 rword, cond_code, last_rword);
7816#if ENABLE_HUSH_LOOPS
7817 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7818 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7819 ) {
7820 /* start of a loop: remember where loop starts */
7821 loop_top = pi;
7822 G.depth_of_loop++;
7823 }
7824#endif
7825 /* Still in the same "if...", "then..." or "do..." branch? */
7826 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7827 if ((rcode == 0 && last_followup == PIPE_OR)
7828 || (rcode != 0 && last_followup == PIPE_AND)
7829 ) {
7830 /* It is "<true> || CMD" or "<false> && CMD"
7831 * and we should not execute CMD */
7832 debug_printf_exec("skipped cmd because of || or &&\n");
7833 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02007834 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007835 }
7836 }
7837 last_followup = pi->followup;
7838 IF_HAS_KEYWORDS(last_rword = rword;)
7839#if ENABLE_HUSH_IF
7840 if (cond_code) {
7841 if (rword == RES_THEN) {
7842 /* if false; then ... fi has exitcode 0! */
7843 G.last_exitcode = rcode = EXIT_SUCCESS;
7844 /* "if <false> THEN cmd": skip cmd */
7845 continue;
7846 }
7847 } else {
7848 if (rword == RES_ELSE || rword == RES_ELIF) {
7849 /* "if <true> then ... ELSE/ELIF cmd":
7850 * skip cmd and all following ones */
7851 break;
7852 }
7853 }
7854#endif
7855#if ENABLE_HUSH_LOOPS
7856 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7857 if (!for_lcur) {
7858 /* first loop through for */
7859
7860 static const char encoded_dollar_at[] ALIGN1 = {
7861 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7862 }; /* encoded representation of "$@" */
7863 static const char *const encoded_dollar_at_argv[] = {
7864 encoded_dollar_at, NULL
7865 }; /* argv list with one element: "$@" */
7866 char **vals;
7867
7868 vals = (char**)encoded_dollar_at_argv;
7869 if (pi->next->res_word == RES_IN) {
7870 /* if no variable values after "in" we skip "for" */
7871 if (!pi->next->cmds[0].argv) {
7872 G.last_exitcode = rcode = EXIT_SUCCESS;
7873 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7874 break;
7875 }
7876 vals = pi->next->cmds[0].argv;
7877 } /* else: "for var; do..." -> assume "$@" list */
7878 /* create list of variable values */
7879 debug_print_strings("for_list made from", vals);
7880 for_list = expand_strvec_to_strvec(vals);
7881 for_lcur = for_list;
7882 debug_print_strings("for_list", for_list);
7883 }
7884 if (!*for_lcur) {
7885 /* "for" loop is over, clean up */
7886 free(for_list);
7887 for_list = NULL;
7888 for_lcur = NULL;
7889 break;
7890 }
7891 /* Insert next value from for_lcur */
7892 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7893 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7894 continue;
7895 }
7896 if (rword == RES_IN) {
7897 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7898 }
7899 if (rword == RES_DONE) {
7900 continue; /* "done" has no cmds too */
7901 }
7902#endif
7903#if ENABLE_HUSH_CASE
7904 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007905 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007906 case_word = expand_strvec_to_string(pi->cmds->argv);
7907 continue;
7908 }
7909 if (rword == RES_MATCH) {
7910 char **argv;
7911
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007912 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007913 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7914 break;
7915 /* all prev words didn't match, does this one match? */
7916 argv = pi->cmds->argv;
7917 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007918 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007919 /* TODO: which FNM_xxx flags to use? */
7920 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7921 free(pattern);
7922 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007923 free(case_word);
7924 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007925 break;
7926 }
7927 argv++;
7928 }
7929 continue;
7930 }
7931 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007932 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007933 if (cond_code != 0)
7934 continue; /* not matched yet, skip this pipe */
7935 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01007936 if (rword == RES_ESAC) {
7937 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
7938 if (case_word) {
7939 /* "case" did not match anything: still set $? (to 0) */
7940 G.last_exitcode = rcode = EXIT_SUCCESS;
7941 }
7942 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007943#endif
7944 /* Just pressing <enter> in shell should check for jobs.
7945 * OTOH, in non-interactive shell this is useless
7946 * and only leads to extra job checks */
7947 if (pi->num_cmds == 0) {
7948 if (G_interactive_fd)
7949 goto check_jobs_and_continue;
7950 continue;
7951 }
7952
7953 /* After analyzing all keywords and conditions, we decided
7954 * to execute this pipe. NB: have to do checkjobs(NULL)
7955 * after run_pipe to collect any background children,
7956 * even if list execution is to be stopped. */
7957 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007958#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007959 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007960#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007961 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
7962 if (r != -1) {
7963 /* We ran a builtin, function, or group.
7964 * rcode is already known
7965 * and we don't need to wait for anything. */
7966 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7967 G.last_exitcode = rcode;
7968 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007969#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007970 /* Was it "break" or "continue"? */
7971 if (G.flag_break_continue) {
7972 smallint fbc = G.flag_break_continue;
7973 /* We might fall into outer *loop*,
7974 * don't want to break it too */
7975 if (loop_top) {
7976 G.depth_break_continue--;
7977 if (G.depth_break_continue == 0)
7978 G.flag_break_continue = 0;
7979 /* else: e.g. "continue 2" should *break* once, *then* continue */
7980 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7981 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007982 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007983 break;
7984 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007985 /* "continue": simulate end of loop */
7986 rword = RES_DONE;
7987 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007988 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007989#endif
7990 if (G_flag_return_in_progress == 1) {
7991 checkjobs(NULL, 0 /*(no pid to wait for)*/);
7992 break;
7993 }
7994 } else if (pi->followup == PIPE_BG) {
7995 /* What does bash do with attempts to background builtins? */
7996 /* even bash 3.2 doesn't do that well with nested bg:
7997 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7998 * I'm NOT treating inner &'s as jobs */
7999#if ENABLE_HUSH_JOB
8000 if (G.run_list_level == 1)
8001 insert_bg_job(pi);
8002#endif
8003 /* Last command's pid goes to $! */
8004 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8005 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8006/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash says 0 */
8007 G.last_exitcode = rcode = EXIT_SUCCESS;
8008 check_and_run_traps();
8009 } else {
8010#if ENABLE_HUSH_JOB
8011 if (G.run_list_level == 1 && G_interactive_fd) {
8012 /* Waits for completion, then fg's main shell */
8013 rcode = checkjobs_and_fg_shell(pi);
8014 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
8015 } else
8016#endif
8017 { /* This one just waits for completion */
8018 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8019 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8020 }
8021 G.last_exitcode = rcode;
8022 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008023 }
8024
8025 /* Analyze how result affects subsequent commands */
8026#if ENABLE_HUSH_IF
8027 if (rword == RES_IF || rword == RES_ELIF)
8028 cond_code = rcode;
8029#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008030 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008031 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008032 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008033#if ENABLE_HUSH_LOOPS
8034 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008035 if (pi->next
8036 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008037 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008038 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008039 if (rword == RES_WHILE) {
8040 if (rcode) {
8041 /* "while false; do...done" - exitcode 0 */
8042 G.last_exitcode = rcode = EXIT_SUCCESS;
8043 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008044 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008045 }
8046 }
8047 if (rword == RES_UNTIL) {
8048 if (!rcode) {
8049 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008050 break;
8051 }
8052 }
8053 }
8054#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008055 } /* for (pi) */
8056
8057#if ENABLE_HUSH_JOB
8058 G.run_list_level--;
8059#endif
8060#if ENABLE_HUSH_LOOPS
8061 if (loop_top)
8062 G.depth_of_loop--;
8063 free(for_list);
8064#endif
8065#if ENABLE_HUSH_CASE
8066 free(case_word);
8067#endif
8068 debug_leave();
8069 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8070 return rcode;
8071}
8072
8073/* Select which version we will use */
8074static int run_and_free_list(struct pipe *pi)
8075{
8076 int rcode = 0;
8077 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08008078 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008079 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8080 rcode = run_list(pi);
8081 }
8082 /* free_pipe_list has the side effect of clearing memory.
8083 * In the long run that function can be merged with run_list,
8084 * but doing that now would hobble the debugging effort. */
8085 free_pipe_list(pi);
8086 debug_printf_exec("run_and_free_list return %d\n", rcode);
8087 return rcode;
8088}
8089
8090
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008091static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00008092{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008093 sighandler_t old_handler;
8094 unsigned sig = 0;
8095 while ((mask >>= 1) != 0) {
8096 sig++;
8097 if (!(mask & 1))
8098 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02008099 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008100 /* POSIX allows shell to re-enable SIGCHLD
8101 * even if it was SIG_IGN on entry.
8102 * Therefore we skip IGN check for it:
8103 */
8104 if (sig == SIGCHLD)
8105 continue;
8106 if (old_handler == SIG_IGN) {
8107 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008108 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008109 if (!G.traps)
8110 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8111 free(G.traps[sig]);
8112 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
8113 }
8114 }
8115}
8116
8117/* Called a few times only (or even once if "sh -c") */
8118static void install_special_sighandlers(void)
8119{
Denis Vlasenkof9375282009-04-05 19:13:39 +00008120 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008121
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008122 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008123 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008124 if (G_interactive_fd) {
8125 mask |= SPECIAL_INTERACTIVE_SIGS;
8126 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008127 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008128 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008129 /* Careful, do not re-install handlers we already installed */
8130 if (G.special_sig_mask != mask) {
8131 unsigned diff = mask & ~G.special_sig_mask;
8132 G.special_sig_mask = mask;
8133 install_sighandlers(diff);
8134 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008135}
8136
8137#if ENABLE_HUSH_JOB
8138/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008139/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008140static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00008141{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008142 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008143
8144 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008145 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01008146 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8147 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008148 + (1 << SIGBUS ) * HUSH_DEBUG
8149 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01008150 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008151 + (1 << SIGABRT)
8152 /* bash 3.2 seems to handle these just like 'fatal' ones */
8153 + (1 << SIGPIPE)
8154 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008155 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008156 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008157 * we never want to restore pgrp on exit, and this fn is not called
8158 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008159 /*+ (1 << SIGHUP )*/
8160 /*+ (1 << SIGTERM)*/
8161 /*+ (1 << SIGINT )*/
8162 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008163 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008164
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008165 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008166}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00008167#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00008168
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008169static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00008170{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008171 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008172 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008173 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08008174 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008175 break;
8176 case 'x':
8177 IF_HUSH_MODE_X(G_x_mode = state;)
8178 break;
8179 case 'o':
8180 if (!o_opt) {
8181 /* "set -+o" without parameter.
8182 * in bash, set -o produces this output:
8183 * pipefail off
8184 * and set +o:
8185 * set +o pipefail
8186 * We always use the second form.
8187 */
8188 const char *p = o_opt_strings;
8189 idx = 0;
8190 while (*p) {
8191 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8192 idx++;
8193 p += strlen(p) + 1;
8194 }
8195 break;
8196 }
8197 idx = index_in_strings(o_opt_strings, o_opt);
8198 if (idx >= 0) {
8199 G.o_opt[idx] = state;
8200 break;
8201 }
8202 default:
8203 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008204 }
8205 return EXIT_SUCCESS;
8206}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008207
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00008208int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00008209int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00008210{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008211 enum {
8212 OPT_login = (1 << 0),
8213 };
8214 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00008215 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008216 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008217 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008218 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008219 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00008220
Denis Vlasenko574f2f42008-02-27 18:41:59 +00008221 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02008222 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008223 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008224
Denys Vlasenko10c01312011-05-11 11:49:21 +02008225#if ENABLE_HUSH_FAST
8226 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8227#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008228#if !BB_MMU
8229 G.argv0_for_re_execing = argv[0];
8230#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008231 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008232 shell_ver = xzalloc(sizeof(*shell_ver));
8233 shell_ver->flg_export = 1;
8234 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02008235 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02008236 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008237 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02008238 /* Create shell local variables from the values
8239 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00008240 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008241 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008242 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008243 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008244 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008245 if (e) while (*e) {
8246 char *value = strchr(*e, '=');
8247 if (value) { /* paranoia */
8248 cur_var->next = xzalloc(sizeof(*cur_var));
8249 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00008250 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008251 cur_var->max_len = strlen(*e);
8252 cur_var->flg_export = 1;
8253 }
8254 e++;
8255 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02008256 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008257 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8258 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02008259
8260 /* Export PWD */
8261 set_pwd_var(/*exp:*/ 1);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008262
8263#if ENABLE_HUSH_BASH_COMPAT
8264 /* Set (but not export) HOSTNAME unless already set */
8265 if (!get_local_var_value("HOSTNAME")) {
8266 struct utsname uts;
8267 uname(&uts);
8268 set_local_var_from_halves("HOSTNAME", uts.nodename);
8269 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008270 /* bash also exports SHLVL and _,
8271 * and sets (but doesn't export) the following variables:
8272 * BASH=/bin/bash
8273 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8274 * BASH_VERSION='3.2.0(1)-release'
8275 * HOSTTYPE=i386
8276 * MACHTYPE=i386-pc-linux-gnu
8277 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02008278 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02008279 * EUID=<NNNNN>
8280 * UID=<NNNNN>
8281 * GROUPS=()
8282 * LINES=<NNN>
8283 * COLUMNS=<NNN>
8284 * BASH_ARGC=()
8285 * BASH_ARGV=()
8286 * BASH_LINENO=()
8287 * BASH_SOURCE=()
8288 * DIRSTACK=()
8289 * PIPESTATUS=([0]="0")
8290 * HISTFILE=/<xxx>/.bash_history
8291 * HISTFILESIZE=500
8292 * HISTSIZE=500
8293 * MAILCHECK=60
8294 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8295 * SHELL=/bin/bash
8296 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8297 * TERM=dumb
8298 * OPTERR=1
8299 * OPTIND=1
8300 * IFS=$' \t\n'
8301 * PS1='\s-\v\$ '
8302 * PS2='> '
8303 * PS4='+ '
8304 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008305#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02008306
Denis Vlasenko38f63192007-01-22 09:03:07 +00008307#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02008308 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008309#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02008310
Eric Andersen94ac2442001-05-22 19:05:18 +00008311 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00008312 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00008313
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008314 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00008315
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008316 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008317 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008318 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008319 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008320 * in order to intercept (more) signals.
8321 */
8322
8323 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008324 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008325 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008326 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008327 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008328 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008329#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00008330 "<:$:R:V:"
8331# if ENABLE_HUSH_FUNCTIONS
8332 "F:"
8333# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008334#endif
8335 );
8336 if (opt <= 0)
8337 break;
Eric Andersen25f27032001-04-26 23:22:31 +00008338 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008339 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008340 /* Possibilities:
8341 * sh ... -c 'script'
8342 * sh ... -c 'script' ARG0 [ARG1...]
8343 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01008344 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008345 * "" needs to be replaced with NULL
8346 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01008347 * Note: the form without ARG0 never happens:
8348 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008349 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02008350 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008351 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008352 G.root_ppid = getppid();
8353 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008354 G.global_argv = argv + optind;
8355 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008356 if (builtin_argc) {
8357 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8358 const struct built_in_command *x;
8359
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008360 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008361 x = find_builtin(optarg);
8362 if (x) { /* paranoia */
8363 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8364 G.global_argv += builtin_argc;
8365 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008366 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01008367 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008368 }
8369 goto final_return;
8370 }
8371 if (!G.global_argv[0]) {
8372 /* -c 'script' (no params): prevent empty $0 */
8373 G.global_argv--; /* points to argv[i] of 'script' */
8374 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02008375 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008376 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008377 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008378 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008379 goto final_return;
8380 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00008381 /* Well, we cannot just declare interactiveness,
8382 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008383 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008384 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008385 case 's':
8386 /* "-s" means "read from stdin", but this is how we always
8387 * operate, so simply do nothing here. */
8388 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008389 case 'l':
8390 flags |= OPT_login;
8391 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008392#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008393 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02008394 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008395 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008396 case '$': {
8397 unsigned long long empty_trap_mask;
8398
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008399 G.root_pid = bb_strtou(optarg, &optarg, 16);
8400 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02008401 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8402 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008403 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8404 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008405 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008406 optarg++;
8407 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008408 optarg++;
8409 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8410 if (empty_trap_mask != 0) {
8411 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008412 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008413 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8414 for (sig = 1; sig < NSIG; sig++) {
8415 if (empty_trap_mask & (1LL << sig)) {
8416 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008417 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008418 }
8419 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008420 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008421# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008422 optarg++;
8423 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008424# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008425 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008426 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008427 case 'R':
8428 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02008429 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008430 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00008431# if ENABLE_HUSH_FUNCTIONS
8432 case 'F': {
8433 struct function *funcp = new_function(optarg);
8434 /* funcp->name is already set to optarg */
8435 /* funcp->body is set to NULL. It's a special case. */
8436 funcp->body_as_string = argv[optind];
8437 optind++;
8438 break;
8439 }
8440# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008441#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008442 case 'n':
8443 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008444 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008445 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008446 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008447#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008448 fprintf(stderr, "Usage: sh [FILE]...\n"
8449 " or: sh -c command [args]...\n\n");
8450 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008451#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008452 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008453#endif
Eric Andersen25f27032001-04-26 23:22:31 +00008454 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008455 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008456
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008457 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8458 G.global_argc = argc - (optind - 1);
8459 G.global_argv = argv + (optind - 1);
8460 G.global_argv[0] = argv[0];
8461
Denys Vlasenkodea47882009-10-09 15:40:49 +02008462 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008463 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008464 G.root_ppid = getppid();
8465 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008466
8467 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008468 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008469 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008470 debug_printf("sourcing /etc/profile\n");
8471 input = fopen_for_read("/etc/profile");
8472 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008473 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008474 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008475 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008476 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008477 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008478 /* bash: after sourcing /etc/profile,
8479 * tries to source (in the given order):
8480 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008481 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008482 * bash also sources ~/.bash_logout on exit.
8483 * If called as sh, skips .bash_XXX files.
8484 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008485 }
8486
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008487 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008488 FILE *input;
8489 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008490 * "bash <script>" (which is never interactive (unless -i?))
8491 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008492 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02008493 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008494 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008495 G.global_argc--;
8496 G.global_argv++;
8497 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02008498 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008499 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02008500 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008501 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008502 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008503 parse_and_run_file(input);
8504#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008505 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008506#endif
8507 goto final_return;
8508 }
8509
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008510 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008511 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008512 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008513
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008514 /* A shell is interactive if the '-i' flag was given,
8515 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008516 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008517 * no arguments remaining or the -s flag given
8518 * standard input is a terminal
8519 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008520 * Refer to Posix.2, the description of the 'sh' utility.
8521 */
8522#if ENABLE_HUSH_JOB
8523 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008524 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8525 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8526 if (G_saved_tty_pgrp < 0)
8527 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008528
8529 /* try to dup stdin to high fd#, >= 255 */
8530 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8531 if (G_interactive_fd < 0) {
8532 /* try to dup to any fd */
8533 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008534 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008535 /* give up */
8536 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008537 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008538 }
8539 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008540// TODO: track & disallow any attempts of user
8541// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008542 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008543 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008544 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008545 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008546
Mike Frysinger38478a62009-05-20 04:48:06 -04008547 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008548 /* If we were run as 'hush &', sleep until we are
8549 * in the foreground (tty pgrp == our pgrp).
8550 * If we get started under a job aware app (like bash),
8551 * make sure we are now in charge so we don't fight over
8552 * who gets the foreground */
8553 while (1) {
8554 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008555 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8556 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008557 break;
8558 /* send TTIN to ourself (should stop us) */
8559 kill(- shell_pgrp, SIGTTIN);
8560 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008561 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008562
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008563 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008564 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008565
Mike Frysinger38478a62009-05-20 04:48:06 -04008566 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008567 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008568 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008569 /* Put ourselves in our own process group
8570 * (bash, too, does this only if ctty is available) */
8571 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8572 /* Grab control of the terminal */
8573 tcsetpgrp(G_interactive_fd, getpid());
8574 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02008575 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008576
8577# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8578 {
8579 const char *hp = get_local_var_value("HISTFILE");
8580 if (!hp) {
8581 hp = get_local_var_value("HOME");
8582 if (hp)
8583 hp = concat_path_file(hp, ".hush_history");
8584 } else {
8585 hp = xstrdup(hp);
8586 }
8587 if (hp) {
8588 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008589 //set_local_var(xasprintf("HISTFILE=%s", ...));
8590 }
8591# if ENABLE_FEATURE_SH_HISTFILESIZE
8592 hp = get_local_var_value("HISTFILESIZE");
8593 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8594# endif
8595 }
8596# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008597 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008598 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008599 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008600#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008601 /* No job control compiled in, only prompt/line editing */
8602 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008603 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8604 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008605 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008606 G_interactive_fd = dup(STDIN_FILENO);
8607 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008608 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008609 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008610 }
8611 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008612 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008613 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008614 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008615 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008616#else
8617 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008618 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008619#endif
8620 /* bash:
8621 * if interactive but not a login shell, sources ~/.bashrc
8622 * (--norc turns this off, --rcfile <file> overrides)
8623 */
8624
8625 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008626 /* note: ash and hush share this string */
8627 printf("\n\n%s %s\n"
8628 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8629 "\n",
8630 bb_banner,
8631 "hush - the humble shell"
8632 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008633 }
8634
Denis Vlasenkof9375282009-04-05 19:13:39 +00008635 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008636
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008637 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008638 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008639}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008640
8641
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008642#if ENABLE_MSH
8643int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8644int msh_main(int argc, char **argv)
8645{
Denys Vlasenkoed6ff5e2016-09-30 12:28:37 +02008646 bb_error_msg("msh is deprecated, please use hush instead");
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008647 return hush_main(argc, argv);
8648}
8649#endif
8650
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008651
8652/*
8653 * Built-ins
8654 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008655static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008656{
8657 return 0;
8658}
8659
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008660static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008661{
8662 int argc = 0;
8663 while (*argv) {
8664 argc++;
8665 argv++;
8666 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008667 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008668}
8669
8670static int FAST_FUNC builtin_test(char **argv)
8671{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008672 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008673}
8674
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008675static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008676{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008677 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008678}
8679
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008680#if ENABLE_PRINTF
8681static int FAST_FUNC builtin_printf(char **argv)
8682{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008683 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008684}
8685#endif
8686
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008687static char **skip_dash_dash(char **argv)
8688{
8689 argv++;
8690 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8691 argv++;
8692 return argv;
8693}
8694
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008695static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008696{
8697 int rcode = EXIT_SUCCESS;
8698
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008699 argv = skip_dash_dash(argv);
8700 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008701 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008702 /* bash:
8703 * eval "echo Hi; done" ("done" is syntax error):
8704 * "echo Hi" will not execute too.
8705 */
8706 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008707 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008708 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008709 }
8710 return rcode;
8711}
8712
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008713static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008714{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008715 const char *newdir;
8716
8717 argv = skip_dash_dash(argv);
8718 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008719 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008720 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008721 * bash says "bash: cd: HOME not set" and does nothing
8722 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008723 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008724 const char *home = get_local_var_value("HOME");
8725 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008726 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008727 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008728 /* Mimic bash message exactly */
8729 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008730 return EXIT_FAILURE;
8731 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008732 /* Read current dir (get_cwd(1) is inside) and set PWD.
8733 * Note: do not enforce exporting. If PWD was unset or unexported,
8734 * set it again, but do not export. bash does the same.
8735 */
8736 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008737 return EXIT_SUCCESS;
8738}
8739
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008740static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008741{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008742 argv = skip_dash_dash(argv);
8743 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008744 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008745
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008746 /* Careful: we can end up here after [v]fork. Do not restore
8747 * tty pgrp then, only top-level shell process does that */
8748 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8749 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8750
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008751 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008752 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008753 * and tcsetpgrp, and this is inherently racy.
8754 */
8755 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008756}
8757
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008758static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008759{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008760 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008761
8762 /* interactive bash:
8763 * # trap "echo EEE" EXIT
8764 * # exit
8765 * exit
8766 * There are stopped jobs.
8767 * (if there are _stopped_ jobs, running ones don't count)
8768 * # exit
8769 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01008770 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00008771 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008772 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008773 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008774
8775 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008776 argv = skip_dash_dash(argv);
8777 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008778 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008779 /* mimic bash: exit 123abc == exit 255 + error msg */
8780 xfunc_error_retval = 255;
8781 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008782 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008783}
8784
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008785static void print_escaped(const char *s)
8786{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008787 if (*s == '\'')
8788 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008789 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008790 const char *p = strchrnul(s, '\'');
8791 /* print 'xxxx', possibly just '' */
8792 printf("'%.*s'", (int)(p - s), s);
8793 if (*p == '\0')
8794 break;
8795 s = p;
8796 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008797 /* s points to '; print "'''...'''" */
8798 putchar('"');
8799 do putchar('\''); while (*++s == '\'');
8800 putchar('"');
8801 } while (*s);
8802}
8803
Denys Vlasenko295fef82009-06-03 12:47:26 +02008804#if !ENABLE_HUSH_LOCAL
8805#define helper_export_local(argv, exp, lvl) \
8806 helper_export_local(argv, exp)
8807#endif
8808static void helper_export_local(char **argv, int exp, int lvl)
8809{
8810 do {
8811 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008812 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008813
8814 /* So far we do not check that name is valid (TODO?) */
8815
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008816 if (*name_end == '\0') {
8817 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008818
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008819 vpp = get_ptr_to_local_var(name, name_end - name);
8820 var = vpp ? *vpp : NULL;
8821
Denys Vlasenko295fef82009-06-03 12:47:26 +02008822 if (exp == -1) { /* unexporting? */
8823 /* export -n NAME (without =VALUE) */
8824 if (var) {
8825 var->flg_export = 0;
8826 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8827 unsetenv(name);
8828 } /* else: export -n NOT_EXISTING_VAR: no-op */
8829 continue;
8830 }
8831 if (exp == 1) { /* exporting? */
8832 /* export NAME (without =VALUE) */
8833 if (var) {
8834 var->flg_export = 1;
8835 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8836 putenv(var->varstr);
8837 continue;
8838 }
8839 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02008840#if ENABLE_HUSH_LOCAL
8841 if (exp == 0 /* local? */
8842 && var && var->func_nest_level == lvl
8843 ) {
8844 /* "local x=abc; ...; local x" - ignore second local decl */
Denys Vlasenko80729a42016-10-02 22:33:15 +02008845 continue;
Denys Vlasenko61508d92016-10-02 21:12:02 +02008846 }
8847#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02008848 /* Exporting non-existing variable.
8849 * bash does not put it in environment,
8850 * but remembers that it is exported,
8851 * and does put it in env when it is set later.
8852 * We just set it to "" and export. */
8853 /* Or, it's "local NAME" (without =VALUE).
8854 * bash sets the value to "". */
8855 name = xasprintf("%s=", name);
8856 } else {
8857 /* (Un)exporting/making local NAME=VALUE */
8858 name = xstrdup(name);
8859 }
8860 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8861 } while (*++argv);
8862}
8863
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008864static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008865{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008866 unsigned opt_unexport;
8867
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008868#if ENABLE_HUSH_EXPORT_N
8869 /* "!": do not abort on errors */
8870 opt_unexport = getopt32(argv, "!n");
8871 if (opt_unexport == (uint32_t)-1)
8872 return EXIT_FAILURE;
8873 argv += optind;
8874#else
8875 opt_unexport = 0;
8876 argv++;
8877#endif
8878
8879 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008880 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008881 if (e) {
8882 while (*e) {
8883#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008884 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008885#else
8886 /* ash emits: export VAR='VAL'
8887 * bash: declare -x VAR="VAL"
8888 * we follow ash example */
8889 const char *s = *e++;
8890 const char *p = strchr(s, '=');
8891
8892 if (!p) /* wtf? take next variable */
8893 continue;
8894 /* export var= */
8895 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008896 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008897 putchar('\n');
8898#endif
8899 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008900 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008901 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008902 return EXIT_SUCCESS;
8903 }
8904
Denys Vlasenko295fef82009-06-03 12:47:26 +02008905 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008906
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008907 return EXIT_SUCCESS;
8908}
8909
Denys Vlasenko295fef82009-06-03 12:47:26 +02008910#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008911static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008912{
8913 if (G.func_nest_level == 0) {
8914 bb_error_msg("%s: not in a function", argv[0]);
8915 return EXIT_FAILURE; /* bash compat */
8916 }
8917 helper_export_local(argv, 0, G.func_nest_level);
8918 return EXIT_SUCCESS;
8919}
8920#endif
8921
Denys Vlasenko61508d92016-10-02 21:12:02 +02008922/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8923static int FAST_FUNC builtin_unset(char **argv)
8924{
8925 int ret;
8926 unsigned opts;
8927
8928 /* "!": do not abort on errors */
8929 /* "+": stop at 1st non-option */
8930 opts = getopt32(argv, "!+vf");
8931 if (opts == (unsigned)-1)
8932 return EXIT_FAILURE;
8933 if (opts == 3) {
8934 bb_error_msg("unset: -v and -f are exclusive");
8935 return EXIT_FAILURE;
8936 }
8937 argv += optind;
8938
8939 ret = EXIT_SUCCESS;
8940 while (*argv) {
8941 if (!(opts & 2)) { /* not -f */
8942 if (unset_local_var(*argv)) {
8943 /* unset <nonexistent_var> doesn't fail.
8944 * Error is when one tries to unset RO var.
8945 * Message was printed by unset_local_var. */
8946 ret = EXIT_FAILURE;
8947 }
8948 }
8949#if ENABLE_HUSH_FUNCTIONS
8950 else {
8951 unset_func(*argv);
8952 }
8953#endif
8954 argv++;
8955 }
8956 return ret;
8957}
8958
8959/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8960 * built-in 'set' handler
8961 * SUSv3 says:
8962 * set [-abCefhmnuvx] [-o option] [argument...]
8963 * set [+abCefhmnuvx] [+o option] [argument...]
8964 * set -- [argument...]
8965 * set -o
8966 * set +o
8967 * Implementations shall support the options in both their hyphen and
8968 * plus-sign forms. These options can also be specified as options to sh.
8969 * Examples:
8970 * Write out all variables and their values: set
8971 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8972 * Turn on the -x and -v options: set -xv
8973 * Unset all positional parameters: set --
8974 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8975 * Set the positional parameters to the expansion of x, even if x expands
8976 * with a leading '-' or '+': set -- $x
8977 *
8978 * So far, we only support "set -- [argument...]" and some of the short names.
8979 */
8980static int FAST_FUNC builtin_set(char **argv)
8981{
8982 int n;
8983 char **pp, **g_argv;
8984 char *arg = *++argv;
8985
8986 if (arg == NULL) {
8987 struct variable *e;
8988 for (e = G.top_var; e; e = e->next)
8989 puts(e->varstr);
8990 return EXIT_SUCCESS;
8991 }
8992
8993 do {
8994 if (strcmp(arg, "--") == 0) {
8995 ++argv;
8996 goto set_argv;
8997 }
8998 if (arg[0] != '+' && arg[0] != '-')
8999 break;
9000 for (n = 1; arg[n]; ++n) {
9001 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9002 goto error;
9003 if (arg[n] == 'o' && argv[1])
9004 argv++;
9005 }
9006 } while ((arg = *++argv) != NULL);
9007 /* Now argv[0] is 1st argument */
9008
9009 if (arg == NULL)
9010 return EXIT_SUCCESS;
9011 set_argv:
9012
9013 /* NB: G.global_argv[0] ($0) is never freed/changed */
9014 g_argv = G.global_argv;
9015 if (G.global_args_malloced) {
9016 pp = g_argv;
9017 while (*++pp)
9018 free(*pp);
9019 g_argv[1] = NULL;
9020 } else {
9021 G.global_args_malloced = 1;
9022 pp = xzalloc(sizeof(pp[0]) * 2);
9023 pp[0] = g_argv[0]; /* retain $0 */
9024 g_argv = pp;
9025 }
9026 /* This realloc's G.global_argv */
9027 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9028
9029 n = 1;
9030 while (*++pp)
9031 n++;
9032 G.global_argc = n;
9033
9034 return EXIT_SUCCESS;
9035
9036 /* Nothing known, so abort */
9037 error:
9038 bb_error_msg("set: %s: invalid option", arg);
9039 return EXIT_FAILURE;
9040}
9041
9042static int FAST_FUNC builtin_shift(char **argv)
9043{
9044 int n = 1;
9045 argv = skip_dash_dash(argv);
9046 if (argv[0]) {
9047 n = atoi(argv[0]);
9048 }
9049 if (n >= 0 && n < G.global_argc) {
9050 if (G.global_args_malloced) {
9051 int m = 1;
9052 while (m <= n)
9053 free(G.global_argv[m++]);
9054 }
9055 G.global_argc -= n;
9056 memmove(&G.global_argv[1], &G.global_argv[n+1],
9057 G.global_argc * sizeof(G.global_argv[0]));
9058 return EXIT_SUCCESS;
9059 }
9060 return EXIT_FAILURE;
9061}
9062
9063/* Interruptibility of read builtin in bash
9064 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9065 *
9066 * Empty trap makes read ignore corresponding signal, for any signal.
9067 *
9068 * SIGINT:
9069 * - terminates non-interactive shell;
9070 * - interrupts read in interactive shell;
9071 * if it has non-empty trap:
9072 * - executes trap and returns to command prompt in interactive shell;
9073 * - executes trap and returns to read in non-interactive shell;
9074 * SIGTERM:
9075 * - is ignored (does not interrupt) read in interactive shell;
9076 * - terminates non-interactive shell;
9077 * if it has non-empty trap:
9078 * - executes trap and returns to read;
9079 * SIGHUP:
9080 * - terminates shell (regardless of interactivity);
9081 * if it has non-empty trap:
9082 * - executes trap and returns to read;
9083 */
9084static int FAST_FUNC builtin_read(char **argv)
9085{
9086 const char *r;
9087 char *opt_n = NULL;
9088 char *opt_p = NULL;
9089 char *opt_t = NULL;
9090 char *opt_u = NULL;
9091 const char *ifs;
9092 int read_flags;
9093
9094 /* "!": do not abort on errors.
9095 * Option string must start with "sr" to match BUILTIN_READ_xxx
9096 */
9097 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9098 if (read_flags == (uint32_t)-1)
9099 return EXIT_FAILURE;
9100 argv += optind;
9101 ifs = get_local_var_value("IFS"); /* can be NULL */
9102
9103 again:
9104 r = shell_builtin_read(set_local_var_from_halves,
9105 argv,
9106 ifs,
9107 read_flags,
9108 opt_n,
9109 opt_p,
9110 opt_t,
9111 opt_u
9112 );
9113
9114 if ((uintptr_t)r == 1 && errno == EINTR) {
9115 unsigned sig = check_and_run_traps();
9116 if (sig && sig != SIGINT)
9117 goto again;
9118 }
9119
9120 if ((uintptr_t)r > 1) {
9121 bb_error_msg("%s", r);
9122 r = (char*)(uintptr_t)1;
9123 }
9124
9125 return (uintptr_t)r;
9126}
9127
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009128static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009129{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009130 int sig;
9131 char *new_cmd;
9132
9133 if (!G.traps)
9134 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
9135
9136 argv++;
9137 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00009138 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009139 /* No args: print all trapped */
9140 for (i = 0; i < NSIG; ++i) {
9141 if (G.traps[i]) {
9142 printf("trap -- ");
9143 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02009144 /* note: bash adds "SIG", but only if invoked
9145 * as "bash". If called as "sh", or if set -o posix,
9146 * then it prints short signal names.
9147 * We are printing short names: */
9148 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009149 }
9150 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009151 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009152 return EXIT_SUCCESS;
9153 }
9154
9155 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009156 /* If first arg is a number: reset all specified signals */
9157 sig = bb_strtou(*argv, NULL, 10);
9158 if (errno == 0) {
9159 int ret;
9160 process_sig_list:
9161 ret = EXIT_SUCCESS;
9162 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009163 sighandler_t handler;
9164
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009165 sig = get_signum(*argv++);
9166 if (sig < 0 || sig >= NSIG) {
9167 ret = EXIT_FAILURE;
9168 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00009169 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009170 continue;
9171 }
9172
9173 free(G.traps[sig]);
9174 G.traps[sig] = xstrdup(new_cmd);
9175
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009176 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009177 get_signame(sig), sig, G.traps[sig]);
9178
9179 /* There is no signal for 0 (EXIT) */
9180 if (sig == 0)
9181 continue;
9182
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009183 if (new_cmd)
9184 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9185 else
9186 /* We are removing trap handler */
9187 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02009188 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009189 }
9190 return ret;
9191 }
9192
9193 if (!argv[1]) { /* no second arg */
9194 bb_error_msg("trap: invalid arguments");
9195 return EXIT_FAILURE;
9196 }
9197
9198 /* First arg is "-": reset all specified to default */
9199 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9200 /* Everything else: set arg as signal handler
9201 * (includes "" case, which ignores signal) */
9202 if (argv[0][0] == '-') {
9203 if (argv[0][1] == '\0') { /* "-" */
9204 /* new_cmd remains NULL: "reset these sigs" */
9205 goto reset_traps;
9206 }
9207 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9208 argv++;
9209 }
9210 /* else: "-something", no special meaning */
9211 }
9212 new_cmd = *argv;
9213 reset_traps:
9214 argv++;
9215 goto process_sig_list;
9216}
9217
Mike Frysinger93cadc22009-05-27 17:06:25 -04009218/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009219static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04009220{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009221 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04009222
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009223 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04009224 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02009225 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04009226
9227 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009228 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009229 type = "an alias";*/
9230#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009231 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009232 type = "a function";
9233#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009234 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009235 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009236 else if ((path = find_in_path(*argv)) != NULL)
9237 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009238 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009239 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04009240 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009241 continue;
9242 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04009243
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009244 printf("%s is %s\n", *argv, type);
9245 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04009246 }
9247
9248 return ret;
9249}
9250
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009251#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009252static struct pipe *parse_jobspec(const char *str)
9253{
9254 struct pipe *pi;
9255 int jobnum;
9256
9257 if (sscanf(str, "%%%d", &jobnum) != 1) {
9258 bb_error_msg("bad argument '%s'", str);
9259 return NULL;
9260 }
9261 for (pi = G.job_list; pi; pi = pi->next) {
9262 if (pi->jobid == jobnum) {
9263 return pi;
9264 }
9265 }
9266 bb_error_msg("%d: no such job", jobnum);
9267 return NULL;
9268}
9269
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009270/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009271static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009272{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009273 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009274 struct pipe *pi;
9275
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009276 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009277 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009278
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009279 /* If they gave us no args, assume they want the last backgrounded task */
9280 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00009281 for (pi = G.job_list; pi; pi = pi->next) {
9282 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009283 goto found;
9284 }
9285 }
9286 bb_error_msg("%s: no current job", argv[0]);
9287 return EXIT_FAILURE;
9288 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009289
9290 pi = parse_jobspec(argv[1]);
9291 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009292 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009293 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00009294 /* TODO: bash prints a string representation
9295 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04009296 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009297 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009298 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009299 }
9300
9301 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009302 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9303 for (i = 0; i < pi->num_cmds; i++) {
9304 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009305 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009306 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009307
9308 i = kill(- pi->pgrp, SIGCONT);
9309 if (i < 0) {
9310 if (errno == ESRCH) {
9311 delete_finished_bg_job(pi);
9312 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009313 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009314 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009315 }
9316
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009317 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009318 remove_bg_job(pi);
9319 return checkjobs_and_fg_shell(pi);
9320 }
9321 return EXIT_SUCCESS;
9322}
9323#endif
9324
9325#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009326static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009327{
9328 const struct built_in_command *x;
9329
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009330 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009331 "Built-in commands:\n"
9332 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009333 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01009334 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009335 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009336 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009337 return EXIT_SUCCESS;
9338}
9339#endif
9340
Denys Vlasenkoff463a82013-05-12 02:45:23 +02009341#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02009342static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9343{
9344 show_history(G.line_input_state);
9345 return EXIT_SUCCESS;
9346}
9347#endif
9348
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009349#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009350static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009351{
9352 struct pipe *job;
9353 const char *status_string;
9354
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009355 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denis Vlasenko87a86552008-07-29 19:43:10 +00009356 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009357 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009358 status_string = "Stopped";
9359 else
9360 status_string = "Running";
9361
9362 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9363 }
9364 return EXIT_SUCCESS;
9365}
9366#endif
9367
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009368#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009369static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009370{
9371 void *p;
9372 unsigned long l;
9373
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009374# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02009375 /* Optional. Reduces probability of false positives */
9376 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009377# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009378 /* Crude attempt to find where "free memory" starts,
9379 * sans fragmentation. */
9380 p = malloc(240);
9381 l = (unsigned long)p;
9382 free(p);
9383 p = malloc(3400);
9384 if (l < (unsigned long)p) l = (unsigned long)p;
9385 free(p);
9386
Denys Vlasenko7f0ebbc2016-10-03 17:42:53 +02009387
9388# if 0 /* debug */
9389 {
9390 struct mallinfo mi = mallinfo();
9391 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
9392 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
9393 }
9394# endif
9395
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009396 if (!G.memleak_value)
9397 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02009398
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009399 l -= G.memleak_value;
9400 if ((long)l < 0)
9401 l = 0;
9402 l /= 1024;
9403 if (l > 127)
9404 l = 127;
9405
9406 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9407 return l;
9408}
9409#endif
9410
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009411static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009412{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009413 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009414 return EXIT_SUCCESS;
9415}
9416
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009417static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009418{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009419 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009420 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009421 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009422#if ENABLE_HUSH_FUNCTIONS
9423 smallint sv_flg;
9424#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009425
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009426 argv = skip_dash_dash(argv);
9427 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009428 if (!filename) {
9429 /* bash says: "bash: .: filename argument required" */
9430 return 2; /* bash compat */
9431 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009432 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009433 if (!strchr(filename, '/')) {
9434 arg_path = find_in_path(filename);
9435 if (arg_path)
9436 filename = arg_path;
9437 }
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009438 input = remember_FILE(fopen_or_warn(filename, "r"));
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009439 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009440 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009441 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009442 /* POSIX: non-interactive shell should abort here,
9443 * not merely fail. So far no one complained :)
9444 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009445 return EXIT_FAILURE;
9446 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009447
Mike Frysinger885b6f22009-04-18 21:04:25 +00009448#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009449 sv_flg = G_flag_return_in_progress;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009450 /* "we are inside sourced file, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009451 G_flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009452#endif
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009453 if (argv[1])
9454 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009455
Denys Vlasenko992e0ff2016-09-29 01:27:09 +02009456 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9457 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009458 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009459 fclose_and_forget(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009460
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009461 if (argv[1])
9462 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00009463#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009464 G_flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009465#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009466
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009467 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009468}
9469
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009470static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009471{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009472 int rc;
9473 mode_t mask;
9474
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009475 rc = 1;
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009476 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009477 argv = skip_dash_dash(argv);
9478 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009479 mode_t old_mask = mask;
9480
Denys Vlasenko6283f982015-10-07 16:56:20 +02009481 /* numeric umasks are taken as-is */
9482 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9483 if (!isdigit(argv[0][0]))
9484 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009485 mask = bb_parse_mode(argv[0], mask);
Denys Vlasenko6283f982015-10-07 16:56:20 +02009486 if (!isdigit(argv[0][0]))
9487 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009488 if ((unsigned)mask > 0777) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009489 mask = old_mask;
9490 /* bash messages:
9491 * bash: umask: 'q': invalid symbolic mode operator
9492 * bash: umask: 999: octal number out of range
9493 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02009494 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009495 rc = 0;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009496 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009497 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009498 /* Mimic bash */
9499 printf("%04o\n", (unsigned) mask);
9500 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009501 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009502 umask(mask);
9503
9504 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009505}
9506
Mike Frysinger56bdea12009-03-28 20:01:58 +00009507/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009508#if !ENABLE_HUSH_JOB
9509# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
9510#endif
9511static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +02009512{
9513 int ret = 0;
9514 for (;;) {
9515 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009516 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +02009517
Denys Vlasenko830ea352016-11-08 04:59:11 +01009518 if (!sigisemptyset(&G.pending_set))
9519 goto check_sig;
9520
Denys Vlasenko7e675362016-10-28 21:57:31 +02009521 /* waitpid is not interruptible by SA_RESTARTed
9522 * signals which we use. Thus, this ugly dance:
9523 */
9524
9525 /* Make sure possible SIGCHLD is stored in kernel's
9526 * pending signal mask before we call waitpid.
9527 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009528 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +02009529 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009530 sigfillset(&oldset); /* block all signals, remember old set */
9531 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009532
9533 if (!sigisemptyset(&G.pending_set)) {
9534 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009535 goto restore;
9536 }
9537
9538 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009539/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009540 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009541 debug_printf_exec("checkjobs:%d\n", ret);
9542#if ENABLE_HUSH_JOB
9543 if (waitfor_pipe) {
9544 int rcode = job_exited_or_stopped(waitfor_pipe);
9545 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
9546 if (rcode >= 0) {
9547 ret = rcode;
9548 sigprocmask(SIG_SETMASK, &oldset, NULL);
9549 break;
9550 }
9551 }
9552#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009553 /* if ECHILD, there are no children (ret is -1 or 0) */
9554 /* if ret == 0, no children changed state */
9555 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009556 if (errno == ECHILD || ret) {
9557 ret--;
9558 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009559 ret = 0;
9560 sigprocmask(SIG_SETMASK, &oldset, NULL);
9561 break;
9562 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009563 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009564 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9565 /* Note: sigsuspend invokes signal handler */
9566 sigsuspend(&oldset);
9567 restore:
9568 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +01009569 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009570 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009571 sig = check_and_run_traps();
9572 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009573 ret = 128 + sig;
9574 break;
9575 }
9576 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9577 }
9578 return ret;
9579}
9580
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009581static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00009582{
Denys Vlasenko7e675362016-10-28 21:57:31 +02009583 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009584 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009585
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009586 argv = skip_dash_dash(argv);
9587 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009588 /* Don't care about wait results */
9589 /* Note 1: must wait until there are no more children */
9590 /* Note 2: must be interruptible */
9591 /* Examples:
9592 * $ sleep 3 & sleep 6 & wait
9593 * [1] 30934 sleep 3
9594 * [2] 30935 sleep 6
9595 * [1] Done sleep 3
9596 * [2] Done sleep 6
9597 * $ sleep 3 & sleep 6 & wait
9598 * [1] 30936 sleep 3
9599 * [2] 30937 sleep 6
9600 * [1] Done sleep 3
9601 * ^C <-- after ~4 sec from keyboard
9602 * $
9603 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009604 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009605 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009606
Denys Vlasenko7e675362016-10-28 21:57:31 +02009607 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009608 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009609 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009610#if ENABLE_HUSH_JOB
9611 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +01009612 struct pipe *wait_pipe;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009613 wait_pipe = parse_jobspec(*argv);
9614 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +01009615 ret = job_exited_or_stopped(wait_pipe);
9616 if (ret < 0)
9617 ret = wait_for_child_or_signal(wait_pipe, 0);
9618 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009619 }
9620 }
9621#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00009622 /* mimic bash message */
9623 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009624 ret = EXIT_FAILURE;
9625 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009626 }
Denys Vlasenko02affb42016-11-08 00:59:29 +01009627
Denys Vlasenko7e675362016-10-28 21:57:31 +02009628 /* Do we have such child? */
9629 ret = waitpid(pid, &status, WNOHANG);
9630 if (ret < 0) {
9631 /* No */
9632 if (errno == ECHILD) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009633 if (G.last_bg_pid > 0 && pid == G.last_bg_pid) {
9634 /* "wait $!" but last bg task has already exited. Try:
9635 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
9636 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +01009637 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009638 */
Denys Vlasenko26ad94b2016-11-07 23:07:21 +01009639 /* ret = G.last_bg_pid_exitstatus - FIXME */
9640 } else {
9641 /* Example: "wait 1". mimic bash message */
9642 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009643 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009644 } else {
9645 /* ??? */
9646 bb_perror_msg("wait %s", *argv);
9647 }
9648 ret = 127;
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009649 continue; /* bash checks all argv[] */
9650 }
9651 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009652 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +01009653 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009654 } else {
9655 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +01009656 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +02009657 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009658 if (WIFSIGNALED(status))
9659 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009660 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009661 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009662
9663 return ret;
9664}
9665
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009666#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9667static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9668{
9669 if (argv[1]) {
9670 def = bb_strtou(argv[1], NULL, 10);
9671 if (errno || def < def_min || argv[2]) {
9672 bb_error_msg("%s: bad arguments", argv[0]);
9673 def = UINT_MAX;
9674 }
9675 }
9676 return def;
9677}
9678#endif
9679
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009680#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009681static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009682{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009683 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009684 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009685 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +02009686 /* if we came from builtin_continue(), need to undo "= 1" */
9687 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009688 return EXIT_SUCCESS; /* bash compat */
9689 }
Denys Vlasenko49117b42016-07-21 14:40:08 +02009690 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009691
9692 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9693 if (depth == UINT_MAX)
9694 G.flag_break_continue = BC_BREAK;
9695 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009696 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009697
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009698 return EXIT_SUCCESS;
9699}
9700
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009701static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009702{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009703 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9704 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009705}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009706#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009707
9708#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009709static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009710{
9711 int rc;
9712
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009713 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009714 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9715 return EXIT_FAILURE; /* bash compat */
9716 }
9717
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009718 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009719
9720 /* bash:
9721 * out of range: wraps around at 256, does not error out
9722 * non-numeric param:
9723 * f() { false; return qwe; }; f; echo $?
9724 * bash: return: qwe: numeric argument required <== we do this
9725 * 255 <== we also do this
9726 */
9727 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9728 return rc;
9729}
9730#endif