blob: a713a9680a86985a31bce7d127eaa282edf54e70 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
45 * tilde expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000046 * aliases
Denys Vlasenko349ef962010-05-21 15:46:24 +020047 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020050 * make complex ${var%...} constructs support optional
51 * make here documents optional
Mike Frysinger25a6ca02009-03-28 13:59:26 +000052 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020053 * Bash compat TODO:
54 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020055 * reserved words: function select
56 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020057 * process substitution: <(list) and >(list)
58 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020059 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020060 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020063 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020064 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020066 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenkobbecd742010-10-03 17:22:52 +020067 *
68 * Won't do:
69 * In bash, export builtin is special, its arguments are assignments
Denys Vlasenko08218012009-06-03 14:43:56 +020070 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
72 * compare with:
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020076 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020077 * Note2: bash 3.2.33(1) does this only if export word itself
78 * is not quoted:
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
80 * aaa bbb
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
82 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000083 */
Denys Vlasenko202a2d12010-07-16 12:36:14 +020084//config:config HUSH
85//config: bool "hush"
86//config: default y
87//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +020088//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +020089//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
90//config: case/esac. Redirections, here documents, $((arithmetic))
91//config: and functions are supported.
92//config:
93//config: It will compile and work on no-mmu systems.
94//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +020095//config: It does not handle select, aliases, tilde expansion,
96//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +020097//config:
98//config:config HUSH_BASH_COMPAT
99//config: bool "bash-compatible extensions"
100//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100101//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200102//config: help
103//config: Enable bash-compatible extensions.
104//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200105//config:config HUSH_BRACE_EXPANSION
106//config: bool "Brace expansion"
107//config: default y
108//config: depends on HUSH_BASH_COMPAT
109//config: help
110//config: Enable {abc,def} extension.
111//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200112//config:config HUSH_INTERACTIVE
113//config: bool "Interactive mode"
114//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100115//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200116//config: help
117//config: Enable interactive mode (prompt and command editing).
118//config: Without this, hush simply reads and executes commands
119//config: from stdin just like a shell script from a file.
120//config: No prompt, no PS1/PS2 magic shell variables.
121//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200122//config:config HUSH_SAVEHISTORY
123//config: bool "Save command history to .hush_history"
124//config: default y
125//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
126//config: help
127//config: Enable history saving in hush.
128//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200129//config:config HUSH_JOB
130//config: bool "Job control"
131//config: default y
132//config: depends on HUSH_INTERACTIVE
133//config: help
134//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
135//config: command (not entire shell), fg/bg builtins work. Without this option,
136//config: "cmd &" still works by simply spawning a process and immediately
137//config: prompting for next command (or executing next command in a script),
138//config: but no separate process group is formed.
139//config:
140//config:config HUSH_TICK
141//config: bool "Process substitution"
142//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100143//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200144//config: help
145//config: Enable process substitution `command` and $(command) in hush.
146//config:
147//config:config HUSH_IF
148//config: bool "Support if/then/elif/else/fi"
149//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100150//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200151//config: help
152//config: Enable if/then/elif/else/fi in hush.
153//config:
154//config:config HUSH_LOOPS
155//config: bool "Support for, while and until loops"
156//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100157//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200158//config: help
159//config: Enable for, while and until loops in hush.
160//config:
161//config:config HUSH_CASE
162//config: bool "Support case ... esac statement"
163//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100164//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200165//config: help
166//config: Enable case ... esac statement in hush. +400 bytes.
167//config:
168//config:config HUSH_FUNCTIONS
169//config: bool "Support funcname() { commands; } syntax"
170//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100171//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200172//config: help
173//config: Enable support for shell functions in hush. +800 bytes.
174//config:
175//config:config HUSH_LOCAL
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100176//config: bool "local builtin"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200177//config: default y
178//config: depends on HUSH_FUNCTIONS
179//config: help
180//config: Enable support for local variables in functions.
181//config:
182//config:config HUSH_RANDOM_SUPPORT
183//config: bool "Pseudorandom generator and $RANDOM variable"
184//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100185//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200186//config: help
187//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
188//config: Each read of "$RANDOM" will generate a new pseudorandom value.
189//config:
190//config:config HUSH_EXPORT_N
191//config: bool "Support 'export -n' option"
192//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100193//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200194//config: help
195//config: export -n unexports variables. It is a bash extension.
196//config:
197//config:config HUSH_MODE_X
198//config: bool "Support 'hush -x' option and 'set -x' command"
199//config: default y
Denys Vlasenko0b883582016-12-23 16:49:07 +0100200//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200201//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200202//config: This instructs hush to print commands before execution.
203//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200204//config:
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100205//config:config HUSH_HELP
206//config: bool "help builtin"
207//config: default y
208//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
209//config: help
210//config: Enable help builtin in hush. Code size + ~1 kbyte.
211//config:
212//config:config HUSH_PRINTF
213//config: bool "printf builtin"
214//config: default y
215//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
216//config: help
217//config: Enable printf builtin in hush.
218//config:
219//config:config HUSH_KILL
220//config: bool "kill builtin (for kill %jobspec)"
221//config: default y
222//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
223//config: help
224//config: Enable kill builtin in hush.
225//config:
226//config:config HUSH_WAIT
227//config: bool "wait builtin"
228//config: default y
229//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
230//config: help
231//config: Enable wait builtin in hush.
232//config:
233//config:config HUSH_TRAP
234//config: bool "trap builtin"
235//config: default y
236//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
237//config: help
238//config: Enable trap builtin in hush.
239//config:
240//config:config HUSH_ULIMIT
241//config: bool "ulimit builtin"
242//config: default y
243//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
244//config: help
245//config: Enable ulimit builtin in hush.
246//config:
247//config:config HUSH_TYPE
248//config: bool "type builtin"
249//config: default y
250//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
251//config: help
252//config: Enable type builtin in hush.
253//config:
254//config:config HUSH_READ
255//config: bool "read builtin"
256//config: default y
257//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
258//config: help
259//config: Enable read builtin in hush.
260//config:
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100261//config:config HUSH_SET
262//config: bool "set builtin"
263//config: default y
264//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
265//config: help
266//config: Enable set builtin in hush.
267//config:
268//config:config HUSH_UNSET
269//config: bool "unset builtin"
270//config: default y
271//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
272//config: help
273//config: Enable unset builtin in hush.
274//config:
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100275//config:config HUSH_UMASK
276//config: bool "umask builtin"
277//config: default y
278//config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
279//config: help
280//config: Enable umask builtin in hush.
281//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200282//config:config MSH
283//config: bool "msh (deprecated: aliased to hush)"
284//config: default n
285//config: select HUSH
286//config: help
287//config: msh is deprecated and will be removed, please migrate to hush.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200288
Denys Vlasenko20704f02011-03-23 17:59:27 +0100289//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
Denys Vlasenko0b883582016-12-23 16:49:07 +0100290//applet:IF_MSH(APPLET_ODDNAME(msh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
291//applet:IF_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
292//applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
Denys Vlasenko20704f02011-03-23 17:59:27 +0100293
294//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko0b883582016-12-23 16:49:07 +0100295//kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
296//kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
Denys Vlasenko20704f02011-03-23 17:59:27 +0100297//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
298
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100299/* -i (interactive) and -s (read stdin) are also accepted,
300 * but currently do nothing, therefore aren't shown in help.
301 * NOMMU-specific options are not meant to be used by users,
302 * therefore we don't show them either.
303 */
304//usage:#define hush_trivial_usage
Denys Vlasenkof58f7052011-05-12 02:10:33 +0200305//usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100306//usage:#define hush_full_usage "\n\n"
307//usage: "Unix shell interpreter"
308
Denys Vlasenko67047462016-12-22 15:21:58 +0100309#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
310 || defined(__APPLE__) \
311 )
312# include <malloc.h> /* for malloc_trim */
313#endif
314#include <glob.h>
315/* #include <dmalloc.h> */
316#if ENABLE_HUSH_CASE
317# include <fnmatch.h>
318#endif
319#include <sys/utsname.h> /* for setting $HOSTNAME */
320
321#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
322#include "unicode.h"
323#include "shell_common.h"
324#include "math.h"
325#include "match.h"
326#if ENABLE_HUSH_RANDOM_SUPPORT
327# include "random.h"
328#else
329# define CLEAR_RANDOM_T(rnd) ((void)0)
330#endif
331#ifndef F_DUPFD_CLOEXEC
332# define F_DUPFD_CLOEXEC F_DUPFD
333#endif
334#ifndef PIPE_BUF
335# define PIPE_BUF 4096 /* amount of buffering in a pipe */
336#endif
337
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000338
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200339/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000340#define LEAK_HUNTING 0
341#define BUILD_AS_NOMMU 0
342/* Enable/disable sanity checks. Ok to enable in production,
343 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
344 * Keeping 1 for now even in released versions.
345 */
346#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200347/* Slightly bigger (+200 bytes), but faster hush.
348 * So far it only enables a trick with counting SIGCHLDs and forks,
349 * which allows us to do fewer waitpid's.
350 * (we can detect a case where neither forks were done nor SIGCHLDs happened
351 * and therefore waitpid will return the same result as last time)
352 */
353#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200354/* TODO: implement simplified code for users which do not need ${var%...} ops
355 * So far ${var%...} ops are always enabled:
356 */
357#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000358
359
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000360#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000361# undef BB_MMU
362# undef USE_FOR_NOMMU
363# undef USE_FOR_MMU
364# define BB_MMU 0
365# define USE_FOR_NOMMU(...) __VA_ARGS__
366# define USE_FOR_MMU(...)
367#endif
368
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200369#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100370#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000371/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000372# undef CONFIG_FEATURE_SH_STANDALONE
373# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000374# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100375# undef IF_NOT_FEATURE_SH_STANDALONE
376# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000377# define IF_FEATURE_SH_STANDALONE(...)
378# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000379#endif
380
Denis Vlasenko05743d72008-02-10 12:10:08 +0000381#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000382# undef ENABLE_FEATURE_EDITING
383# define ENABLE_FEATURE_EDITING 0
384# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
385# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200386# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
387# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000388#endif
389
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000390/* Do we support ANY keywords? */
391#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000392# define HAS_KEYWORDS 1
393# define IF_HAS_KEYWORDS(...) __VA_ARGS__
394# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000395#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000396# define HAS_KEYWORDS 0
397# define IF_HAS_KEYWORDS(...)
398# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000399#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000400
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000401/* If you comment out one of these below, it will be #defined later
402 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000403#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000404/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000405#define debug_printf_parse(...) do {} while (0)
406#define debug_print_tree(a, b) do {} while (0)
407#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000408#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000409#define debug_printf_jobs(...) do {} while (0)
410#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200411#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000412#define debug_printf_glob(...) do {} while (0)
413#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000414#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000415#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000416
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000417#define ERR_PTR ((void*)(long)1)
418
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100419#define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000420
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200421#define _SPECIAL_VARS_STR "_*@$!?#"
422#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
423#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200424#if ENABLE_HUSH_BASH_COMPAT
425/* Support / and // replace ops */
426/* Note that // is stored as \ in "encoded" string representation */
427# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
428# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
429# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
430#else
431# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
432# define VAR_SUBST_OPS "%#:-=+?"
433# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
434#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200435
436#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000437
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200438struct variable;
439
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000440static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
441
442/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000443 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000444 */
445#if !BB_MMU
446typedef struct nommu_save_t {
447 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200448 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000449 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000450 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000451} nommu_save_t;
452#endif
453
Denys Vlasenko9b782552010-09-08 13:33:26 +0200454enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000455 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000456#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000457 RES_IF ,
458 RES_THEN ,
459 RES_ELIF ,
460 RES_ELSE ,
461 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000462#endif
463#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000464 RES_FOR ,
465 RES_WHILE ,
466 RES_UNTIL ,
467 RES_DO ,
468 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000469#endif
470#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000471 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000472#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000473#if ENABLE_HUSH_CASE
474 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200475 /* three pseudo-keywords support contrived "case" syntax: */
476 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
477 RES_MATCH , /* "word)" */
478 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000479 RES_ESAC ,
480#endif
481 RES_XXXX ,
482 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200483};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000484
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000485typedef struct o_string {
486 char *data;
487 int length; /* position where data is appended */
488 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200489 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000490 /* At least some part of the string was inside '' or "",
491 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200492 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000493 smallint has_empty_slot;
494 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
495} o_string;
496enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200497 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
498 EXP_FLAG_GLOB = 0x2,
499 /* Protect newly added chars against globbing
500 * by prepending \ to *, ?, [, \ */
501 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
502};
503enum {
504 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000505 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200506 NOT_ASSIGNMENT = 2,
Maninder Singh97c64912015-05-25 13:46:36 +0200507 /* Not an assignment, but next word may be: "if v=xyz cmd;" */
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200508 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000509};
510/* Used for initialization: o_string foo = NULL_O_STRING; */
511#define NULL_O_STRING { NULL }
512
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200513#ifndef debug_printf_parse
514static const char *const assignment_flag[] = {
515 "MAYBE_ASSIGNMENT",
516 "DEFINITELY_ASSIGNMENT",
517 "NOT_ASSIGNMENT",
518 "WORD_IS_KEYWORD",
519};
520#endif
521
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000522typedef struct in_str {
523 const char *p;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000524#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000525 smallint promptmode; /* 0: PS1, 1: PS2 */
526#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +0200527 int peek_buf[2];
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200528 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000529 FILE *file;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000530} in_str;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000531
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200532/* The descrip member of this structure is only used to make
533 * debugging output pretty */
534static const struct {
535 int mode;
536 signed char default_fd;
537 char descrip[3];
538} redir_table[] = {
539 { O_RDONLY, 0, "<" },
540 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
541 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
542 { O_CREAT|O_RDWR, 1, "<>" },
543 { O_RDONLY, 0, "<<" },
544/* Should not be needed. Bogus default_fd helps in debugging */
545/* { O_RDONLY, 77, "<<" }, */
546};
547
Eric Andersen25f27032001-04-26 23:22:31 +0000548struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000549 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000550 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000551 int rd_fd; /* fd to redirect */
552 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
553 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000554 smallint rd_type; /* (enum redir_type) */
555 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000556 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200557 * bit 0: do we need to trim leading tabs?
558 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000559 */
Eric Andersen25f27032001-04-26 23:22:31 +0000560};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000561typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200562 REDIRECT_INPUT = 0,
563 REDIRECT_OVERWRITE = 1,
564 REDIRECT_APPEND = 2,
565 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000566 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200567 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000568
569 REDIRFD_CLOSE = -3,
570 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000571 REDIRFD_TO_FILE = -1,
572 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000573
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000574 HEREDOC_SKIPTABS = 1,
575 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000576} redir_type;
577
Eric Andersen25f27032001-04-26 23:22:31 +0000578
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000579struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000580 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000581 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200582 smallint cmd_type; /* CMD_xxx */
583#define CMD_NORMAL 0
584#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200585#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200586/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200587# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000588#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200589#if ENABLE_HUSH_FUNCTIONS
590# define CMD_FUNCDEF 3
591#endif
592
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100593 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200594 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
595 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000596#if !BB_MMU
597 char *group_as_string;
598#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000599#if ENABLE_HUSH_FUNCTIONS
600 struct function *child_func;
601/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200602 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000603 * When we execute "f1() {a;}" cmd, we create new function and clear
604 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200605 * When we execute "f1() {b;}", we notice that f1 exists,
606 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000607 * we put those fields back into cmd->xxx
608 * (struct function has ->parent_cmd ptr to facilitate that).
609 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
610 * Without this trick, loop would execute a;b;b;b;...
611 * instead of correct sequence a;b;a;b;...
612 * When command is freed, it severs the link
613 * (sets ->child_func->parent_cmd to NULL).
614 */
615#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000616 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000617/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
618 * and on execution these are substituted with their values.
619 * Substitution can make _several_ words out of one argv[n]!
620 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000621 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000622 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000623 struct redir_struct *redirects; /* I/O redirections */
624};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000625/* Is there anything in this command at all? */
626#define IS_NULL_CMD(cmd) \
627 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
628
Eric Andersen25f27032001-04-26 23:22:31 +0000629struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000630 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000631 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000632 int alive_cmds; /* number of commands running (not exited) */
633 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000634#if ENABLE_HUSH_JOB
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100635 unsigned jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000636 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000637 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000638#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000639 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000640 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000641 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
642 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000643};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000644typedef enum pipe_style {
Denys Vlasenko00a06b92016-11-08 20:35:53 +0100645 PIPE_SEQ = 0,
646 PIPE_AND = 1,
647 PIPE_OR = 2,
648 PIPE_BG = 3,
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000649} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000650/* Is there anything in this pipe at all? */
651#define IS_NULL_PIPE(pi) \
652 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000653
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000654/* This holds pointers to the various results of parsing */
655struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000656 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000657 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000658 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000659 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000660 /* last command in pipe (being constructed right now) */
661 struct command *command;
662 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000663 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000664#if !BB_MMU
665 o_string as_string;
666#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000667#if HAS_KEYWORDS
668 smallint ctx_res_w;
669 smallint ctx_inverted; /* "! cmd | cmd" */
670#if ENABLE_HUSH_CASE
671 smallint ctx_dsemicolon; /* ";;" seen */
672#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000673 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
674 int old_flag;
675 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000676 * example: "if pipe1; pipe2; then pipe3; fi"
677 * when we see "if" or "then", we malloc and copy current context,
678 * and make ->stack point to it. then we parse pipeN.
679 * when closing "then" / fi" / whatever is found,
680 * we move list_head into ->stack->command->group,
681 * copy ->stack into current context, and delete ->stack.
682 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000683 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000684 struct parse_context *stack;
685#endif
686};
687
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000688/* On program start, environ points to initial environment.
689 * putenv adds new pointers into it, unsetenv removes them.
690 * Neither of these (de)allocates the strings.
691 * setenv allocates new strings in malloc space and does putenv,
692 * and thus setenv is unusable (leaky) for shell's purposes */
693#define setenv(...) setenv_is_leaky_dont_use()
694struct variable {
695 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000696 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200697#if ENABLE_HUSH_LOCAL
698 unsigned func_nest_level;
699#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000700 int max_len; /* if > 0, name is part of initial env; else name is malloced */
701 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000702 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000703};
704
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000705enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000706 BC_BREAK = 1,
707 BC_CONTINUE = 2,
708};
709
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000710#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000711struct function {
712 struct function *next;
713 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000714 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000715 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200716# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000717 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200718# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000719};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000720#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000721
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000722
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100723/* set -/+o OPT support. (TODO: make it optional)
724 * bash supports the following opts:
725 * allexport off
726 * braceexpand on
727 * emacs on
728 * errexit off
729 * errtrace off
730 * functrace off
731 * hashall on
732 * histexpand off
733 * history on
734 * ignoreeof off
735 * interactive-comments on
736 * keyword off
737 * monitor on
738 * noclobber off
739 * noexec off
740 * noglob off
741 * nolog off
742 * notify off
743 * nounset off
744 * onecmd off
745 * physical off
746 * pipefail off
747 * posix off
748 * privileged off
749 * verbose off
750 * vi off
751 * xtrace off
752 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800753static const char o_opt_strings[] ALIGN1 =
754 "pipefail\0"
755 "noexec\0"
756#if ENABLE_HUSH_MODE_X
757 "xtrace\0"
758#endif
759 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100760enum {
761 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800762 OPT_O_NOEXEC,
763#if ENABLE_HUSH_MODE_X
764 OPT_O_XTRACE,
765#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100766 NUM_OPT_O
767};
768
769
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200770struct FILE_list {
771 struct FILE_list *next;
772 FILE *fp;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +0200773 int fd;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200774};
775
776
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000777/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000778/* Sorted roughly by size (smaller offsets == smaller code) */
779struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000780 /* interactive_fd != 0 means we are an interactive shell.
781 * If we are, then saved_tty_pgrp can also be != 0, meaning
782 * that controlling tty is available. With saved_tty_pgrp == 0,
783 * job control still works, but terminal signals
784 * (^C, ^Z, ^Y, ^\) won't work at all, and background
785 * process groups can only be created with "cmd &".
786 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
787 * to give tty to the foreground process group,
788 * and will take it back when the group is stopped (^Z)
789 * or killed (^C).
790 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000791#if ENABLE_HUSH_INTERACTIVE
792 /* 'interactive_fd' is a fd# open to ctty, if we have one
793 * _AND_ if we decided to act interactively */
794 int interactive_fd;
795 const char *PS1;
796 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000797# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000798#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000799# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000800#endif
801#if ENABLE_FEATURE_EDITING
802 line_input_t *line_input_state;
803#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000804 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200805 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000806 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200807#if ENABLE_HUSH_RANDOM_SUPPORT
808 random_t random_gen;
809#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000810#if ENABLE_HUSH_JOB
811 int run_list_level;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +0100812 unsigned last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000813 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000814 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400815# define G_saved_tty_pgrp (G.saved_tty_pgrp)
816#else
817# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000818#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100819 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100820#if ENABLE_HUSH_MODE_X
821# define G_x_mode (G.o_opt[OPT_O_XTRACE])
822#else
823# define G_x_mode 0
824#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000825 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000826#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000827 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000828#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000829#if ENABLE_HUSH_FUNCTIONS
830 /* 0: outside of a function (or sourced file)
831 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000832 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000833 */
834 smallint flag_return_in_progress;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +0200835# define G_flag_return_in_progress (G.flag_return_in_progress)
836#else
837# define G_flag_return_in_progress 0
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000838#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000839 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000840 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000841 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000842 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000843 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000844 /* how many non-NULL argv's we have. NB: $# + 1 */
845 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000846 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000847#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000848 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000849#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000850#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000851 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000852 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000853#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000854 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000855 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200856 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200857 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000858#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000859 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200860# if ENABLE_HUSH_LOCAL
861 struct variable **shadowed_vars_pp;
862 unsigned func_nest_level;
863# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000864#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000865 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200866#if ENABLE_HUSH_FAST
867 unsigned count_SIGCHLD;
868 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200869 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200870#endif
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +0200871 struct FILE_list *FILE_list;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200872 /* Which signals have non-DFL handler (even with no traps set)?
873 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200874 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200875 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200876 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200877 * Other than these two times, never modified.
878 */
879 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200880#if ENABLE_HUSH_JOB
881 unsigned fatal_sig_mask;
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200882# define G_fatal_sig_mask G.fatal_sig_mask
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200883#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200884# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200885#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100886#if ENABLE_HUSH_TRAP
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000887 char **traps; /* char *traps[NSIG] */
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100888# define G_traps G.traps
889#else
890# define G_traps ((char**)NULL)
891#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200892 sigset_t pending_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000893#if HUSH_DEBUG
894 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000895 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000896#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200897 struct sigaction sa;
Denys Vlasenko0448c552016-09-29 20:25:44 +0200898#if ENABLE_FEATURE_EDITING
899 char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
900#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000901};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000902#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000903/* Not #defining name to G.name - this quickly gets unwieldy
904 * (too many defines). Also, I actually prefer to see when a variable
905 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000906#define INIT_G() do { \
907 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200908 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
909 sigfillset(&G.sa.sa_mask); \
910 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000911} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000912
913
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000914/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200915static int builtin_cd(char **argv) FAST_FUNC;
916static int builtin_echo(char **argv) FAST_FUNC;
917static int builtin_eval(char **argv) FAST_FUNC;
918static int builtin_exec(char **argv) FAST_FUNC;
919static int builtin_exit(char **argv) FAST_FUNC;
920static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000921#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200922static int builtin_fg_bg(char **argv) FAST_FUNC;
923static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000924#endif
925#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200926static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000927#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200928#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200929static int builtin_history(char **argv) FAST_FUNC;
930#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200931#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200932static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200933#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000934#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200935static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000936#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +0100937#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400938static int builtin_printf(char **argv) FAST_FUNC;
939#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200940static int builtin_pwd(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100941#if ENABLE_HUSH_READ
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200942static int builtin_read(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100943#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100944#if ENABLE_HUSH_SET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200945static int builtin_set(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100946#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200947static int builtin_shift(char **argv) FAST_FUNC;
948static int builtin_source(char **argv) FAST_FUNC;
949static int builtin_test(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100950#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200951static int builtin_trap(char **argv) FAST_FUNC;
Denys Vlasenko7a85c602017-01-08 17:40:18 +0100952#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +0100953#if ENABLE_HUSH_TYPE
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200954static int builtin_type(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +0100955#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200956static int builtin_true(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100957#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200958static int builtin_umask(char **argv) FAST_FUNC;
Denys Vlasenkod5933b12017-01-08 18:31:39 +0100959#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100960#if ENABLE_HUSH_UNSET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200961static int builtin_unset(char **argv) FAST_FUNC;
Denys Vlasenko10d5ece2017-01-08 18:28:43 +0100962#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +0100963#if ENABLE_HUSH_KILL
964static int builtin_kill(char **argv) FAST_FUNC;
965#endif
966#if ENABLE_HUSH_WAIT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200967static int builtin_wait(char **argv) FAST_FUNC;
Denys Vlasenko1125d7d2017-01-08 17:19:38 +0100968#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000969#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200970static int builtin_break(char **argv) FAST_FUNC;
971static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000972#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000973#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200974static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000975#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000976
977/* Table of built-in functions. They can be forked or not, depending on
978 * context: within pipes, they fork. As simple commands, they do not.
979 * When used in non-forking context, they can change global variables
980 * in the parent shell process. If forked, of course they cannot.
981 * For example, 'unset foo | whatever' will parse and run, but foo will
982 * still be set at the end. */
983struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100984 const char *b_cmd;
985 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000986#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100987 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200988# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000989#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200990# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000991#endif
992};
993
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200994static const struct built_in_command bltins1[] = {
995 BLTIN("." , builtin_source , "Run commands in a file"),
996 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000997#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200998 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000999#endif
1000#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001001 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001002#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001003 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001004#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001005 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001006#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001007 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
1008 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
1009 BLTIN("exit" , builtin_exit , "Exit"),
1010 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001011#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001012 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001013#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001014#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001015 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001016#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +02001017#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02001018 BLTIN("history" , builtin_history , "Show command history"),
1019#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001020#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001021 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +00001022#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001023#if ENABLE_HUSH_KILL
1024 BLTIN("kill" , builtin_kill , "Send signals to processes"),
1025#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001026#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001027 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +02001028#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001029#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001030 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00001031#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001032#if ENABLE_HUSH_READ
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001033 BLTIN("read" , builtin_read , "Input into variable"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001034#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001035#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001036 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00001037#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001038#if ENABLE_HUSH_SET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001039 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001040#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001041 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +02001042#if ENABLE_HUSH_BASH_COMPAT
1043 BLTIN("source" , builtin_source , "Run commands in a file"),
1044#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001045#if ENABLE_HUSH_TRAP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001046 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001047#endif
Denys Vlasenko2bba5912014-03-14 12:43:57 +01001048 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001049#if ENABLE_HUSH_TYPE
Denys Vlasenko651a2692010-03-23 16:25:17 +01001050 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001051#endif
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001052#if ENABLE_HUSH_ULIMIT
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001053 BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001054#endif
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001055#if ENABLE_HUSH_UMASK
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001056 BLTIN("umask" , builtin_umask , "Set file creation mask"),
Denys Vlasenkod5933b12017-01-08 18:31:39 +01001057#endif
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001058#if ENABLE_HUSH_UNSET
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001059 BLTIN("unset" , builtin_unset , "Unset variables"),
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01001060#endif
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001061#if ENABLE_HUSH_WAIT
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001062 BLTIN("wait" , builtin_wait , "Wait for process"),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001063#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001064};
1065/* For now, echo and test are unconditionally enabled.
1066 * Maybe make it configurable? */
1067static const struct built_in_command bltins2[] = {
1068 BLTIN("[" , builtin_test , NULL),
1069 BLTIN("echo" , builtin_echo , NULL),
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01001070#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04001071 BLTIN("printf" , builtin_printf , NULL),
1072#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001073 BLTIN("pwd" , builtin_pwd , NULL),
1074 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001075};
1076
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001077
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001078/* Debug printouts.
1079 */
1080#if HUSH_DEBUG
1081/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001082# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001083# define debug_enter() (G.debug_indent++)
1084# define debug_leave() (G.debug_indent--)
1085#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001086# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001087# define debug_enter() ((void)0)
1088# define debug_leave() ((void)0)
1089#endif
1090
1091#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001092# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001093#endif
1094
1095#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001096# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001097#endif
1098
1099#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001100#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001101#endif
1102
1103#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001104# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001105#endif
1106
1107#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001108# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001109# define DEBUG_JOBS 1
1110#else
1111# define DEBUG_JOBS 0
1112#endif
1113
1114#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001115# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001116# define DEBUG_EXPAND 1
1117#else
1118# define DEBUG_EXPAND 0
1119#endif
1120
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001121#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001122# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001123#endif
1124
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001125#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001126# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001127# define DEBUG_GLOB 1
1128#else
1129# define DEBUG_GLOB 0
1130#endif
1131
1132#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001133# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001134#endif
1135
1136#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001137# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001138#endif
1139
1140#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001141# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001142# define DEBUG_CLEAN 1
1143#else
1144# define DEBUG_CLEAN 0
1145#endif
1146
1147#if DEBUG_EXPAND
1148static void debug_print_strings(const char *prefix, char **vv)
1149{
1150 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001151 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001152 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001153 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001154}
1155#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001156# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001157#endif
1158
1159
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001160/* Leak hunting. Use hush_leaktool.sh for post-processing.
1161 */
1162#if LEAK_HUNTING
1163static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001164{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001165 void *ptr = xmalloc((size + 0xff) & ~0xff);
1166 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1167 return ptr;
1168}
1169static void *xxrealloc(int lineno, void *ptr, size_t size)
1170{
1171 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1172 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1173 return ptr;
1174}
1175static char *xxstrdup(int lineno, const char *str)
1176{
1177 char *ptr = xstrdup(str);
1178 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1179 return ptr;
1180}
1181static void xxfree(void *ptr)
1182{
1183 fdprintf(2, "free %p\n", ptr);
1184 free(ptr);
1185}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001186# define xmalloc(s) xxmalloc(__LINE__, s)
1187# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1188# define xstrdup(s) xxstrdup(__LINE__, s)
1189# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001190#endif
1191
1192
1193/* Syntax and runtime errors. They always abort scripts.
1194 * In interactive use they usually discard unparsed and/or unexecuted commands
1195 * and return to the prompt.
1196 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1197 */
1198#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001199# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001200# define syntax_error(lineno, msg) syntax_error(msg)
1201# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1202# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1203# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1204# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001205#endif
1206
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001207static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001208{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001209 va_list p;
1210
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001211#if HUSH_DEBUG >= 2
1212 bb_error_msg("hush.c:%u", lineno);
1213#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001214 va_start(p, fmt);
1215 bb_verror_msg(fmt, p, NULL);
1216 va_end(p);
1217 if (!G_interactive_fd)
1218 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001219}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001220
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001221static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001222{
1223 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001224 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001225 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001226 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001227}
1228
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001229static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001230{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001231 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001232}
1233
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001234static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001235{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001236 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001237}
1238
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001239static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001240{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001241 char msg[2] = { ch, '\0' };
1242 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001243}
1244
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001245static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001246{
1247 char msg[2];
1248 msg[0] = ch;
1249 msg[1] = '\0';
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01001250#if HUSH_DEBUG >= 2
1251 bb_error_msg("hush.c:%u", lineno);
1252#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001253 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001254}
1255
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001256#if HUSH_DEBUG < 2
1257# undef die_if_script
1258# undef syntax_error
1259# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001260# undef syntax_error_unterm_ch
1261# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001262# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001263#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001264# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001265# define syntax_error(msg) syntax_error(__LINE__, msg)
1266# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1267# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1268# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1269# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001270#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001271
Denis Vlasenko552433b2009-04-04 19:29:21 +00001272
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001273#if ENABLE_HUSH_INTERACTIVE
1274static void cmdedit_update_prompt(void);
1275#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001276# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001277#endif
1278
1279
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001280/* Utility functions
1281 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001282/* Replace each \x with x in place, return ptr past NUL. */
1283static char *unbackslash(char *src)
1284{
Denys Vlasenko71885402009-09-24 01:44:13 +02001285 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001286 while (1) {
1287 if (*src == '\\')
1288 src++;
1289 if ((*dst++ = *src++) == '\0')
1290 break;
1291 }
1292 return dst;
1293}
1294
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001295static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001296{
1297 int i;
1298 unsigned count1;
1299 unsigned count2;
1300 char **v;
1301
1302 v = strings;
1303 count1 = 0;
1304 if (v) {
1305 while (*v) {
1306 count1++;
1307 v++;
1308 }
1309 }
1310 count2 = 0;
1311 v = add;
1312 while (*v) {
1313 count2++;
1314 v++;
1315 }
1316 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1317 v[count1 + count2] = NULL;
1318 i = count2;
1319 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001320 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001321 return v;
1322}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001323#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001324static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1325{
1326 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1327 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1328 return ptr;
1329}
1330#define add_strings_to_strings(strings, add, need_to_dup) \
1331 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1332#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001333
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001334/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001335static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001336{
1337 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001338 v[0] = add;
1339 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001340 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001341}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001342#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001343static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1344{
1345 char **ptr = add_string_to_strings(strings, add);
1346 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1347 return ptr;
1348}
1349#define add_string_to_strings(strings, add) \
1350 xx_add_string_to_strings(__LINE__, strings, add)
1351#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001352
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001353static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001354{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001355 char **v;
1356
1357 if (!strings)
1358 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001359 v = strings;
1360 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001361 free(*v);
1362 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001363 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001364 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001365}
1366
Denis Vlasenko76d50412008-06-10 16:19:39 +00001367
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001368static int xdup_and_close(int fd, int F_DUPFD_maybe_CLOEXEC)
1369{
1370 /* We avoid taking stdio fds. Mimicking ash: use fds above 9 */
1371 int newfd = fcntl(fd, F_DUPFD_maybe_CLOEXEC, 10);
1372 if (newfd < 0) {
1373 /* fd was not open? */
1374 if (errno == EBADF)
1375 return fd;
1376 xfunc_die();
1377 }
1378 close(fd);
1379 return newfd;
1380}
1381
1382
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001383/* Manipulating the list of open FILEs */
1384static FILE *remember_FILE(FILE *fp)
1385{
1386 if (fp) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001387 struct FILE_list *n = xmalloc(sizeof(*n));
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001388 n->next = G.FILE_list;
1389 G.FILE_list = n;
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001390 n->fp = fp;
1391 n->fd = fileno(fp);
1392 close_on_exec_on(n->fd);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001393 }
1394 return fp;
1395}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001396static void fclose_and_forget(FILE *fp)
1397{
1398 struct FILE_list **pp = &G.FILE_list;
1399 while (*pp) {
1400 struct FILE_list *cur = *pp;
1401 if (cur->fp == fp) {
1402 *pp = cur->next;
1403 free(cur);
1404 break;
1405 }
1406 pp = &cur->next;
1407 }
1408 fclose(fp);
1409}
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02001410static int save_FILEs_on_redirect(int fd)
1411{
1412 struct FILE_list *fl = G.FILE_list;
1413 while (fl) {
1414 if (fd == fl->fd) {
1415 /* We use it only on script files, they are all CLOEXEC */
1416 fl->fd = xdup_and_close(fd, F_DUPFD_CLOEXEC);
1417 return 1;
1418 }
1419 fl = fl->next;
1420 }
1421 return 0;
1422}
1423static void restore_redirected_FILEs(void)
1424{
1425 struct FILE_list *fl = G.FILE_list;
1426 while (fl) {
1427 int should_be = fileno(fl->fp);
1428 if (fl->fd != should_be) {
1429 xmove_fd(fl->fd, should_be);
1430 fl->fd = should_be;
1431 }
1432 fl = fl->next;
1433 }
1434}
1435#if ENABLE_FEATURE_SH_STANDALONE
1436static void close_all_FILE_list(void)
1437{
1438 struct FILE_list *fl = G.FILE_list;
1439 while (fl) {
1440 /* fclose would also free FILE object.
1441 * It is disastrous if we share memory with a vforked parent.
1442 * I'm not sure we never come here after vfork.
1443 * Therefore just close fd, nothing more.
1444 */
1445 /*fclose(fl->fp); - unsafe */
1446 close(fl->fd);
1447 fl = fl->next;
1448 }
1449}
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02001450#endif
1451
1452
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001453/* Helpers for setting new $n and restoring them back
1454 */
1455typedef struct save_arg_t {
1456 char *sv_argv0;
1457 char **sv_g_argv;
1458 int sv_g_argc;
1459 smallint sv_g_malloced;
1460} save_arg_t;
1461
1462static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1463{
1464 int n;
1465
1466 sv->sv_argv0 = argv[0];
1467 sv->sv_g_argv = G.global_argv;
1468 sv->sv_g_argc = G.global_argc;
1469 sv->sv_g_malloced = G.global_args_malloced;
1470
1471 argv[0] = G.global_argv[0]; /* retain $0 */
1472 G.global_argv = argv;
1473 G.global_args_malloced = 0;
1474
1475 n = 1;
1476 while (*++argv)
1477 n++;
1478 G.global_argc = n;
1479}
1480
1481static void restore_G_args(save_arg_t *sv, char **argv)
1482{
1483 char **pp;
1484
1485 if (G.global_args_malloced) {
1486 /* someone ran "set -- arg1 arg2 ...", undo */
1487 pp = G.global_argv;
1488 while (*++pp) /* note: does not free $0 */
1489 free(*pp);
1490 free(G.global_argv);
1491 }
1492 argv[0] = sv->sv_argv0;
1493 G.global_argv = sv->sv_g_argv;
1494 G.global_argc = sv->sv_g_argc;
1495 G.global_args_malloced = sv->sv_g_malloced;
1496}
1497
1498
Denis Vlasenkod5762932009-03-31 11:22:57 +00001499/* Basic theory of signal handling in shell
1500 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001501 * This does not describe what hush does, rather, it is current understanding
1502 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001503 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1504 *
1505 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1506 * is finished or backgrounded. It is the same in interactive and
1507 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001508 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001509 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001510 * backgrounds (i.e. stops) or kills all members of currently running
1511 * pipe.
1512 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001513 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001514 * or by SIGINT in interactive shell.
1515 *
1516 * Trap handlers will execute even within trap handlers. (right?)
1517 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001518 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1519 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001520 *
1521 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001522 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001523 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001524 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001525 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001526 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001527 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001528 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001529 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001530 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001531 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001532 *
1533 * SIGQUIT: ignore
1534 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001535 * SIGHUP (interactive):
1536 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001537 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001538 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1539 * that all pipe members are stopped. Try this in bash:
1540 * while :; do :; done - ^Z does not background it
1541 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001542 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001543 * of the command line, show prompt. NB: ^C does not send SIGINT
1544 * to interactive shell while shell is waiting for a pipe,
1545 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001546 * Example 1: this waits 5 sec, but does not execute ls:
1547 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1548 * Example 2: this does not wait and does not execute ls:
1549 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1550 * Example 3: this does not wait 5 sec, but executes ls:
1551 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001552 * Example 4: this does not wait and does not execute ls:
1553 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001554 *
1555 * (What happens to signals which are IGN on shell start?)
1556 * (What happens with signal mask on shell start?)
1557 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001558 * Old implementation
1559 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001560 * We use in-kernel pending signal mask to determine which signals were sent.
1561 * We block all signals which we don't want to take action immediately,
1562 * i.e. we block all signals which need to have special handling as described
1563 * above, and all signals which have traps set.
1564 * After each pipe execution, we extract any pending signals via sigtimedwait()
1565 * and act on them.
1566 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001567 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001568 * sigset_t blocked_set: current blocked signal set
1569 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001570 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001571 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001572 * "trap 'cmd' SIGxxx":
1573 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001574 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001575 * unblock signals with special interactive handling
1576 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001577 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001578 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001579 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001580 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001581 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001582 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001583 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001584 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001585 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001586 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001587 * Standard says "When a subshell is entered, traps that are not being ignored
1588 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001589 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001590 *
1591 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001592 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001593 * masked signals are not visible!
1594 *
1595 * New implementation
1596 * ==================
1597 * We record each signal we are interested in by installing signal handler
1598 * for them - a bit like emulating kernel pending signal mask in userspace.
1599 * We are interested in: signals which need to have special handling
1600 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001601 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001602 * After each pipe execution, we extract any pending signals
1603 * and act on them.
1604 *
1605 * unsigned special_sig_mask: a mask of shell-special signals.
1606 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1607 * char *traps[sig] if trap for sig is set (even if it's '').
1608 * sigset_t pending_set: set of sigs we received.
1609 *
1610 * "trap - SIGxxx":
1611 * if sig is in special_sig_mask, set handler back to:
1612 * record_pending_signo, or to IGN if it's a tty stop signal
1613 * if sig is in fatal_sig_mask, set handler back to sigexit.
1614 * else: set handler back to SIG_DFL
1615 * "trap 'cmd' SIGxxx":
1616 * set handler to record_pending_signo.
1617 * "trap '' SIGxxx":
1618 * set handler to SIG_IGN.
1619 * after [v]fork, if we plan to be a shell:
1620 * set signals with special interactive handling to SIG_DFL
1621 * (because child shell is not interactive),
1622 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1623 * after [v]fork, if we plan to exec:
1624 * POSIX says fork clears pending signal mask in child - no need to clear it.
1625 *
1626 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1627 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1628 *
1629 * Note (compat):
1630 * Standard says "When a subshell is entered, traps that are not being ignored
1631 * are set to the default actions". bash interprets it so that traps which
1632 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001633 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001634enum {
1635 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001636 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001637 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001638 | (1 << SIGHUP)
1639 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001640 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001641#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001642 | (1 << SIGTTIN)
1643 | (1 << SIGTTOU)
1644 | (1 << SIGTSTP)
1645#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001646 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001647};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001648
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001649static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001650{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001651 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001652#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001653 if (sig == SIGCHLD) {
1654 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001655//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 +02001656 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001657#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001658}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001659
Denys Vlasenko0806e402011-05-12 23:06:20 +02001660static sighandler_t install_sighandler(int sig, sighandler_t handler)
1661{
1662 struct sigaction old_sa;
1663
1664 /* We could use signal() to install handlers... almost:
1665 * except that we need to mask ALL signals while handlers run.
1666 * I saw signal nesting in strace, race window isn't small.
1667 * SA_RESTART is also needed, but in Linux, signal()
1668 * sets SA_RESTART too.
1669 */
1670 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1671 /* sigfillset(&G.sa.sa_mask); - already done */
1672 /* G.sa.sa_flags = SA_RESTART; - already done */
1673 G.sa.sa_handler = handler;
1674 sigaction(sig, &G.sa, &old_sa);
1675 return old_sa.sa_handler;
1676}
1677
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001678static void hush_exit(int exitcode) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001679
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001680static void restore_ttypgrp_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001681static void restore_ttypgrp_and__exit(void)
1682{
1683 /* xfunc has failed! die die die */
1684 /* no EXIT traps, this is an escape hatch! */
1685 G.exiting = 1;
1686 hush_exit(xfunc_error_retval);
1687}
1688
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001689#if ENABLE_HUSH_JOB
1690
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001691/* Needed only on some libc:
1692 * It was observed that on exit(), fgetc'ed buffered data
1693 * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
1694 * With the net effect that even after fork(), not vfork(),
1695 * exit() in NOEXECed applet in "sh SCRIPT":
1696 * noexec_applet_here
1697 * echo END_OF_SCRIPT
1698 * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
1699 * This makes "echo END_OF_SCRIPT" executed twice.
1700 * Similar problems can be seen with die_if_script() -> xfunc_die()
1701 * and in `cmd` handling.
1702 * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
1703 */
Denys Vlasenkob6afcc72016-12-12 16:30:20 +01001704static void fflush_and__exit(void) NORETURN;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001705static void fflush_and__exit(void)
1706{
1707 fflush_all();
1708 _exit(xfunc_error_retval);
1709}
1710
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001711/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001712# define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001713/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001714# define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001715
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001716/* Restores tty foreground process group, and exits.
1717 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001718 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001719 * or called directly with -EXITCODE.
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02001720 * We also call it if xfunc is exiting.
1721 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001722static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001723static void sigexit(int sig)
1724{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001725 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001726 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001727 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1728 /* Disable all signals: job control, SIGPIPE, etc.
1729 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1730 */
1731 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001732 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001733 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001734
1735 /* Not a signal, just exit */
1736 if (sig <= 0)
1737 _exit(- sig);
1738
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001739 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001740}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001741#else
1742
Denys Vlasenko8391c482010-05-22 17:50:43 +02001743# define disable_restore_tty_pgrp_on_exit() ((void)0)
1744# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001745
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001746#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001747
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001748static sighandler_t pick_sighandler(unsigned sig)
1749{
1750 sighandler_t handler = SIG_DFL;
1751 if (sig < sizeof(unsigned)*8) {
1752 unsigned sigmask = (1 << sig);
1753
1754#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001755 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001756 if (G_fatal_sig_mask & sigmask)
1757 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001758 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001759#endif
1760 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001761 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001762 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001763 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001764 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001765 * in an endless loop when we try to do some
1766 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001767 */
1768 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1769 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001770 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001771 }
1772 return handler;
1773}
1774
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001775/* Restores tty foreground process group, and exits. */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001776static void hush_exit(int exitcode)
1777{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001778#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1779 save_history(G.line_input_state);
1780#endif
1781
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001782 fflush_all();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001783 if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001784 char *argv[3];
1785 /* argv[0] is unused */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001786 argv[1] = G_traps[0];
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001787 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001788 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001789 /* Note: G_traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001790 * "trap" will still show it, if executed
1791 * in the handler */
1792 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001793 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001794
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001795#if ENABLE_FEATURE_CLEAN_UP
1796 {
1797 struct variable *cur_var;
1798 if (G.cwd != bb_msg_unknown)
1799 free((char*)G.cwd);
1800 cur_var = G.top_var;
1801 while (cur_var) {
1802 struct variable *tmp = cur_var;
1803 if (!cur_var->max_len)
1804 free(cur_var->varstr);
1805 cur_var = cur_var->next;
1806 free(tmp);
1807 }
1808 }
1809#endif
1810
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001811 fflush_all();
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001812#if ENABLE_HUSH_JOB
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001813 sigexit(- (exitcode & 0xff));
1814#else
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02001815 _exit(exitcode);
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001816#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001817}
1818
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001819
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001820//TODO: return a mask of ALL handled sigs?
1821static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001822{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001823 int last_sig = 0;
1824
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001825 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001826 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001827
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001828 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001829 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001830 sig = 0;
1831 do {
1832 sig++;
1833 if (sigismember(&G.pending_set, sig)) {
1834 sigdelset(&G.pending_set, sig);
1835 goto got_sig;
1836 }
1837 } while (sig < NSIG);
1838 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001839 got_sig:
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001840 if (G_traps && G_traps[sig]) {
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001841 debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001842 if (G_traps[sig][0]) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001843 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001844 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001845 char *argv[3];
1846 /* argv[0] is unused */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01001847 argv[1] = G_traps[sig];
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001848 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001849 save_rcode = G.last_exitcode;
1850 builtin_eval(argv);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01001851//FIXME: shouldn't it be set to 128 + sig instead?
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001852 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001853 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001854 } /* else: "" trap, ignoring signal */
1855 continue;
1856 }
1857 /* not a trap: special action */
1858 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001859 case SIGINT:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001860 debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001861 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001862 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001863 break;
1864#if ENABLE_HUSH_JOB
1865 case SIGHUP: {
1866 struct pipe *job;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001867 debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001868 /* bash is observed to signal whole process groups,
1869 * not individual processes */
1870 for (job = G.job_list; job; job = job->next) {
1871 if (job->pgrp <= 0)
1872 continue;
1873 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1874 if (kill(- job->pgrp, SIGHUP) == 0)
1875 kill(- job->pgrp, SIGCONT);
1876 }
1877 sigexit(SIGHUP);
1878 }
1879#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001880#if ENABLE_HUSH_FAST
1881 case SIGCHLD:
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001882 debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001883 G.count_SIGCHLD++;
1884//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1885 /* Note:
1886 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1887 * This simplifies wait builtin a bit.
1888 */
1889 break;
1890#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001891 default: /* ignored: */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02001892 debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001893 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001894 /* Note:
1895 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1896 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001897 * in interactive shell, because TERM is ignored.
1898 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001899 break;
1900 }
1901 }
1902 return last_sig;
1903}
1904
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001905
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001906static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001907{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001908 if (force || G.cwd == NULL) {
1909 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1910 * we must not try to free(bb_msg_unknown) */
1911 if (G.cwd == bb_msg_unknown)
1912 G.cwd = NULL;
1913 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1914 if (!G.cwd)
1915 G.cwd = bb_msg_unknown;
1916 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001917 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001918}
1919
Denis Vlasenko83506862007-11-23 13:11:42 +00001920
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001921/*
1922 * Shell and environment variable support
1923 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001924static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001925{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001926 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001927 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001928
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001929 pp = &G.top_var;
1930 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001931 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001932 return pp;
1933 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001934 }
1935 return NULL;
1936}
1937
Denys Vlasenko03dad222010-01-12 23:29:57 +01001938static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001939{
Denys Vlasenko29082232010-07-16 13:52:32 +02001940 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001941 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001942
1943 if (G.expanded_assignments) {
1944 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001945 while (*cpp) {
1946 char *cp = *cpp;
1947 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1948 return cp + len + 1;
1949 cpp++;
1950 }
1951 }
1952
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001953 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001954 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001955 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001956
Denys Vlasenkodea47882009-10-09 15:40:49 +02001957 if (strcmp(name, "PPID") == 0)
1958 return utoa(G.root_ppid);
1959 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001960#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001961 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001962 return utoa(next_random(&G.random_gen));
1963#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001964 return NULL;
1965}
1966
1967/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001968 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001969 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001970 * 0: do not change export flag
1971 * (if creating new variable, flag will be 0)
1972 * 1: set export flag and putenv the variable
1973 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001974 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001975 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001976#if !BB_MMU && ENABLE_HUSH_LOCAL
1977/* all params are used */
1978#elif BB_MMU && ENABLE_HUSH_LOCAL
1979#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1980 set_local_var(str, flg_export, local_lvl)
1981#elif BB_MMU && !ENABLE_HUSH_LOCAL
1982#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001983 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001984#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1985#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1986 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001987#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001988static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001989{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001990 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001991 struct variable *cur;
Denys Vlasenkoa7693902016-10-03 15:01:06 +02001992 char *free_me = NULL;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001993 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001994 int name_len;
1995
Denis Vlasenko950bd722009-04-21 11:23:56 +00001996 eq_sign = strchr(str, '=');
1997 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001998 free(str);
1999 return -1;
2000 }
2001
Denis Vlasenko950bd722009-04-21 11:23:56 +00002002 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02002003 var_pp = &G.top_var;
2004 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002005 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002006 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002007 continue;
2008 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002009
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002010 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002011 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002012#if !BB_MMU
2013 if (!flg_read_only)
2014#endif
2015 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002016 free(str);
2017 return -1;
2018 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002019 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00002020 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2021 *eq_sign = '\0';
2022 unsetenv(str);
2023 *eq_sign = '=';
2024 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002025#if ENABLE_HUSH_LOCAL
2026 if (cur->func_nest_level < local_lvl) {
2027 /* New variable is declared as local,
2028 * and existing one is global, or local
2029 * from enclosing function.
2030 * Remove and save old one: */
2031 *var_pp = cur->next;
2032 cur->next = *G.shadowed_vars_pp;
2033 *G.shadowed_vars_pp = cur;
2034 /* bash 3.2.33(1) and exported vars:
2035 * # export z=z
2036 * # f() { local z=a; env | grep ^z; }
2037 * # f
2038 * z=a
2039 * # env | grep ^z
2040 * z=z
2041 */
2042 if (cur->flg_export)
2043 flg_export = 1;
2044 break;
2045 }
2046#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00002047 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002048 free_and_exp:
2049 free(str);
2050 goto exp;
2051 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002052 if (cur->max_len != 0) {
2053 if (cur->max_len >= strlen(str)) {
2054 /* This one is from startup env, reuse space */
2055 strcpy(cur->varstr, str);
2056 goto free_and_exp;
2057 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002058 /* Can't reuse */
2059 cur->max_len = 0;
2060 goto set_str_and_exp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02002061 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002062 /* max_len == 0 signifies "malloced" var, which we can
2063 * (and have to) free. But we can't free(cur->varstr) here:
2064 * if cur->flg_export is 1, it is in the environment.
2065 * We should either unsetenv+free, or wait until putenv,
2066 * then putenv(new)+free(old).
2067 */
2068 free_me = cur->varstr;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002069 goto set_str_and_exp;
2070 }
2071
Denys Vlasenko295fef82009-06-03 12:47:26 +02002072 /* Not found - create new variable struct */
2073 cur = xzalloc(sizeof(*cur));
2074#if ENABLE_HUSH_LOCAL
2075 cur->func_nest_level = local_lvl;
2076#endif
2077 cur->next = *var_pp;
2078 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002079
2080 set_str_and_exp:
2081 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002082#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002083 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002084#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002085 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00002086 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002087 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002088 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2089 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002090 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002091 if (flg_export == -1) {
2092 cur->flg_export = 0;
2093 /* unsetenv was already done */
2094 } else {
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002095 int i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002096 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002097 i = putenv(cur->varstr);
2098 /* only now we can free old exported malloced string */
2099 free(free_me);
2100 return i;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002101 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002102 }
Denys Vlasenkoa7693902016-10-03 15:01:06 +02002103 free(free_me);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002104 return 0;
2105}
2106
Denys Vlasenko6db47842009-09-05 20:15:17 +02002107/* Used at startup and after each cd */
2108static void set_pwd_var(int exp)
2109{
2110 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
2111 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
2112}
2113
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002114static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002115{
2116 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002117 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002118
2119 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00002120 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002121 var_pp = &G.top_var;
2122 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002123 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2124 if (cur->flg_read_only) {
2125 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00002126 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002127 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002128 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002129 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2130 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002131 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
2132 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002133 if (!cur->max_len)
2134 free(cur->varstr);
2135 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00002136 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002137 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002138 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002139 }
Mike Frysingerd690f682009-03-30 06:50:54 +00002140 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002141}
2142
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002143#if ENABLE_HUSH_UNSET
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002144static int unset_local_var(const char *name)
2145{
2146 return unset_local_var_len(name, strlen(name));
2147}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01002148#endif
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002149
2150static void unset_vars(char **strings)
2151{
2152 char **v;
2153
2154 if (!strings)
2155 return;
2156 v = strings;
2157 while (*v) {
2158 const char *eq = strchrnul(*v, '=');
2159 unset_local_var_len(*v, (int)(eq - *v));
2160 v++;
2161 }
2162 free(strings);
2163}
2164
Denys Vlasenko03dad222010-01-12 23:29:57 +01002165static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00002166{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002167 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01002168 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00002169}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002170
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002171
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002172/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002173 * Helpers for "var1=val1 var2=val2 cmd" feature
2174 */
2175static void add_vars(struct variable *var)
2176{
2177 struct variable *next;
2178
2179 while (var) {
2180 next = var->next;
2181 var->next = G.top_var;
2182 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002183 if (var->flg_export) {
2184 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002185 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002186 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02002187 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002188 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002189 var = next;
2190 }
2191}
2192
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002193static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002194{
2195 char **s;
2196 struct variable *old = NULL;
2197
2198 if (!strings)
2199 return old;
2200 s = strings;
2201 while (*s) {
2202 struct variable *var_p;
2203 struct variable **var_pp;
2204 char *eq;
2205
2206 eq = strchr(*s, '=');
2207 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002208 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002209 if (var_pp) {
2210 /* Remove variable from global linked list */
2211 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02002212 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002213 *var_pp = var_p->next;
2214 /* Add it to returned list */
2215 var_p->next = old;
2216 old = var_p;
2217 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02002218 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002219 }
2220 s++;
2221 }
2222 return old;
2223}
2224
2225
2226/*
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002227 * Unicode helper
2228 */
2229static void reinit_unicode_for_hush(void)
2230{
2231 /* Unicode support should be activated even if LANG is set
2232 * _during_ shell execution, not only if it was set when
2233 * shell was started. Therefore, re-check LANG every time:
2234 */
Denys Vlasenko841f8332014-08-13 10:09:49 +02002235 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2236 || ENABLE_UNICODE_USING_LOCALE
2237 ) {
2238 const char *s = get_local_var_value("LC_ALL");
2239 if (!s) s = get_local_var_value("LC_CTYPE");
2240 if (!s) s = get_local_var_value("LANG");
2241 reinit_unicode(s);
2242 }
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002243}
2244
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002245/*
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002246 * in_str support (strings, and "strings" read from files).
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002247 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002248
2249#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenko4074d492016-09-30 01:49:53 +02002250/* To test correct lineedit/interactive behavior, type from command line:
2251 * echo $P\
2252 * \
2253 * AT\
2254 * H\
2255 * \
2256 * It excercises a lot of corner cases.
2257 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002258static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002259{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002260 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002261 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002262 if (G.PS1 == NULL)
2263 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002264 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002265 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002266 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002267 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002268 if (G.PS2 == NULL)
2269 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002270}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002271static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002272{
2273 const char *prompt_str;
2274 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002275 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2276 /* Set up the prompt */
2277 if (promptmode == 0) { /* PS1 */
2278 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002279 /* bash uses $PWD value, even if it is set by user.
2280 * It uses current dir only if PWD is unset.
2281 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002282 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002283 prompt_str = G.PS1;
2284 } else
2285 prompt_str = G.PS2;
2286 } else
2287 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denys Vlasenko4074d492016-09-30 01:49:53 +02002288 debug_printf("prompt_str '%s'\n", prompt_str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002289 return prompt_str;
2290}
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002291static int get_user_input(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002292{
2293 int r;
2294 const char *prompt_str;
2295
2296 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002297# if ENABLE_FEATURE_EDITING
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002298 for (;;) {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02002299 reinit_unicode_for_hush();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002300 if (G.flag_SIGINT) {
2301 /* There was ^C'ed, make it look prettier: */
2302 bb_putchar('\n');
2303 G.flag_SIGINT = 0;
2304 }
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002305 /* buglet: SIGINT will not make new prompt to appear _at once_,
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002306 * only after <Enter>. (^C works immediately) */
Denys Vlasenko0448c552016-09-29 20:25:44 +02002307 r = read_line_input(G.line_input_state, prompt_str,
2308 G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1,
2309 /*timeout*/ -1
2310 );
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002311 /* read_line_input intercepts ^C, "convert" it to SIGINT */
2312 if (r == 0) {
2313 write(STDOUT_FILENO, "^C", 2);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002314 raise(SIGINT);
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002315 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002316 check_and_run_traps();
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002317 if (r != 0 && !G.flag_SIGINT)
2318 break;
2319 /* ^C or SIGINT: repeat */
2320 G.last_exitcode = 128 + SIGINT;
2321 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002322 if (r < 0) {
2323 /* EOF/error detected */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002324 i->p = NULL;
2325 i->peek_buf[0] = r = EOF;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002326 return r;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002327 }
Denys Vlasenko4074d492016-09-30 01:49:53 +02002328 i->p = G.user_input_buf;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002329 return (unsigned char)*i->p++;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002330# else
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002331 for (;;) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002332 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002333 if (i->last_char == '\0' || i->last_char == '\n') {
2334 /* Why check_and_run_traps here? Try this interactively:
2335 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2336 * $ <[enter], repeatedly...>
2337 * Without check_and_run_traps, handler never runs.
2338 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002339 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002340 fputs(prompt_str, stdout);
2341 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002342 fflush_all();
Denys Vlasenko4b89d512016-11-25 03:41:03 +01002343//FIXME: here ^C or SIGINT will have effect only after <Enter>
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002344 r = fgetc(i->file);
Denys Vlasenko8660aeb2016-11-24 17:44:02 +01002345 /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
2346 * no ^C masking happens during fgetc, no special code for ^C:
2347 * it generates SIGINT as usual.
2348 */
2349 check_and_run_traps();
2350 if (G.flag_SIGINT)
2351 G.last_exitcode = 128 + SIGINT;
2352 if (r != '\0')
2353 break;
2354 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002355 return r;
Denys Vlasenko8391c482010-05-22 17:50:43 +02002356# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002357}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002358/* This is the magic location that prints prompts
2359 * and gets data back from the user */
Denys Vlasenko4074d492016-09-30 01:49:53 +02002360static int fgetc_interactive(struct in_str *i)
2361{
2362 int ch;
2363 /* If it's interactive stdin, get new line. */
2364 if (G_interactive_fd && i->file == stdin) {
2365 /* Returns first char (or EOF), the rest is in i->p[] */
2366 ch = get_user_input(i);
2367 i->promptmode = 1; /* PS2 */
2368 } else {
2369 /* Not stdin: script file, sourced file, etc */
2370 do ch = fgetc(i->file); while (ch == '\0');
2371 }
2372 return ch;
2373}
2374#else
2375static inline int fgetc_interactive(struct in_str *i)
2376{
2377 int ch;
2378 do ch = fgetc(i->file); while (ch == '\0');
2379 return ch;
2380}
2381#endif /* INTERACTIVE */
2382
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002383static int i_getch(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002384{
2385 int ch;
2386
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002387 if (!i->file) {
2388 /* string-based in_str */
2389 ch = (unsigned char)*i->p;
2390 if (ch != '\0') {
2391 i->p++;
2392 i->last_char = ch;
2393 return ch;
2394 }
2395 return EOF;
2396 }
2397
2398 /* FILE-based in_str */
2399
Denys Vlasenko4074d492016-09-30 01:49:53 +02002400#if ENABLE_FEATURE_EDITING
2401 /* This can be stdin, check line editing char[] buffer */
2402 if (i->p && *i->p != '\0') {
2403 ch = (unsigned char)*i->p++;
2404 goto out;
2405 }
2406#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002407 /* peek_buf[] is an int array, not char. Can contain EOF. */
2408 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002409 if (ch != 0) {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002410 int ch2 = i->peek_buf[1];
2411 i->peek_buf[0] = ch2;
2412 if (ch2 == 0) /* very likely, avoid redundant write */
2413 goto out;
2414 i->peek_buf[1] = 0;
2415 goto out;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002416 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002417
Denys Vlasenko4074d492016-09-30 01:49:53 +02002418 ch = fgetc_interactive(i);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002419 out:
Denis Vlasenko913a2012009-04-05 22:17:04 +00002420 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002421 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002422 return ch;
2423}
2424
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002425static int i_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002426{
2427 int ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002428
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002429 if (!i->file) {
2430 /* string-based in_str */
2431 /* Doesn't report EOF on NUL. None of the callers care. */
2432 return (unsigned char)*i->p;
2433 }
2434
2435 /* FILE-based in_str */
2436
Denys Vlasenko4074d492016-09-30 01:49:53 +02002437#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002438 /* This can be stdin, check line editing char[] buffer */
2439 if (i->p && *i->p != '\0')
2440 return (unsigned char)*i->p;
2441#endif
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002442 /* peek_buf[] is an int array, not char. Can contain EOF. */
2443 ch = i->peek_buf[0];
Denys Vlasenko4074d492016-09-30 01:49:53 +02002444 if (ch != 0)
2445 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002446
Denys Vlasenko4074d492016-09-30 01:49:53 +02002447 /* Need to get a new char */
2448 ch = fgetc_interactive(i);
2449 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2450
2451 /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
2452#if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
2453 if (i->p) {
2454 i->p -= 1;
2455 return ch;
2456 }
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002457#endif
Denys Vlasenko4074d492016-09-30 01:49:53 +02002458 i->peek_buf[0] = ch;
2459 /*i->peek_buf[1] = 0; - already is */
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002460 return ch;
2461}
2462
Denys Vlasenko4074d492016-09-30 01:49:53 +02002463/* Only ever called if i_peek() was called, and did not return EOF.
2464 * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
2465 * not end-of-line. Therefore we never need to read a new editing line here.
2466 */
2467static int i_peek2(struct in_str *i)
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002468{
Denys Vlasenko4074d492016-09-30 01:49:53 +02002469 int ch;
2470
2471 /* There are two cases when i->p[] buffer exists.
2472 * (1) it's a string in_str.
Denys Vlasenko08755f92016-09-30 02:02:25 +02002473 * (2) It's a file, and we have a saved line editing buffer.
Denys Vlasenko4074d492016-09-30 01:49:53 +02002474 * In both cases, we know that i->p[0] exists and not NUL, and
2475 * the peek2 result is in i->p[1].
2476 */
2477 if (i->p)
2478 return (unsigned char)i->p[1];
2479
2480 /* Now we know it is a file-based in_str. */
2481
2482 /* peek_buf[] is an int array, not char. Can contain EOF. */
2483 /* Is there 2nd char? */
2484 ch = i->peek_buf[1];
2485 if (ch == 0) {
2486 /* We did not read it yet, get it now */
2487 do ch = fgetc(i->file); while (ch == '\0');
2488 i->peek_buf[1] = ch;
2489 }
2490
2491 debug_printf("file_peek2: got '%c' %d\n", ch, ch);
2492 return ch;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02002493}
2494
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002495static void setup_file_in_str(struct in_str *i, FILE *f)
2496{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002497 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002498 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002499 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002500 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002501}
2502
2503static void setup_string_in_str(struct in_str *i, const char *s)
2504{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002505 memset(i, 0, sizeof(*i));
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002506 /* i->promptmode = 0; - PS1 (memset did it) */
Denys Vlasenko87e039d2016-11-08 22:35:05 +01002507 /*i->file = NULL */;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002508 i->p = s;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002509}
2510
2511
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002512/*
2513 * o_string support
2514 */
2515#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002516
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002517static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002518{
2519 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002520 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002521 if (o->data)
2522 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002523}
2524
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002525static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002526{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002527 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002528 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002529}
2530
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002531static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2532{
2533 free(o->data);
2534}
2535
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002536static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002537{
2538 if (o->length + len > o->maxlen) {
Denys Vlasenko46e64982016-09-29 19:50:55 +02002539 o->maxlen += (2 * len) | (B_CHUNK-1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002540 o->data = xrealloc(o->data, 1 + o->maxlen);
2541 }
2542}
2543
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002544static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002545{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002546 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002547 if (o->length < o->maxlen) {
2548 /* likely. avoid o_grow_by() call */
2549 add:
2550 o->data[o->length] = ch;
2551 o->length++;
2552 o->data[o->length] = '\0';
2553 return;
2554 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002555 o_grow_by(o, 1);
Denys Vlasenko46e64982016-09-29 19:50:55 +02002556 goto add;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002557}
2558
Denys Vlasenko657086a2016-09-29 18:07:42 +02002559#if 0
2560/* Valid only if we know o_string is not empty */
2561static void o_delchr(o_string *o)
2562{
2563 o->length--;
2564 o->data[o->length] = '\0';
2565}
2566#endif
2567
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002568static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002569{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002570 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002571 memcpy(&o->data[o->length], str, len);
2572 o->length += len;
2573 o->data[o->length] = '\0';
2574}
2575
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002576static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002577{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002578 o_addblock(o, str, strlen(str));
2579}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002580
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002581#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002582static void nommu_addchr(o_string *o, int ch)
2583{
2584 if (o)
2585 o_addchr(o, ch);
2586}
2587#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002588# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002589#endif
2590
2591static void o_addstr_with_NUL(o_string *o, const char *str)
2592{
2593 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002594}
2595
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002596/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002597 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002598 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2599 * Apparently, on unquoted $v bash still does globbing
2600 * ("v='*.txt'; echo $v" prints all .txt files),
2601 * but NOT brace expansion! Thus, there should be TWO independent
2602 * quoting mechanisms on $v expansion side: one protects
2603 * $v from brace expansion, and other additionally protects "$v" against globbing.
2604 * We have only second one.
2605 */
2606
Denys Vlasenko9e800222010-10-03 14:28:04 +02002607#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002608# define MAYBE_BRACES "{}"
2609#else
2610# define MAYBE_BRACES ""
2611#endif
2612
Eric Andersen25f27032001-04-26 23:22:31 +00002613/* My analysis of quoting semantics tells me that state information
2614 * is associated with a destination, not a source.
2615 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002616static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002617{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002618 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002619 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002620 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002621 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002622 o_grow_by(o, sz);
2623 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002624 o->data[o->length] = '\\';
2625 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002626 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002627 o->data[o->length] = ch;
2628 o->length++;
2629 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002630}
2631
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002632static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002633{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002634 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002635 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2636 && strchr("*?[\\" MAYBE_BRACES, ch)
2637 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002638 sz++;
2639 o->data[o->length] = '\\';
2640 o->length++;
2641 }
2642 o_grow_by(o, sz);
2643 o->data[o->length] = ch;
2644 o->length++;
2645 o->data[o->length] = '\0';
2646}
2647
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002648static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002649{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002650 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002651 char ch;
2652 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002653 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002654 if (ordinary_cnt > len) /* paranoia */
2655 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002656 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002657 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002658 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002659 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002660 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002661
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002662 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002663 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002664 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002665 sz++;
2666 o->data[o->length] = '\\';
2667 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002668 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002669 o_grow_by(o, sz);
2670 o->data[o->length] = ch;
2671 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002672 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002673 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002674}
2675
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002676static void o_addQblock(o_string *o, const char *str, int len)
2677{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002678 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002679 o_addblock(o, str, len);
2680 return;
2681 }
2682 o_addqblock(o, str, len);
2683}
2684
Denys Vlasenko38292b62010-09-05 14:49:40 +02002685static void o_addQstr(o_string *o, const char *str)
2686{
2687 o_addQblock(o, str, strlen(str));
2688}
2689
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002690/* A special kind of o_string for $VAR and `cmd` expansion.
2691 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002692 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002693 * list[i] contains an INDEX (int!) into this string data.
2694 * It means that if list[] needs to grow, data needs to be moved higher up
2695 * but list[i]'s need not be modified.
2696 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002697 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002698 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2699 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002700#if DEBUG_EXPAND || DEBUG_GLOB
2701static void debug_print_list(const char *prefix, o_string *o, int n)
2702{
2703 char **list = (char**)o->data;
2704 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2705 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002706
2707 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002708 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 +02002709 prefix, list, n, string_start, o->length, o->maxlen,
2710 !!(o->o_expflags & EXP_FLAG_GLOB),
2711 o->has_quoted_part,
2712 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002713 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002714 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002715 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2716 o->data + (int)(uintptr_t)list[i] + string_start,
2717 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002718 i++;
2719 }
2720 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002721 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002722 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002723 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002724 }
2725}
2726#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002727# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002728#endif
2729
2730/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2731 * in list[n] so that it points past last stored byte so far.
2732 * It returns n+1. */
2733static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002734{
2735 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002736 int string_start;
2737 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002738
2739 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002740 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2741 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002742 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002743 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002744 /* list[n] points to string_start, make space for 16 more pointers */
2745 o->maxlen += 0x10 * sizeof(list[0]);
2746 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002747 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002748 memmove(list + n + 0x10, list + n, string_len);
2749 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002750 } else {
2751 debug_printf_list("list[%d]=%d string_start=%d\n",
2752 n, string_len, string_start);
2753 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002754 } else {
2755 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002756 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2757 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002758 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2759 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002760 o->has_empty_slot = 0;
2761 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002762 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002763 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002764 return n + 1;
2765}
2766
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002767/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002768static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002769{
2770 char **list = (char**)o->data;
2771 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2772
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002773 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002774}
2775
Denys Vlasenko9e800222010-10-03 14:28:04 +02002776#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002777/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2778 * first, it processes even {a} (no commas), second,
2779 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002780 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002781 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002782
2783/* Helper */
2784static int glob_needed(const char *s)
2785{
2786 while (*s) {
2787 if (*s == '\\') {
2788 if (!s[1])
2789 return 0;
2790 s += 2;
2791 continue;
2792 }
2793 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2794 return 1;
2795 s++;
2796 }
2797 return 0;
2798}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002799/* Return pointer to next closing brace or to comma */
2800static const char *next_brace_sub(const char *cp)
2801{
2802 unsigned depth = 0;
2803 cp++;
2804 while (*cp != '\0') {
2805 if (*cp == '\\') {
2806 if (*++cp == '\0')
2807 break;
2808 cp++;
2809 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002810 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002811 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002812 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002813 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002814 depth++;
2815 }
2816
2817 return *cp != '\0' ? cp : NULL;
2818}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002819/* Recursive brace globber. Note: may garble pattern[]. */
2820static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002821{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002822 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002823 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002824 const char *next;
2825 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002826 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002827 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002828
2829 debug_printf_glob("glob_brace('%s')\n", pattern);
2830
2831 begin = pattern;
2832 while (1) {
2833 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002834 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002835 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002836 /* Find the first sub-pattern and at the same time
2837 * find the rest after the closing brace */
2838 next = next_brace_sub(begin);
2839 if (next == NULL) {
2840 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002841 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002842 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002843 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002844 /* "{abc}" with no commas - illegal
2845 * brace expr, disregard and skip it */
2846 begin = next + 1;
2847 continue;
2848 }
2849 break;
2850 }
2851 if (*begin == '\\' && begin[1] != '\0')
2852 begin++;
2853 begin++;
2854 }
2855 debug_printf_glob("begin:%s\n", begin);
2856 debug_printf_glob("next:%s\n", next);
2857
2858 /* Now find the end of the whole brace expression */
2859 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002860 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002861 rest = next_brace_sub(rest);
2862 if (rest == NULL) {
2863 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002864 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002865 }
2866 debug_printf_glob("rest:%s\n", rest);
2867 }
2868 rest_len = strlen(++rest) + 1;
2869
2870 /* We are sure the brace expression is well-formed */
2871
2872 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002873 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002874
2875 /* We have a brace expression. BEGIN points to the opening {,
2876 * NEXT points past the terminator of the first element, and REST
2877 * points past the final }. We will accumulate result names from
2878 * recursive runs for each brace alternative in the buffer using
2879 * GLOB_APPEND. */
2880
2881 p = begin + 1;
2882 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002883 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002884 memcpy(
2885 mempcpy(
2886 mempcpy(new_pattern_buf,
2887 /* We know the prefix for all sub-patterns */
2888 pattern, begin - pattern),
2889 p, next - p),
2890 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002891
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002892 /* Note: glob_brace() may garble new_pattern_buf[].
2893 * That's why we re-copy prefix every time (1st memcpy above).
2894 */
2895 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002896 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002897 /* We saw the last entry */
2898 break;
2899 }
2900 p = next + 1;
2901 next = next_brace_sub(next);
2902 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002903 free(new_pattern_buf);
2904 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002905
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002906 simple_glob:
2907 {
2908 int gr;
2909 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002910
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002911 memset(&globdata, 0, sizeof(globdata));
2912 gr = glob(pattern, 0, NULL, &globdata);
2913 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2914 if (gr != 0) {
2915 if (gr == GLOB_NOMATCH) {
2916 globfree(&globdata);
2917 /* NB: garbles parameter */
2918 unbackslash(pattern);
2919 o_addstr_with_NUL(o, pattern);
2920 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2921 return o_save_ptr_helper(o, n);
2922 }
2923 if (gr == GLOB_NOSPACE)
2924 bb_error_msg_and_die(bb_msg_memory_exhausted);
2925 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2926 * but we didn't specify it. Paranoia again. */
2927 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2928 }
2929 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2930 char **argv = globdata.gl_pathv;
2931 while (1) {
2932 o_addstr_with_NUL(o, *argv);
2933 n = o_save_ptr_helper(o, n);
2934 argv++;
2935 if (!*argv)
2936 break;
2937 }
2938 }
2939 globfree(&globdata);
2940 }
2941 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002942}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002943/* Performs globbing on last list[],
2944 * saving each result as a new list[].
2945 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002946static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002947{
2948 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002949
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002950 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002951 if (!o->data)
2952 return o_save_ptr_helper(o, n);
2953 pattern = o->data + o_get_last_ptr(o, n);
2954 debug_printf_glob("glob pattern '%s'\n", pattern);
2955 if (!glob_needed(pattern)) {
2956 /* unbackslash last string in o in place, fix length */
2957 o->length = unbackslash(pattern) - o->data;
2958 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2959 return o_save_ptr_helper(o, n);
2960 }
2961
2962 copy = xstrdup(pattern);
2963 /* "forget" pattern in o */
2964 o->length = pattern - o->data;
2965 n = glob_brace(copy, o, n);
2966 free(copy);
2967 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002968 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002969 return n;
2970}
2971
Denys Vlasenko238081f2010-10-03 14:26:26 +02002972#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002973
2974/* Helper */
2975static int glob_needed(const char *s)
2976{
2977 while (*s) {
2978 if (*s == '\\') {
2979 if (!s[1])
2980 return 0;
2981 s += 2;
2982 continue;
2983 }
2984 if (*s == '*' || *s == '[' || *s == '?')
2985 return 1;
2986 s++;
2987 }
2988 return 0;
2989}
2990/* Performs globbing on last list[],
2991 * saving each result as a new list[].
2992 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002993static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002994{
2995 glob_t globdata;
2996 int gr;
2997 char *pattern;
2998
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002999 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003000 if (!o->data)
3001 return o_save_ptr_helper(o, n);
3002 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003003 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003004 if (!glob_needed(pattern)) {
3005 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003006 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003007 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003008 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003009 return o_save_ptr_helper(o, n);
3010 }
3011
3012 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003013 /* Can't use GLOB_NOCHECK: it does not unescape the string.
3014 * If we glob "*.\*" and don't find anything, we need
3015 * to fall back to using literal "*.*", but GLOB_NOCHECK
3016 * will return "*.\*"!
3017 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003018 gr = glob(pattern, 0, NULL, &globdata);
3019 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003020 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003021 if (gr == GLOB_NOMATCH) {
3022 globfree(&globdata);
3023 goto literal;
3024 }
3025 if (gr == GLOB_NOSPACE)
3026 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01003027 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
3028 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003029 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003030 }
3031 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
3032 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003033 /* "forget" pattern in o */
3034 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003035 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003036 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003037 n = o_save_ptr_helper(o, n);
3038 argv++;
3039 if (!*argv)
3040 break;
3041 }
3042 }
3043 globfree(&globdata);
3044 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003045 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003046 return n;
3047}
3048
Denys Vlasenko238081f2010-10-03 14:26:26 +02003049#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01003050
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003051/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003052 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003053static int o_save_ptr(o_string *o, int n)
3054{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003055 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003056 /* If o->has_empty_slot, list[n] was already globbed
3057 * (if it was requested back then when it was filled)
3058 * so don't do that again! */
3059 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02003060 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00003061 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003062 return o_save_ptr_helper(o, n);
3063}
3064
3065/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003066static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003067{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003068 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003069 int string_start;
3070
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003071 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
3072 if (DEBUG_EXPAND)
3073 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003074 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003075 list = (char**)o->data;
3076 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
3077 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003078 while (n) {
3079 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003080 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003081 }
3082 return list;
3083}
3084
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003085static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003086
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003087/* Returns pi->next - next pipe in the list */
3088static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003089{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003090 struct pipe *next;
3091 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003092
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003093 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003094 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003095 struct command *command;
3096 struct redir_struct *r, *rnext;
3097
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003098 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003099 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003100 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003101 if (DEBUG_CLEAN) {
3102 int a;
3103 char **p;
3104 for (a = 0, p = command->argv; *p; a++, p++) {
3105 debug_printf_clean(" argv[%d] = %s\n", a, *p);
3106 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003107 }
3108 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003109 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003110 }
3111 /* not "else if": on syntax error, we may have both! */
3112 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003113 debug_printf_clean(" begin group (cmd_type:%d)\n",
3114 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003115 free_pipe_list(command->group);
3116 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003117 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003118 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003119 /* else is crucial here.
3120 * If group != NULL, child_func is meaningless */
3121#if ENABLE_HUSH_FUNCTIONS
3122 else if (command->child_func) {
3123 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3124 command->child_func->parent_cmd = NULL;
3125 }
3126#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003127#if !BB_MMU
3128 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003129 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003130#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003131 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003132 debug_printf_clean(" redirect %d%s",
3133 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003134 /* guard against the case >$FOO, where foo is unset or blank */
3135 if (r->rd_filename) {
3136 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3137 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003138 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003139 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003140 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003141 rnext = r->next;
3142 free(r);
3143 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003144 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003145 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003146 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003147 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003148#if ENABLE_HUSH_JOB
3149 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003150 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003151#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003152
3153 next = pi->next;
3154 free(pi);
3155 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003156}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003157
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003158static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003159{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003160 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003161#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003162 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003163#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003164 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02003165 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003166 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003167}
3168
3169
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003170/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003171
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003172#ifndef debug_print_tree
3173static void debug_print_tree(struct pipe *pi, int lvl)
3174{
3175 static const char *const PIPE[] = {
3176 [PIPE_SEQ] = "SEQ",
3177 [PIPE_AND] = "AND",
3178 [PIPE_OR ] = "OR" ,
3179 [PIPE_BG ] = "BG" ,
3180 };
3181 static const char *RES[] = {
3182 [RES_NONE ] = "NONE" ,
3183# if ENABLE_HUSH_IF
3184 [RES_IF ] = "IF" ,
3185 [RES_THEN ] = "THEN" ,
3186 [RES_ELIF ] = "ELIF" ,
3187 [RES_ELSE ] = "ELSE" ,
3188 [RES_FI ] = "FI" ,
3189# endif
3190# if ENABLE_HUSH_LOOPS
3191 [RES_FOR ] = "FOR" ,
3192 [RES_WHILE] = "WHILE",
3193 [RES_UNTIL] = "UNTIL",
3194 [RES_DO ] = "DO" ,
3195 [RES_DONE ] = "DONE" ,
3196# endif
3197# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3198 [RES_IN ] = "IN" ,
3199# endif
3200# if ENABLE_HUSH_CASE
3201 [RES_CASE ] = "CASE" ,
3202 [RES_CASE_IN ] = "CASE_IN" ,
3203 [RES_MATCH] = "MATCH",
3204 [RES_CASE_BODY] = "CASE_BODY",
3205 [RES_ESAC ] = "ESAC" ,
3206# endif
3207 [RES_XXXX ] = "XXXX" ,
3208 [RES_SNTX ] = "SNTX" ,
3209 };
3210 static const char *const CMDTYPE[] = {
3211 "{}",
3212 "()",
3213 "[noglob]",
3214# if ENABLE_HUSH_FUNCTIONS
3215 "func()",
3216# endif
3217 };
3218
3219 int pin, prn;
3220
3221 pin = 0;
3222 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003223 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003224 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3225 prn = 0;
3226 while (prn < pi->num_cmds) {
3227 struct command *command = &pi->cmds[prn];
3228 char **argv = command->argv;
3229
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003230 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003231 lvl*2, "", prn,
3232 command->assignment_cnt);
3233 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003234 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003235 CMDTYPE[command->cmd_type],
3236 argv
3237# if !BB_MMU
3238 , " group_as_string:", command->group_as_string
3239# else
3240 , "", ""
3241# endif
3242 );
3243 debug_print_tree(command->group, lvl+1);
3244 prn++;
3245 continue;
3246 }
3247 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003248 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003249 argv++;
3250 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01003251 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01003252 prn++;
3253 }
3254 pi = pi->next;
3255 pin++;
3256 }
3257}
3258#endif /* debug_print_tree */
3259
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003260static struct pipe *new_pipe(void)
3261{
Eric Andersen25f27032001-04-26 23:22:31 +00003262 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003263 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003264 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003265 return pi;
3266}
3267
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003268/* Command (member of a pipe) is complete, or we start a new pipe
3269 * if ctx->command is NULL.
3270 * No errors possible here.
3271 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003272static int done_command(struct parse_context *ctx)
3273{
3274 /* The command is really already in the pipe structure, so
3275 * advance the pipe counter and make a new, null command. */
3276 struct pipe *pi = ctx->pipe;
3277 struct command *command = ctx->command;
3278
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003279#if 0 /* Instead we emit error message at run time */
3280 if (ctx->pending_redirect) {
3281 /* For example, "cmd >" (no filename to redirect to) */
3282 die_if_script("syntax error: %s", "invalid redirect");
3283 ctx->pending_redirect = NULL;
3284 }
3285#endif
3286
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003287 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003288 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003289 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003290 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003291 }
3292 pi->num_cmds++;
3293 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003294 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003295 } else {
3296 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3297 }
3298
3299 /* Only real trickiness here is that the uncommitted
3300 * command structure is not counted in pi->num_cmds. */
3301 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003302 ctx->command = command = &pi->cmds[pi->num_cmds];
3303 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003304 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003305 return pi->num_cmds; /* used only for 0/nonzero check */
3306}
3307
3308static void done_pipe(struct parse_context *ctx, pipe_style type)
3309{
3310 int not_null;
3311
3312 debug_printf_parse("done_pipe entered, followup %d\n", type);
3313 /* Close previous command */
3314 not_null = done_command(ctx);
3315 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003316#if HAS_KEYWORDS
3317 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3318 ctx->ctx_inverted = 0;
3319 ctx->pipe->res_word = ctx->ctx_res_w;
3320#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003321
3322 /* Without this check, even just <enter> on command line generates
3323 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003324 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003325 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00003326#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003327 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00003328#endif
3329#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003330 || ctx->ctx_res_w == RES_DONE
3331 || ctx->ctx_res_w == RES_FOR
3332 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00003333#endif
3334#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003335 || ctx->ctx_res_w == RES_ESAC
3336#endif
3337 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003338 struct pipe *new_p;
3339 debug_printf_parse("done_pipe: adding new pipe: "
3340 "not_null:%d ctx->ctx_res_w:%d\n",
3341 not_null, ctx->ctx_res_w);
3342 new_p = new_pipe();
3343 ctx->pipe->next = new_p;
3344 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003345 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003346 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003347 * This is used to control execution.
3348 * RES_FOR and RES_IN are NOT sticky (needed to support
3349 * cases where variable or value happens to match a keyword):
3350 */
3351#if ENABLE_HUSH_LOOPS
3352 if (ctx->ctx_res_w == RES_FOR
3353 || ctx->ctx_res_w == RES_IN)
3354 ctx->ctx_res_w = RES_NONE;
3355#endif
3356#if ENABLE_HUSH_CASE
3357 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003358 ctx->ctx_res_w = RES_CASE_BODY;
3359 if (ctx->ctx_res_w == RES_CASE)
3360 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003361#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003362 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003363 /* Create the memory for command, roughly:
3364 * ctx->pipe->cmds = new struct command;
3365 * ctx->command = &ctx->pipe->cmds[0];
3366 */
3367 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003368 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003369 }
3370 debug_printf_parse("done_pipe return\n");
3371}
3372
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003373static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003374{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003375 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003376 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003377 /* Create the memory for command, roughly:
3378 * ctx->pipe->cmds = new struct command;
3379 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003380 */
3381 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003382}
3383
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003384/* If a reserved word is found and processed, parse context is modified
3385 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003386 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003387#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003388struct reserved_combo {
3389 char literal[6];
3390 unsigned char res;
3391 unsigned char assignment_flag;
3392 int flag;
3393};
3394enum {
3395 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003396# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003397 FLAG_IF = (1 << RES_IF ),
3398 FLAG_THEN = (1 << RES_THEN ),
3399 FLAG_ELIF = (1 << RES_ELIF ),
3400 FLAG_ELSE = (1 << RES_ELSE ),
3401 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003402# endif
3403# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003404 FLAG_FOR = (1 << RES_FOR ),
3405 FLAG_WHILE = (1 << RES_WHILE),
3406 FLAG_UNTIL = (1 << RES_UNTIL),
3407 FLAG_DO = (1 << RES_DO ),
3408 FLAG_DONE = (1 << RES_DONE ),
3409 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003410# endif
3411# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003412 FLAG_MATCH = (1 << RES_MATCH),
3413 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003414# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003415 FLAG_START = (1 << RES_XXXX ),
3416};
3417
3418static const struct reserved_combo* match_reserved_word(o_string *word)
3419{
Eric Andersen25f27032001-04-26 23:22:31 +00003420 /* Mostly a list of accepted follow-up reserved words.
3421 * FLAG_END means we are done with the sequence, and are ready
3422 * to turn the compound list into a command.
3423 * FLAG_START means the word must start a new compound list.
3424 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003425 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003426# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003427 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3428 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3429 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3430 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3431 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3432 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003433# endif
3434# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003435 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3436 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3437 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3438 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3439 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3440 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003441# endif
3442# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003443 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3444 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003445# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003446 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003447 const struct reserved_combo *r;
3448
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003449 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003450 if (strcmp(word->data, r->literal) == 0)
3451 return r;
3452 }
3453 return NULL;
3454}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003455/* Return 0: not a keyword, 1: keyword
3456 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003457static int reserved_word(o_string *word, struct parse_context *ctx)
3458{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003459# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003460 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003461 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003462 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003463# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003464 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003465
Denys Vlasenko38292b62010-09-05 14:49:40 +02003466 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003467 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003468 r = match_reserved_word(word);
3469 if (!r)
3470 return 0;
3471
3472 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003473# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003474 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3475 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003476 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003477 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003478# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003479 if (r->flag == 0) { /* '!' */
3480 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003481 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003482 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003483 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003484 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003485 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003486 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003487 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003488 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003489
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003490 old = xmalloc(sizeof(*old));
3491 debug_printf_parse("push stack %p\n", old);
3492 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003493 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003494 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003495 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003496 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003497 ctx->ctx_res_w = RES_SNTX;
3498 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003499 } else {
3500 /* "{...} fi" is ok. "{...} if" is not
3501 * Example:
3502 * if { echo foo; } then { echo bar; } fi */
3503 if (ctx->command->group)
3504 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003505 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003506
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003507 ctx->ctx_res_w = r->res;
3508 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003509 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003510 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003511
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003512 if (ctx->old_flag & FLAG_END) {
3513 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003514
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003515 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003516 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003517 old = ctx->stack;
3518 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003519 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003520# if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02003521 /* At this point, the compound command's string is in
3522 * ctx->as_string... except for the leading keyword!
3523 * Consider this example: "echo a | if true; then echo a; fi"
3524 * ctx->as_string will contain "true; then echo a; fi",
3525 * with "if " remaining in old->as_string!
3526 */
3527 {
3528 char *str;
3529 int len = old->as_string.length;
3530 /* Concatenate halves */
3531 o_addstr(&old->as_string, ctx->as_string.data);
3532 o_free_unsafe(&ctx->as_string);
3533 /* Find where leading keyword starts in first half */
3534 str = old->as_string.data + len;
3535 if (str > old->as_string.data)
3536 str--; /* skip whitespace after keyword */
3537 while (str > old->as_string.data && isalpha(str[-1]))
3538 str--;
3539 /* Ugh, we're done with this horrid hack */
3540 old->command->group_as_string = xstrdup(str);
3541 debug_printf_parse("pop, remembering as:'%s'\n",
3542 old->command->group_as_string);
3543 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003544# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003545 *ctx = *old; /* physical copy */
3546 free(old);
3547 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003548 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003549}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003550#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003551
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003552/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003553 * Normal return is 0. Syntax errors return 1.
3554 * Note: on return, word is reset, but not o_free'd!
3555 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003556static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003557{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003558 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003559
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003560 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003561 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003562 debug_printf_parse("done_word return 0: true null, ignored\n");
3563 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003564 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003565
Eric Andersen25f27032001-04-26 23:22:31 +00003566 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003567 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3568 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003569 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3570 * "2.7 Redirection
3571 * ...the word that follows the redirection operator
3572 * shall be subjected to tilde expansion, parameter expansion,
3573 * command substitution, arithmetic expansion, and quote
3574 * removal. Pathname expansion shall not be performed
3575 * on the word by a non-interactive shell; an interactive
3576 * shell may perform it, but shall do so only when
3577 * the expansion would result in one word."
3578 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003579 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003580 /* Cater for >\file case:
3581 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3582 * Same with heredocs:
3583 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3584 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003585 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3586 unbackslash(ctx->pending_redirect->rd_filename);
3587 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003588 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003589 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3590 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003591 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003592 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003593 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003594 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003595#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003596# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003597 if (ctx->ctx_dsemicolon
3598 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3599 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003600 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003601 /* ctx->ctx_res_w = RES_MATCH; */
3602 ctx->ctx_dsemicolon = 0;
3603 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003604# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003605 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003606# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003607 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3608 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003609# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003610# if ENABLE_HUSH_CASE
3611 && ctx->ctx_res_w != RES_CASE
3612# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003613 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003614 int reserved = reserved_word(word, ctx);
3615 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3616 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003617 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003618 debug_printf_parse("done_word return %d\n",
3619 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003620 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003621 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003622# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003623 if (strcmp(word->data, "[[") == 0) {
3624 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3625 }
3626 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003627# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003628 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003629#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003630 if (command->group) {
3631 /* "{ echo foo; } echo bar" - bad */
3632 syntax_error_at(word->data);
3633 debug_printf_parse("done_word return 1: syntax error, "
3634 "groups and arglists don't mix\n");
3635 return 1;
3636 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003637
3638 /* If this word wasn't an assignment, next ones definitely
3639 * can't be assignments. Even if they look like ones. */
3640 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3641 && word->o_assignment != WORD_IS_KEYWORD
3642 ) {
3643 word->o_assignment = NOT_ASSIGNMENT;
3644 } else {
3645 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3646 command->assignment_cnt++;
3647 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3648 }
3649 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3650 word->o_assignment = MAYBE_ASSIGNMENT;
3651 }
3652 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3653
Denys Vlasenko38292b62010-09-05 14:49:40 +02003654 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003655 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3656 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003657 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003658 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003659 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003660 char *p = word->data;
3661 while (p[0] == SPECIAL_VAR_SYMBOL
3662 && (p[1] & 0x7f) == '@'
3663 && p[2] == SPECIAL_VAR_SYMBOL
3664 ) {
3665 p += 3;
3666 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003667 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003668 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003669 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003670 }
Eric Andersen25f27032001-04-26 23:22:31 +00003671
Denis Vlasenko06810332007-05-21 23:30:54 +00003672#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003673 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003674 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003675 || !is_well_formed_var_name(command->argv[0], '\0')
3676 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003677 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003678 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003679 return 1;
3680 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003681 /* Force FOR to have just one word (variable name) */
3682 /* NB: basically, this makes hush see "for v in ..."
3683 * syntax as if it is "for v; in ...". FOR and IN become
3684 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003685 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003686 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003687#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003688#if ENABLE_HUSH_CASE
3689 /* Force CASE to have just one word */
3690 if (ctx->ctx_res_w == RES_CASE) {
3691 done_pipe(ctx, PIPE_SEQ);
3692 }
3693#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003694
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003695 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003696
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003697 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003698 return 0;
3699}
3700
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003701
3702/* Peek ahead in the input to find out if we have a "&n" construct,
3703 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003704 * Return:
3705 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3706 * REDIRFD_SYNTAX_ERR if syntax error,
3707 * REDIRFD_TO_FILE if no & was seen,
3708 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003709 */
3710#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003711#define parse_redir_right_fd(as_string, input) \
3712 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003713#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003714static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003715{
3716 int ch, d, ok;
3717
3718 ch = i_peek(input);
3719 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003720 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003721
3722 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003723 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003724 ch = i_peek(input);
3725 if (ch == '-') {
3726 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003727 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003728 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003729 }
3730 d = 0;
3731 ok = 0;
3732 while (ch != EOF && isdigit(ch)) {
3733 d = d*10 + (ch-'0');
3734 ok = 1;
3735 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003736 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003737 ch = i_peek(input);
3738 }
3739 if (ok) return d;
3740
3741//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3742
3743 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003744 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003745}
3746
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003747/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003748 */
3749static int parse_redirect(struct parse_context *ctx,
3750 int fd,
3751 redir_type style,
3752 struct in_str *input)
3753{
3754 struct command *command = ctx->command;
3755 struct redir_struct *redir;
3756 struct redir_struct **redirp;
3757 int dup_num;
3758
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003759 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003760 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003761 /* Check for a '>&1' type redirect */
3762 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3763 if (dup_num == REDIRFD_SYNTAX_ERR)
3764 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003765 } else {
3766 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003767 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003768 if (dup_num) { /* <<-... */
3769 ch = i_getch(input);
3770 nommu_addchr(&ctx->as_string, ch);
3771 ch = i_peek(input);
3772 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003773 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003774
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003775 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003776 int ch = i_peek(input);
3777 if (ch == '|') {
3778 /* >|FILE redirect ("clobbering" >).
3779 * Since we do not support "set -o noclobber" yet,
3780 * >| and > are the same for now. Just eat |.
3781 */
3782 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003783 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003784 }
3785 }
3786
3787 /* Create a new redir_struct and append it to the linked list */
3788 redirp = &command->redirects;
3789 while ((redir = *redirp) != NULL) {
3790 redirp = &(redir->next);
3791 }
3792 *redirp = redir = xzalloc(sizeof(*redir));
3793 /* redir->next = NULL; */
3794 /* redir->rd_filename = NULL; */
3795 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003796 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003797
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003798 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3799 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003800
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003801 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003802 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003803 /* Erik had a check here that the file descriptor in question
3804 * is legit; I postpone that to "run time"
3805 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003806 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3807 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003808 } else {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02003809#if 0 /* Instead we emit error message at run time */
3810 if (ctx->pending_redirect) {
3811 /* For example, "cmd > <file" */
3812 die_if_script("syntax error: %s", "invalid redirect");
3813 }
3814#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003815 /* Set ctx->pending_redirect, so we know what to do at the
3816 * end of the next parsed word. */
3817 ctx->pending_redirect = redir;
3818 }
3819 return 0;
3820}
3821
Eric Andersen25f27032001-04-26 23:22:31 +00003822/* If a redirect is immediately preceded by a number, that number is
3823 * supposed to tell which file descriptor to redirect. This routine
3824 * looks for such preceding numbers. In an ideal world this routine
3825 * needs to handle all the following classes of redirects...
3826 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3827 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3828 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3829 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003830 *
3831 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3832 * "2.7 Redirection
3833 * ... If n is quoted, the number shall not be recognized as part of
3834 * the redirection expression. For example:
3835 * echo \2>a
3836 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003837 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003838 *
3839 * A -1 return means no valid number was found,
3840 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003841 */
3842static int redirect_opt_num(o_string *o)
3843{
3844 int num;
3845
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003846 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003847 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003848 num = bb_strtou(o->data, NULL, 10);
3849 if (errno || num < 0)
3850 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003851 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003852 return num;
3853}
3854
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003855#if BB_MMU
3856#define fetch_till_str(as_string, input, word, skip_tabs) \
3857 fetch_till_str(input, word, skip_tabs)
3858#endif
3859static char *fetch_till_str(o_string *as_string,
3860 struct in_str *input,
3861 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003862 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003863{
3864 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003865 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003866 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003867 int ch;
3868
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003869 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003870
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003871 while (1) {
3872 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003873 if (ch != EOF)
3874 nommu_addchr(as_string, ch);
3875 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003876 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3877 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003878 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3879 heredoc.data[past_EOL] = '\0';
3880 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3881 return heredoc.data;
3882 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003883 while (ch == '\n') {
3884 o_addchr(&heredoc, ch);
3885 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003886 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003887 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003888 do {
3889 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003890 if (ch != EOF)
3891 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003892 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003893 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003894 }
3895 if (ch == EOF) {
3896 o_free_unsafe(&heredoc);
3897 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003898 }
3899 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003900 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003901 if (prev == '\\' && ch == '\\')
3902 /* Correctly handle foo\\<eol> (not a line cont.) */
3903 prev = 0; /* not \ */
3904 else
3905 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003906 }
3907}
3908
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003909/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3910 * and load them all. There should be exactly heredoc_cnt of them.
3911 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003912static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3913{
3914 struct pipe *pi = ctx->list_head;
3915
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003916 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003917 int i;
3918 struct command *cmd = pi->cmds;
3919
3920 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3921 pi->num_cmds,
3922 cmd->argv ? cmd->argv[0] : "NONE");
3923 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003924 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003925
3926 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3927 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003928 while (redir) {
3929 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003930 char *p;
3931
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003932 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003933 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003934 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003935 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003936 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003937 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003938 return 1;
3939 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003940 free(redir->rd_filename);
3941 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003942 heredoc_cnt--;
3943 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003944 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003945 }
3946 cmd++;
3947 }
3948 pi = pi->next;
3949 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003950#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003951 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003952 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003953 bb_error_msg_and_die("heredoc BUG 2");
3954#endif
3955 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003956}
3957
3958
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003959static int run_list(struct pipe *pi);
3960#if BB_MMU
3961#define parse_stream(pstring, input, end_trigger) \
3962 parse_stream(input, end_trigger)
3963#endif
3964static struct pipe *parse_stream(char **pstring,
3965 struct in_str *input,
3966 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003967
Eric Andersen25f27032001-04-26 23:22:31 +00003968
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003969#if !ENABLE_HUSH_FUNCTIONS
3970#define parse_group(dest, ctx, input, ch) \
3971 parse_group(ctx, input, ch)
3972#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003973static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003974 struct in_str *input, int ch)
3975{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003976 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003977 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003978 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003979 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003980 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003981 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003982
3983 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003984#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003985 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003986 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003987 if (done_word(dest, ctx))
3988 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003989 if (!command->argv)
3990 goto skip; /* (... */
3991 if (command->argv[1]) { /* word word ... (... */
3992 syntax_error_unexpected_ch('(');
3993 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003994 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003995 /* it is "word(..." or "word (..." */
3996 do
3997 ch = i_getch(input);
3998 while (ch == ' ' || ch == '\t');
3999 if (ch != ')') {
4000 syntax_error_unexpected_ch(ch);
4001 return 1;
4002 }
4003 nommu_addchr(&ctx->as_string, ch);
4004 do
4005 ch = i_getch(input);
4006 while (ch == ' ' || ch == '\t' || ch == '\n');
4007 if (ch != '{') {
4008 syntax_error_unexpected_ch(ch);
4009 return 1;
4010 }
4011 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004012 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004013 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004014 }
4015#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004016
4017#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004018 if (command->argv /* word [word]{... */
4019 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004020 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004021 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004022 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004023 debug_printf_parse("parse_group return 1: "
4024 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004025 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004026 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004027#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004028
4029#if ENABLE_HUSH_FUNCTIONS
4030 skip:
4031#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004032 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004033 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004034 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004035 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004036 } else {
4037 /* bash does not allow "{echo...", requires whitespace */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004038 ch = i_peek(input);
4039 if (ch != ' ' && ch != '\t' && ch != '\n'
4040 && ch != '(' /* but "{(..." is allowed (without whitespace) */
4041 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004042 syntax_error_unexpected_ch(ch);
4043 return 1;
4044 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004045 if (ch != '(') {
4046 ch = i_getch(input);
4047 nommu_addchr(&ctx->as_string, ch);
4048 }
Eric Andersen25f27032001-04-26 23:22:31 +00004049 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004050
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004051 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004052#if BB_MMU
4053# define as_string NULL
4054#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004055 char *as_string = NULL;
4056#endif
4057 pipe_list = parse_stream(&as_string, input, endch);
4058#if !BB_MMU
4059 if (as_string)
4060 o_addstr(&ctx->as_string, as_string);
4061#endif
4062 /* empty ()/{} or parse error? */
4063 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00004064 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004065 if (!BB_MMU)
4066 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004067 debug_printf_parse("parse_group return 1: "
4068 "parse_stream returned %p\n", pipe_list);
4069 return 1;
4070 }
4071 command->group = pipe_list;
4072#if !BB_MMU
4073 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4074 command->group_as_string = as_string;
4075 debug_printf_parse("end of group, remembering as:'%s'\n",
4076 command->group_as_string);
4077#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004078#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004079 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004080 debug_printf_parse("parse_group return 0\n");
4081 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004082 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004083}
4084
Denys Vlasenko46e64982016-09-29 19:50:55 +02004085static int i_getch_and_eat_bkslash_nl(struct in_str *input)
4086{
4087 for (;;) {
4088 int ch, ch2;
4089
4090 ch = i_getch(input);
4091 if (ch != '\\')
4092 return ch;
4093 ch2 = i_peek(input);
4094 if (ch2 != '\n')
4095 return ch;
4096 /* backslash+newline, skip it */
4097 i_getch(input);
4098 }
4099}
4100
Denys Vlasenko657086a2016-09-29 18:07:42 +02004101static int i_peek_and_eat_bkslash_nl(struct in_str *input)
4102{
4103 for (;;) {
4104 int ch, ch2;
4105
4106 ch = i_peek(input);
4107 if (ch != '\\')
4108 return ch;
4109 ch2 = i_peek2(input);
4110 if (ch2 != '\n')
4111 return ch;
4112 /* backslash+newline, skip it */
4113 i_getch(input);
4114 i_getch(input);
4115 }
4116}
4117
Denys Vlasenko0b883582016-12-23 16:49:07 +01004118#if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004119/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004120static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004121/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004122static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004123{
4124 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004125 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004126 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004127 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004128 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004129 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004130 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004131 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004132 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004133 }
4134}
4135/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004136static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004137{
4138 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004139 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004140 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004141 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004142 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004143 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004144 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004145 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004146 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004147 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004148 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004149 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004150 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004151 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004152 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
4153 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004154 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004155 continue;
4156 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004157 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004158 }
4159}
4160/* Process `cmd` - copy contents until "`" is seen. Complicated by
4161 * \` quoting.
4162 * "Within the backquoted style of command substitution, backslash
4163 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4164 * The search for the matching backquote shall be satisfied by the first
4165 * backquote found without a preceding backslash; during this search,
4166 * if a non-escaped backquote is encountered within a shell comment,
4167 * a here-document, an embedded command substitution of the $(command)
4168 * form, or a quoted string, undefined results occur. A single-quoted
4169 * or double-quoted string that begins, but does not end, within the
4170 * "`...`" sequence produces undefined results."
4171 * Example Output
4172 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4173 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004174static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004175{
4176 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004177 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004178 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004179 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004180 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004181 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
4182 ch = i_getch(input);
4183 if (ch != '`'
4184 && ch != '$'
4185 && ch != '\\'
4186 && (!in_dquote || ch != '"')
4187 ) {
4188 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004189 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004190 }
4191 if (ch == EOF) {
4192 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004193 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004194 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004195 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004196 }
4197}
4198/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4199 * quoting and nested ()s.
4200 * "With the $(command) style of command substitution, all characters
4201 * following the open parenthesis to the matching closing parenthesis
4202 * constitute the command. Any valid shell script can be used for command,
4203 * except a script consisting solely of redirections which produces
4204 * unspecified results."
4205 * Example Output
4206 * echo $(echo '(TEST)' BEST) (TEST) BEST
4207 * echo $(echo 'TEST)' BEST) TEST) BEST
4208 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02004209 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004210 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004211 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004212 * In bash compat mode, it needs to also be able to stop on ':' or '/'
4213 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004214 */
Denys Vlasenko74369502010-05-21 19:52:01 +02004215#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004216static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004217{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004218 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02004219 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004220# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004221 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004222# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004223 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
4224
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004225 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004226 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004227 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004228 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004229 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004230 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004231 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004232 if (!dbl)
4233 break;
4234 /* we look for closing )) of $((EXPR)) */
Denys Vlasenko657086a2016-09-29 18:07:42 +02004235 if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004236 i_getch(input); /* eat second ')' */
4237 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004238 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004239 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004240 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004241 if (ch == '(' || ch == '{') {
4242 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004243 if (!add_till_closing_bracket(dest, input, ch))
4244 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004245 o_addchr(dest, ch);
4246 continue;
4247 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004248 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004249 if (!add_till_single_quote(dest, input))
4250 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004251 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004252 continue;
4253 }
4254 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004255 if (!add_till_double_quote(dest, input))
4256 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004257 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004258 continue;
4259 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004260 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004261 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
4262 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02004263 o_addchr(dest, ch);
4264 continue;
4265 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004266 if (ch == '\\') {
4267 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004268 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004269 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004270 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004271 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004272 }
Denys Vlasenko657086a2016-09-29 18:07:42 +02004273#if 0
4274 if (ch == '\n') {
4275 /* "backslash+newline", ignore both */
4276 o_delchr(dest); /* undo insertion of '\' */
4277 continue;
4278 }
4279#endif
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004280 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004281 continue;
4282 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004283 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004284 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004285}
Denys Vlasenko0b883582016-12-23 16:49:07 +01004286#endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004287
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004288/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004289#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004290#define parse_dollar(as_string, dest, input, quote_mask) \
4291 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004292#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004293#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004294static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004295 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004296 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00004297{
Denys Vlasenko657086a2016-09-29 18:07:42 +02004298 int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004299
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004300 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004301 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004302 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004303 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004304 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004305 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004306 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004307 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004308 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004309 quote_mask = 0;
Denys Vlasenko657086a2016-09-29 18:07:42 +02004310 ch = i_peek_and_eat_bkslash_nl(input);
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004311 if (!isalnum(ch) && ch != '_') {
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004312 /* End of variable name reached */
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004313 break;
Denys Vlasenkod17a91d2016-09-29 18:02:37 +02004314 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004315 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004316 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004317 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004318 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004319 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004320 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004321 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004322 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004323 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004324 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004325 o_addchr(dest, ch | quote_mask);
4326 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004327 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004328 case '$': /* pid */
4329 case '!': /* last bg pid */
4330 case '?': /* last exit code */
4331 case '#': /* number of args */
4332 case '*': /* args */
4333 case '@': /* args */
4334 goto make_one_char_var;
4335 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04004336 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4337
Denys Vlasenko74369502010-05-21 19:52:01 +02004338 ch = i_getch(input); /* eat '{' */
4339 nommu_addchr(as_string, ch);
4340
Denys Vlasenko46e64982016-09-29 19:50:55 +02004341 ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02004342 /* It should be ${?}, or ${#var},
4343 * or even ${?+subst} - operator acting on a special variable,
4344 * or the beginning of variable name.
4345 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004346 if (ch == EOF
4347 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
4348 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02004349 bad_dollar_syntax:
4350 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004351 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
4352 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02004353 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004354 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004355 ch |= quote_mask;
4356
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004357 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02004358 * However, this regresses some of our testsuite cases
4359 * which check invalid constructs like ${%}.
4360 * Oh well... let's check that the var name part is fine... */
4361
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004362 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004363 unsigned pos;
4364
Denys Vlasenko74369502010-05-21 19:52:01 +02004365 o_addchr(dest, ch);
4366 debug_printf_parse(": '%c'\n", ch);
4367
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004368 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004369 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02004370 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004371 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004372
Denys Vlasenko74369502010-05-21 19:52:01 +02004373 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004374 unsigned end_ch;
4375 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004376 /* handle parameter expansions
4377 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4378 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004379 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02004380 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004381
4382 /* Eat everything until closing '}' (or ':') */
4383 end_ch = '}';
4384 if (ENABLE_HUSH_BASH_COMPAT
4385 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004386 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004387 ) {
4388 /* It's ${var:N[:M]} thing */
4389 end_ch = '}' * 0x100 + ':';
4390 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004391 if (ENABLE_HUSH_BASH_COMPAT
4392 && ch == '/'
4393 ) {
4394 /* It's ${var/[/]pattern[/repl]} thing */
4395 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
4396 i_getch(input);
4397 nommu_addchr(as_string, '/');
4398 ch = '\\';
4399 }
4400 end_ch = '}' * 0x100 + '/';
4401 }
4402 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004403 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004404 if (!BB_MMU)
4405 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004406#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004407 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004408 if (last_ch == 0) /* error? */
4409 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02004410#else
4411#error Simple code to only allow ${var} is not implemented
4412#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004413 if (as_string) {
4414 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004415 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004416 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004417
4418 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
4419 /* close the first block: */
4420 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004421 /* while parsing N from ${var:N[:M]}
4422 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004423 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004424 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004425 end_ch = '}';
4426 goto again;
4427 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02004428 /* got '}' */
4429 if (end_ch == '}' * 0x100 + ':') {
4430 /* it's ${var:N} - emulate :999999999 */
4431 o_addstr(dest, "999999999");
4432 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02004433 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004434 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004435 }
Denys Vlasenko74369502010-05-21 19:52:01 +02004436 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004437 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4438 break;
4439 }
Denys Vlasenko0b883582016-12-23 16:49:07 +01004440#if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004441 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004442 unsigned pos;
4443
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004444 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004445 nommu_addchr(as_string, ch);
Denys Vlasenko0b883582016-12-23 16:49:07 +01004446# if ENABLE_FEATURE_SH_MATH
Denys Vlasenko657086a2016-09-29 18:07:42 +02004447 if (i_peek_and_eat_bkslash_nl(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004448 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004449 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004450 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4451 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004452 if (!BB_MMU)
4453 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004454 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4455 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004456 if (as_string) {
4457 o_addstr(as_string, dest->data + pos);
4458 o_addchr(as_string, ')');
4459 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004460 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004461 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004462 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004463 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004464# endif
4465# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004466 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4467 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004468 if (!BB_MMU)
4469 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004470 if (!add_till_closing_bracket(dest, input, ')'))
4471 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004472 if (as_string) {
4473 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004474 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004475 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004476 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004477# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004478 break;
4479 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004480#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004481 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004482 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004483 nommu_addchr(as_string, ch);
Denys Vlasenko657086a2016-09-29 18:07:42 +02004484 ch = i_peek_and_eat_bkslash_nl(input);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004485 if (isalnum(ch)) { /* it's $_name or $_123 */
4486 ch = '_';
4487 goto make_var;
4488 }
4489 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004490 /* TODO: $_ and $-: */
4491 /* $_ Shell or shell script name; or last argument of last command
4492 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4493 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004494 /* $- Option flags set by set builtin or shell options (-i etc) */
4495 default:
4496 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004497 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004498 debug_printf_parse("parse_dollar return 1 (ok)\n");
4499 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004500#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004501}
4502
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004503#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004504# if ENABLE_HUSH_BASH_COMPAT
4505#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4506 encode_string(dest, input, dquote_end, process_bkslash)
4507# else
4508/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4509#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4510 encode_string(dest, input, dquote_end)
4511# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004512#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004513
4514#else /* !MMU */
4515
4516# if ENABLE_HUSH_BASH_COMPAT
4517/* all parameters are needed, no macro tricks */
4518# else
4519#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4520 encode_string(as_string, dest, input, dquote_end)
4521# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004522#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004523static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004524 o_string *dest,
4525 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004526 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004527 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004528{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004529#if !ENABLE_HUSH_BASH_COMPAT
4530 const int process_bkslash = 1;
4531#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004532 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004533 int next;
4534
4535 again:
4536 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004537 if (ch != EOF)
4538 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004539 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004540 debug_printf_parse("encode_string return 1 (ok)\n");
4541 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004542 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004543 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004544 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004545 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004546 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004547 }
4548 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004549 if (ch != '\n') {
4550 next = i_peek(input);
4551 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004552 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004553 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004554 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004555 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004556 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004557 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004558 }
4559 /* bash:
4560 * "The backslash retains its special meaning [in "..."]
4561 * only when followed by one of the following characters:
4562 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004563 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004564 * NB: in (unquoted) heredoc, above does not apply to ",
4565 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004566 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004567 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004568 ch = i_getch(input); /* eat next */
4569 if (ch == '\n')
4570 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004571 } /* else: ch remains == '\\', and we double it below: */
4572 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004573 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004574 goto again;
4575 }
4576 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004577 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4578 debug_printf_parse("encode_string return 0: "
4579 "parse_dollar returned 0 (error)\n");
4580 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004581 }
4582 goto again;
4583 }
4584#if ENABLE_HUSH_TICK
4585 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004586 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004587 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4588 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004589 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4590 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004591 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4592 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004593 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004594 }
4595#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004596 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004597 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004598#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004599}
4600
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004601/*
4602 * Scan input until EOF or end_trigger char.
4603 * Return a list of pipes to execute, or NULL on EOF
4604 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004605 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004606 * reset parsing machinery and start parsing anew,
4607 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004608 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004609static struct pipe *parse_stream(char **pstring,
4610 struct in_str *input,
4611 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004612{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004613 struct parse_context ctx;
4614 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004615 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004616
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004617 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004618 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004619 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004620 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004621 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004622 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004623
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004624 /* If very first arg is "" or '', dest.data may end up NULL.
4625 * Preventing this: */
4626 o_addchr(&dest, '\0');
4627 dest.length = 0;
4628
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004629 /* We used to separate words on $IFS here. This was wrong.
4630 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004631 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004632 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004633
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004634 if (MAYBE_ASSIGNMENT != 0)
4635 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004636 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004637 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004638 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004639 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004640 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004641 int ch;
4642 int next;
4643 int redir_fd;
4644 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004645
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004646 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004647 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004648 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004649 if (ch == EOF) {
4650 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004651
4652 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004653 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004654 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004655 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004656 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004657 syntax_error_unterm_ch('(');
4658 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004659 }
Denys Vlasenko42246472016-11-07 16:22:35 +01004660 if (end_trigger == '}') {
4661 syntax_error_unterm_ch('{');
4662 goto parse_error;
4663 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004664
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004665 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004666 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004667 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004668 o_free(&dest);
4669 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004670 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004671 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004672 /* (this makes bare "&" cmd a no-op.
4673 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004674 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004675 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004676 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004677 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004678 pi = NULL;
4679 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004680#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004681 debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004682 if (pstring)
4683 *pstring = ctx.as_string.data;
4684 else
4685 o_free_unsafe(&ctx.as_string);
4686#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004687 debug_leave();
4688 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004689 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004690 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004691 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004692
4693 next = '\0';
4694 if (ch != '\n')
4695 next = i_peek(input);
4696
4697 is_special = "{}<>;&|()#'" /* special outside of "str" */
4698 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4699 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004700 if (ctx.command->argv /* word [word]{... - non-special */
4701 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004702 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004703 || (next != ';' /* }; - special */
4704 && next != ')' /* }) - special */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004705 && next != '(' /* {( - special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004706 && next != '&' /* }& and }&& ... - special */
4707 && next != '|' /* }|| ... - special */
4708 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004709 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004710 ) {
4711 /* They are not special, skip "{}" */
4712 is_special += 2;
4713 }
4714 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004715 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004716
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004717 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004718 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004719 o_addQchr(&dest, ch);
4720 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4721 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004722 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004723 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004724 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004725 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004726 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004727 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004728 continue;
4729 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004730
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004731 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004732 if (done_word(&dest, &ctx)) {
4733 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004734 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004735 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004736 /* Is this a case when newline is simply ignored?
4737 * Some examples:
4738 * "cmd | <newline> cmd ..."
4739 * "case ... in <newline> word) ..."
4740 */
4741 if (IS_NULL_CMD(ctx.command)
4742 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004743 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004744 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004745 * Without check #1, interactive shell
4746 * ignores even bare <newline>,
4747 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004748 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004749 * ps2> _ <=== wrong, should be ps1
4750 * Without check #2, "cmd & <newline>"
4751 * is similarly mistreated.
4752 * (BTW, this makes "cmd & cmd"
4753 * and "cmd && cmd" non-orthogonal.
4754 * Really, ask yourself, why
4755 * "cmd && <newline>" doesn't start
4756 * cmd but waits for more input?
4757 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004758 */
4759 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004760 if (pi->num_cmds != 0 /* check #1 */
4761 && pi->followup != PIPE_BG /* check #2 */
4762 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004763 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004764 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004765 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004766 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004767 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004768 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4769 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004770 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004771 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004772 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004773 heredoc_cnt = 0;
4774 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004775 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004776 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004777 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004778 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004779 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004780 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004781 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004782
4783 /* "cmd}" or "cmd }..." without semicolon or &:
4784 * } is an ordinary char in this case, even inside { cmd; }
4785 * Pathological example: { ""}; } should exec "}" cmd
4786 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004787 if (ch == '}') {
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004788 if (dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004789 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004790 ) {
4791 goto ordinary_char;
4792 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004793 if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
4794 /* Generally, there should be semicolon: "cmd; }"
4795 * However, bash allows to omit it if "cmd" is
4796 * a group. Examples:
4797 * { { echo 1; } }
4798 * {(echo 1)}
4799 * { echo 0 >&2 | { echo 1; } }
4800 * { while false; do :; done }
4801 * { case a in b) ;; esac }
4802 */
4803 if (ctx.command->group)
4804 goto term_group;
4805 goto ordinary_char;
4806 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004807 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004808 /* Can't be an end of {cmd}, skip the check */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004809 goto skip_end_trigger;
4810 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004811 }
Denys Vlasenko672a55e2016-11-04 18:46:14 +01004812 term_group:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004813 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004814 && (ch != ';' || heredoc_cnt == 0)
4815#if ENABLE_HUSH_CASE
4816 && (ch != ')'
4817 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004818 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004819 )
4820#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004821 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004822 if (heredoc_cnt) {
4823 /* This is technically valid:
4824 * { cat <<HERE; }; echo Ok
4825 * heredoc
4826 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004827 * HERE
4828 * but we don't support this.
4829 * We require heredoc to be in enclosing {}/(),
4830 * if any.
4831 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004832 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004833 goto parse_error;
4834 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004835 if (done_word(&dest, &ctx)) {
4836 goto parse_error;
4837 }
4838 done_pipe(&ctx, PIPE_SEQ);
4839 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004840 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004841 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004842 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004843 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004844 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004845 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004846#if !BB_MMU
Denys Vlasenkob5be13c2015-09-04 06:22:10 +02004847 debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004848 if (pstring)
4849 *pstring = ctx.as_string.data;
4850 else
4851 o_free_unsafe(&ctx.as_string);
4852#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004853 debug_leave();
4854 debug_printf_parse("parse_stream return %p: "
4855 "end_trigger char found\n",
4856 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004857 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004858 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004859 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004860 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004861 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004862 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004863
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004864 /* Catch <, > before deciding whether this word is
4865 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4866 switch (ch) {
4867 case '>':
4868 redir_fd = redirect_opt_num(&dest);
4869 if (done_word(&dest, &ctx)) {
4870 goto parse_error;
4871 }
4872 redir_style = REDIRECT_OVERWRITE;
4873 if (next == '>') {
4874 redir_style = REDIRECT_APPEND;
4875 ch = i_getch(input);
4876 nommu_addchr(&ctx.as_string, ch);
4877 }
4878#if 0
4879 else if (next == '(') {
4880 syntax_error(">(process) not supported");
4881 goto parse_error;
4882 }
4883#endif
4884 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4885 goto parse_error;
4886 continue; /* back to top of while (1) */
4887 case '<':
4888 redir_fd = redirect_opt_num(&dest);
4889 if (done_word(&dest, &ctx)) {
4890 goto parse_error;
4891 }
4892 redir_style = REDIRECT_INPUT;
4893 if (next == '<') {
4894 redir_style = REDIRECT_HEREDOC;
4895 heredoc_cnt++;
4896 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4897 ch = i_getch(input);
4898 nommu_addchr(&ctx.as_string, ch);
4899 } else if (next == '>') {
4900 redir_style = REDIRECT_IO;
4901 ch = i_getch(input);
4902 nommu_addchr(&ctx.as_string, ch);
4903 }
4904#if 0
4905 else if (next == '(') {
4906 syntax_error("<(process) not supported");
4907 goto parse_error;
4908 }
4909#endif
4910 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4911 goto parse_error;
4912 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004913 case '#':
4914 if (dest.length == 0 && !dest.has_quoted_part) {
4915 /* skip "#comment" */
4916 while (1) {
4917 ch = i_peek(input);
4918 if (ch == EOF || ch == '\n')
4919 break;
4920 i_getch(input);
4921 /* note: we do not add it to &ctx.as_string */
4922 }
4923 nommu_addchr(&ctx.as_string, '\n');
4924 continue; /* back to top of while (1) */
4925 }
4926 break;
4927 case '\\':
4928 if (next == '\n') {
4929 /* It's "\<newline>" */
4930#if !BB_MMU
4931 /* Remove trailing '\' from ctx.as_string */
4932 ctx.as_string.data[--ctx.as_string.length] = '\0';
4933#endif
4934 ch = i_getch(input); /* eat it */
4935 continue; /* back to top of while (1) */
4936 }
4937 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004938 }
4939
4940 if (dest.o_assignment == MAYBE_ASSIGNMENT
4941 /* check that we are not in word in "a=1 2>word b=1": */
4942 && !ctx.pending_redirect
4943 ) {
4944 /* ch is a special char and thus this word
4945 * cannot be an assignment */
4946 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004947 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004948 }
4949
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004950 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4951
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004952 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004953 case '#': /* non-comment #: "echo a#b" etc */
4954 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004955 break;
4956 case '\\':
4957 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004958 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004959 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004960 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004961 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004962 /* note: ch != '\n' (that case does not reach this place) */
4963 o_addchr(&dest, '\\');
4964 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4965 o_addchr(&dest, ch);
4966 nommu_addchr(&ctx.as_string, ch);
4967 /* Example: echo Hello \2>file
4968 * we need to know that word 2 is quoted */
4969 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004970 break;
4971 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004972 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004973 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004974 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004975 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004976 }
Eric Andersen25f27032001-04-26 23:22:31 +00004977 break;
4978 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004979 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004980 if (next == '\'' && !ctx.pending_redirect) {
4981 insert_empty_quoted_str_marker:
4982 nommu_addchr(&ctx.as_string, next);
4983 i_getch(input); /* eat second ' */
4984 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4985 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4986 } else {
4987 while (1) {
4988 ch = i_getch(input);
4989 if (ch == EOF) {
4990 syntax_error_unterm_ch('\'');
4991 goto parse_error;
4992 }
4993 nommu_addchr(&ctx.as_string, ch);
4994 if (ch == '\'')
4995 break;
4996 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004997 }
Eric Andersen25f27032001-04-26 23:22:31 +00004998 }
Eric Andersen25f27032001-04-26 23:22:31 +00004999 break;
5000 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02005001 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005002 if (next == '"' && !ctx.pending_redirect)
5003 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005004 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005005 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005006 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005007 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02005008 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00005009 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005010#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005011 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02005012 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005013
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005014 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5015 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02005016 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005017 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
5018 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005019# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005020 o_addstr(&ctx.as_string, dest.data + pos);
5021 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02005022# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005023 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5024 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005025 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005026 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005027#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005028 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005029#if ENABLE_HUSH_CASE
5030 case_semi:
5031#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005032 if (done_word(&dest, &ctx)) {
5033 goto parse_error;
5034 }
5035 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005036#if ENABLE_HUSH_CASE
5037 /* Eat multiple semicolons, detect
5038 * whether it means something special */
5039 while (1) {
5040 ch = i_peek(input);
5041 if (ch != ';')
5042 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005043 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005044 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005045 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005046 ctx.ctx_dsemicolon = 1;
5047 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005048 break;
5049 }
5050 }
5051#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005052 new_cmd:
5053 /* We just finished a cmd. New one may start
5054 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005055 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02005056 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00005057 break;
5058 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005059 if (done_word(&dest, &ctx)) {
5060 goto parse_error;
5061 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005062 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005063 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005064 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005065 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005066 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005067 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005068 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005069 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005070 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005071 if (done_word(&dest, &ctx)) {
5072 goto parse_error;
5073 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005074#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005075 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005076 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005077#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005078 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005079 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005080 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005081 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005082 } else {
5083 /* we could pick up a file descriptor choice here
5084 * with redirect_opt_num(), but bash doesn't do it.
5085 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005086 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005087 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005088 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005089 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005090#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005091 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005092 if (ctx.ctx_res_w == RES_MATCH
5093 && ctx.command->argv == NULL /* not (word|(... */
5094 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02005095 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005096 ) {
5097 continue;
5098 }
5099#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005100 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005101 if (parse_group(&dest, &ctx, input, ch) != 0) {
5102 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005103 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005104 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005105 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005106#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005107 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005108 goto case_semi;
5109#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005110 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005111 /* proper use of this character is caught by end_trigger:
5112 * if we see {, we call parse_group(..., end_trigger='}')
5113 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005114 syntax_error_unexpected_ch(ch);
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005115 G.last_exitcode = 2;
5116 goto parse_error1;
Eric Andersen25f27032001-04-26 23:22:31 +00005117 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005118 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005119 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005120 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005121 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005122
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005123 parse_error:
Denys Vlasenkob05bcaf2017-01-03 11:47:50 +01005124 G.last_exitcode = 1;
5125 parse_error1:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005126 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005127 struct parse_context *pctx;
5128 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005129
5130 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005131 * Sample for finding leaks on syntax error recovery path.
5132 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005133 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005134 * Samples to catch leaks at execution:
Denys Vlasenko5d5a6112016-11-07 19:36:50 +01005135 * while if (true | { true;}); then echo ok; fi; do break; done
5136 * 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 +00005137 */
5138 pctx = &ctx;
5139 do {
5140 /* Update pipe/command counts,
5141 * otherwise freeing may miss some */
5142 done_pipe(pctx, PIPE_SEQ);
5143 debug_printf_clean("freeing list %p from ctx %p\n",
5144 pctx->list_head, pctx);
5145 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005146 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005147 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005148#if !BB_MMU
5149 o_free_unsafe(&pctx->as_string);
5150#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005151 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005152 if (pctx != &ctx) {
5153 free(pctx);
5154 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005155 IF_HAS_KEYWORDS(pctx = p2;)
5156 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005157
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02005158 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005159#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005160 if (pstring)
5161 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005162#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005163 debug_leave();
5164 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005165 }
Eric Andersen25f27032001-04-26 23:22:31 +00005166}
5167
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005168
5169/*** Execution routines ***/
5170
5171/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005172#if !ENABLE_HUSH_BASH_COMPAT
5173/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5174#define expand_string_to_string(str, do_unbackslash) \
5175 expand_string_to_string(str)
5176#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005177static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005178#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005179static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01005180#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005181
5182/* expand_strvec_to_strvec() takes a list of strings, expands
5183 * all variable references within and returns a pointer to
5184 * a list of expanded strings, possibly with larger number
5185 * of strings. (Think VAR="a b"; echo $VAR).
5186 * This new list is allocated as a single malloc block.
5187 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005188 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005189 * Caller can deallocate entire list by single free(list). */
5190
Denys Vlasenko238081f2010-10-03 14:26:26 +02005191/* A horde of its helpers come first: */
5192
5193static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
5194{
5195 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02005196 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005197
Denys Vlasenko9e800222010-10-03 14:28:04 +02005198#if ENABLE_HUSH_BRACE_EXPANSION
5199 if (c == '{' || c == '}') {
5200 /* { -> \{, } -> \} */
5201 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02005202 /* And now we want to add { or } and continue:
5203 * o_addchr(o, c);
5204 * continue;
5205 * luckily, just falling throught achieves this.
5206 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02005207 }
5208#endif
5209 o_addchr(o, c);
5210 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02005211 /* \z -> \\\z; \<eol> -> \\<eol> */
5212 o_addchr(o, '\\');
5213 if (len) {
5214 len--;
5215 o_addchr(o, '\\');
5216 o_addchr(o, *str++);
5217 }
5218 }
5219 }
5220}
5221
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005222/* Store given string, finalizing the word and starting new one whenever
5223 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005224 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
5225 * Return in *ended_with_ifs:
5226 * 1 - ended with IFS char, else 0 (this includes case of empty str).
5227 */
5228static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005229{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005230 int last_is_ifs = 0;
5231
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005232 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005233 int word_len;
5234
5235 if (!*str) /* EOL - do not finalize word */
5236 break;
5237 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005238 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005239 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02005240 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005241 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02005242 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005243 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02005244 * Example: "v='\*'; echo b$v" prints "b\*"
5245 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005246 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005247 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005248 /*/ Why can't we do it easier? */
5249 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
5250 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
5251 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005252 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005253 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005254 if (!*str) /* EOL - do not finalize word */
5255 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005256 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005257
5258 /* We know str here points to at least one IFS char */
5259 last_is_ifs = 1;
5260 str += strspn(str, G.ifs); /* skip IFS chars */
5261 if (!*str) /* EOL - do not finalize word */
5262 break;
5263
5264 /* Start new word... but not always! */
5265 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005266 if (output->has_quoted_part
5267 /* Case "v=' a'; echo $v":
5268 * here nothing precedes the space in $v expansion,
5269 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005270 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005271 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005272 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005273 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005274 o_addchr(output, '\0');
5275 debug_print_list("expand_on_ifs", output, n);
5276 n = o_save_ptr(output, n);
5277 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005278 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005279
5280 if (ended_with_ifs)
5281 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005282 debug_print_list("expand_on_ifs[1]", output, n);
5283 return n;
5284}
5285
5286/* Helper to expand $((...)) and heredoc body. These act as if
5287 * they are in double quotes, with the exception that they are not :).
5288 * Just the rules are similar: "expand only $var and `cmd`"
5289 *
5290 * Returns malloced string.
5291 * As an optimization, we return NULL if expansion is not needed.
5292 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005293#if !ENABLE_HUSH_BASH_COMPAT
5294/* only ${var/pattern/repl} (its pattern part) needs additional mode */
5295#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
5296 encode_then_expand_string(str)
5297#endif
5298static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005299{
5300 char *exp_str;
5301 struct in_str input;
5302 o_string dest = NULL_O_STRING;
5303
5304 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02005305 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005306#if ENABLE_HUSH_TICK
5307 && !strchr(str, '`')
5308#endif
5309 ) {
5310 return NULL;
5311 }
5312
5313 /* We need to expand. Example:
5314 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
5315 */
5316 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005317 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01005318//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005319 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005320 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005321 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
5322 o_free_unsafe(&dest);
5323 return exp_str;
5324}
5325
Denys Vlasenko0b883582016-12-23 16:49:07 +01005326#if ENABLE_FEATURE_SH_MATH
Denys Vlasenko063847d2010-09-15 13:33:02 +02005327static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005328{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005329 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005330 arith_t res;
5331 char *exp_str;
5332
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005333 math_state.lookupvar = get_local_var_value;
5334 math_state.setvar = set_local_var_from_halves;
5335 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005336 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02005337 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005338 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005339 if (errmsg_p)
5340 *errmsg_p = math_state.errmsg;
5341 if (math_state.errmsg)
5342 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005343 return res;
5344}
5345#endif
5346
5347#if ENABLE_HUSH_BASH_COMPAT
5348/* ${var/[/]pattern[/repl]} helpers */
5349static char *strstr_pattern(char *val, const char *pattern, int *size)
5350{
5351 while (1) {
5352 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
5353 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
5354 if (end) {
5355 *size = end - val;
5356 return val;
5357 }
5358 if (*val == '\0')
5359 return NULL;
5360 /* Optimization: if "*pat" did not match the start of "string",
5361 * we know that "tring", "ring" etc will not match too:
5362 */
5363 if (pattern[0] == '*')
5364 return NULL;
5365 val++;
5366 }
5367}
5368static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
5369{
5370 char *result = NULL;
5371 unsigned res_len = 0;
5372 unsigned repl_len = strlen(repl);
5373
5374 while (1) {
5375 int size;
5376 char *s = strstr_pattern(val, pattern, &size);
5377 if (!s)
5378 break;
5379
5380 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
5381 memcpy(result + res_len, val, s - val);
5382 res_len += s - val;
5383 strcpy(result + res_len, repl);
5384 res_len += repl_len;
5385 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
5386
5387 val = s + size;
5388 if (exp_op == '/')
5389 break;
5390 }
5391 if (val[0] && result) {
5392 result = xrealloc(result, res_len + strlen(val) + 1);
5393 strcpy(result + res_len, val);
5394 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
5395 }
5396 debug_printf_varexp("result:'%s'\n", result);
5397 return result;
5398}
5399#endif
5400
5401/* Helper:
5402 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
5403 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005404static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005405{
5406 const char *val = NULL;
5407 char *to_be_freed = NULL;
5408 char *p = *pp;
5409 char *var;
5410 char first_char;
5411 char exp_op;
5412 char exp_save = exp_save; /* for compiler */
5413 char *exp_saveptr; /* points to expansion operator */
5414 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005415 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005416
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005417 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005418 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005419 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005420 arg0 = arg[0];
5421 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005422 exp_op = 0;
5423
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005424 if (first_char == '#' /* ${#... */
5425 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
5426 ) {
5427 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005428 var++;
5429 exp_op = 'L';
5430 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005431 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005432 if (exp_saveptr /* if 2nd char is one of expansion operators */
5433 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
5434 ) {
5435 /* ${?:0}, ${#[:]%0} etc */
5436 exp_saveptr = var + 1;
5437 } else {
5438 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
5439 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
5440 }
5441 exp_op = exp_save = *exp_saveptr;
5442 if (exp_op) {
5443 exp_word = exp_saveptr + 1;
5444 if (exp_op == ':') {
5445 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005446//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005447 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005448 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005449 ) {
5450 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
5451 exp_op = ':';
5452 exp_word--;
5453 }
5454 }
5455 *exp_saveptr = '\0';
5456 } /* else: it's not an expansion op, but bare ${var} */
5457 }
5458
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005459 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005460 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005461 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005462 int n = xatoi_positive(var);
5463 if (n < G.global_argc)
5464 val = G.global_argv[n];
5465 /* else val remains NULL: $N with too big N */
5466 } else {
5467 switch (var[0]) {
5468 case '$': /* pid */
5469 val = utoa(G.root_pid);
5470 break;
5471 case '!': /* bg pid */
5472 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5473 break;
5474 case '?': /* exitcode */
5475 val = utoa(G.last_exitcode);
5476 break;
5477 case '#': /* argc */
5478 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5479 break;
5480 default:
5481 val = get_local_var_value(var);
5482 }
5483 }
5484
5485 /* Handle any expansions */
5486 if (exp_op == 'L') {
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005487 reinit_unicode_for_hush();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005488 debug_printf_expand("expand: length(%s)=", val);
Denys Vlasenkoc538d5b2014-08-13 09:57:44 +02005489 val = utoa(val ? unicode_strlen(val) : 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005490 debug_printf_expand("%s\n", val);
5491 } else if (exp_op) {
5492 if (exp_op == '%' || exp_op == '#') {
5493 /* Standard-mandated substring removal ops:
5494 * ${parameter%word} - remove smallest suffix pattern
5495 * ${parameter%%word} - remove largest suffix pattern
5496 * ${parameter#word} - remove smallest prefix pattern
5497 * ${parameter##word} - remove largest prefix pattern
5498 *
5499 * Word is expanded to produce a glob pattern.
5500 * Then var's value is matched to it and matching part removed.
5501 */
5502 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005503 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005504 char *exp_exp_word;
5505 char *loc;
5506 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005507 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005508 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005509 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005510 if (exp_exp_word)
5511 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005512 /* HACK ALERT. We depend here on the fact that
5513 * G.global_argv and results of utoa and get_local_var_value
5514 * are actually in writable memory:
5515 * scan_and_match momentarily stores NULs there. */
5516 t = (char*)val;
5517 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005518 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005519 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005520 free(exp_exp_word);
5521 if (loc) { /* match was found */
5522 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005523 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005524 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005525 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005526 }
5527 }
5528 }
5529#if ENABLE_HUSH_BASH_COMPAT
5530 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005531 /* It's ${var/[/]pattern[/repl]} thing.
5532 * Note that in encoded form it has TWO parts:
5533 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005534 * and if // is used, it is encoded as \:
5535 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005536 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005537 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005538 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005539 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005540 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005541 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005542 * by the usual expansion rules:
5543 * >az; >bz;
5544 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5545 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5546 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5547 * v='a bz'; echo ${v/a*z/\z} prints "z"
5548 * (note that a*z _pattern_ is never globbed!)
5549 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005550 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005551 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005552 if (!pattern)
5553 pattern = xstrdup(exp_word);
5554 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5555 *p++ = SPECIAL_VAR_SYMBOL;
5556 exp_word = p;
5557 p = strchr(p, SPECIAL_VAR_SYMBOL);
5558 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005559 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005560 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5561 /* HACK ALERT. We depend here on the fact that
5562 * G.global_argv and results of utoa and get_local_var_value
5563 * are actually in writable memory:
5564 * replace_pattern momentarily stores NULs there. */
5565 t = (char*)val;
5566 to_be_freed = replace_pattern(t,
5567 pattern,
5568 (repl ? repl : exp_word),
5569 exp_op);
5570 if (to_be_freed) /* at least one replace happened */
5571 val = to_be_freed;
5572 free(pattern);
5573 free(repl);
5574 }
5575 }
5576#endif
5577 else if (exp_op == ':') {
Denys Vlasenko0b883582016-12-23 16:49:07 +01005578#if ENABLE_HUSH_BASH_COMPAT && ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005579 /* It's ${var:N[:M]} bashism.
5580 * Note that in encoded form it has TWO parts:
5581 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5582 */
5583 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005584 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005585
Denys Vlasenko063847d2010-09-15 13:33:02 +02005586 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5587 if (errmsg)
5588 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005589 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5590 *p++ = SPECIAL_VAR_SYMBOL;
5591 exp_word = p;
5592 p = strchr(p, SPECIAL_VAR_SYMBOL);
5593 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005594 len = expand_and_evaluate_arith(exp_word, &errmsg);
5595 if (errmsg)
5596 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005597 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005598 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005599 if (beg < 0) /* bash compat */
5600 beg = 0;
5601 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005602 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005603 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005604 val = NULL;
5605 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005606 /* Paranoia. What if user entered 9999999999999
5607 * which fits in arith_t but not int? */
5608 if (len >= INT_MAX)
5609 len = INT_MAX;
5610 val = to_be_freed = xstrndup(val + beg, len);
5611 }
5612 debug_printf_varexp("val:'%s'\n", val);
5613 } else
5614#endif
5615 {
5616 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005617 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005618 }
5619 } else { /* one of "-=+?" */
5620 /* Standard-mandated substitution ops:
5621 * ${var?word} - indicate error if unset
5622 * If var is unset, word (or a message indicating it is unset
5623 * if word is null) is written to standard error
5624 * and the shell exits with a non-zero exit status.
5625 * Otherwise, the value of var is substituted.
5626 * ${var-word} - use default value
5627 * If var is unset, word is substituted.
5628 * ${var=word} - assign and use default value
5629 * If var is unset, word is assigned to var.
5630 * In all cases, final value of var is substituted.
5631 * ${var+word} - use alternative value
5632 * If var is unset, null is substituted.
5633 * Otherwise, word is substituted.
5634 *
5635 * Word is subjected to tilde expansion, parameter expansion,
5636 * command substitution, and arithmetic expansion.
5637 * If word is not needed, it is not expanded.
5638 *
5639 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5640 * but also treat null var as if it is unset.
5641 */
5642 int use_word = (!val || ((exp_save == ':') && !val[0]));
5643 if (exp_op == '+')
5644 use_word = !use_word;
5645 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5646 (exp_save == ':') ? "true" : "false", use_word);
5647 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005648 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005649 if (to_be_freed)
5650 exp_word = to_be_freed;
5651 if (exp_op == '?') {
5652 /* mimic bash message */
5653 die_if_script("%s: %s",
5654 var,
5655 exp_word[0] ? exp_word : "parameter null or not set"
5656 );
5657//TODO: how interactive bash aborts expansion mid-command?
5658 } else {
5659 val = exp_word;
5660 }
5661
5662 if (exp_op == '=') {
5663 /* ${var=[word]} or ${var:=[word]} */
5664 if (isdigit(var[0]) || var[0] == '#') {
5665 /* mimic bash message */
5666 die_if_script("$%s: cannot assign in this way", var);
5667 val = NULL;
5668 } else {
5669 char *new_var = xasprintf("%s=%s", var, val);
5670 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5671 }
5672 }
5673 }
5674 } /* one of "-=+?" */
5675
5676 *exp_saveptr = exp_save;
5677 } /* if (exp_op) */
5678
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005679 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005680
5681 *pp = p;
5682 *to_be_freed_pp = to_be_freed;
5683 return val;
5684}
5685
5686/* Expand all variable references in given string, adding words to list[]
5687 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5688 * to be filled). This routine is extremely tricky: has to deal with
5689 * variables/parameters with whitespace, $* and $@, and constructs like
5690 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005691static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005692{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005693 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005694 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005695 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005696 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005697 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005698 char *p;
5699
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005700 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5701 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005702 debug_print_list("expand_vars_to_list", output, n);
5703 n = o_save_ptr(output, n);
5704 debug_print_list("expand_vars_to_list[0]", output, n);
5705
5706 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5707 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005708 char *to_be_freed = NULL;
5709 const char *val = NULL;
5710#if ENABLE_HUSH_TICK
5711 o_string subst_result = NULL_O_STRING;
5712#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01005713#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005714 char arith_buf[sizeof(arith_t)*3 + 2];
5715#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005716
5717 if (ended_in_ifs) {
5718 o_addchr(output, '\0');
5719 n = o_save_ptr(output, n);
5720 ended_in_ifs = 0;
5721 }
5722
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005723 o_addblock(output, arg, p - arg);
5724 debug_print_list("expand_vars_to_list[1]", output, n);
5725 arg = ++p;
5726 p = strchr(p, SPECIAL_VAR_SYMBOL);
5727
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005728 /* Fetch special var name (if it is indeed one of them)
5729 * and quote bit, force the bit on if singleword expansion -
5730 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005731 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005732
5733 /* Is this variable quoted and thus expansion can't be null?
5734 * "$@" is special. Even if quoted, it can still
5735 * expand to nothing (not even an empty string),
5736 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005737 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005738 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005739
5740 switch (first_ch & 0x7f) {
5741 /* Highest bit in first_ch indicates that var is double-quoted */
5742 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005743 case '@': {
5744 int i;
5745 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005746 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005747 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005748 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005749 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005750 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005751 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005752 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5753 if (G.global_argv[i++][0] && G.global_argv[i]) {
5754 /* this argv[] is not empty and not last:
5755 * put terminating NUL, start new word */
5756 o_addchr(output, '\0');
5757 debug_print_list("expand_vars_to_list[2]", output, n);
5758 n = o_save_ptr(output, n);
5759 debug_print_list("expand_vars_to_list[3]", output, n);
5760 }
5761 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005762 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005763 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005764 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005765 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005766 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005767 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005768 while (1) {
5769 o_addQstr(output, G.global_argv[i]);
5770 if (++i >= G.global_argc)
5771 break;
5772 o_addchr(output, '\0');
5773 debug_print_list("expand_vars_to_list[4]", output, n);
5774 n = o_save_ptr(output, n);
5775 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005776 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005777 while (1) {
5778 o_addQstr(output, G.global_argv[i]);
5779 if (!G.global_argv[++i])
5780 break;
5781 if (G.ifs[0])
5782 o_addchr(output, G.ifs[0]);
5783 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005784 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005785 }
5786 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005787 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005788 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5789 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005790 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005791 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005792 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005793 break;
5794#if ENABLE_HUSH_TICK
5795 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005796 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005797 arg++;
5798 /* Can't just stuff it into output o_string,
5799 * expanded result may need to be globbed
5800 * and $IFS-splitted */
5801 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5802 G.last_exitcode = process_command_subs(&subst_result, arg);
5803 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5804 val = subst_result.data;
5805 goto store_val;
5806#endif
Denys Vlasenko0b883582016-12-23 16:49:07 +01005807#if ENABLE_FEATURE_SH_MATH
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005808 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5809 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005810
5811 arg++; /* skip '+' */
5812 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5813 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005814 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005815 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5816 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005817 val = arith_buf;
5818 break;
5819 }
5820#endif
5821 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005822 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005823 IF_HUSH_TICK(store_val:)
5824 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005825 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5826 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005827 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005828 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005829 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005830 }
5831 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005832 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005833 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5834 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005835 }
5836 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005837 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5838
5839 if (val && val[0]) {
5840 o_addQstr(output, val);
5841 }
5842 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005843
5844 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5845 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005846 if (*p != SPECIAL_VAR_SYMBOL)
5847 *p = SPECIAL_VAR_SYMBOL;
5848
5849#if ENABLE_HUSH_TICK
5850 o_free(&subst_result);
5851#endif
5852 arg = ++p;
5853 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5854
5855 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005856 if (ended_in_ifs) {
5857 o_addchr(output, '\0');
5858 n = o_save_ptr(output, n);
5859 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005860 debug_print_list("expand_vars_to_list[a]", output, n);
5861 /* this part is literal, and it was already pre-quoted
5862 * if needed (much earlier), do not use o_addQstr here! */
5863 o_addstr_with_NUL(output, arg);
5864 debug_print_list("expand_vars_to_list[b]", output, n);
5865 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005866 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005867 ) {
5868 n--;
5869 /* allow to reuse list[n] later without re-growth */
5870 output->has_empty_slot = 1;
5871 } else {
5872 o_addchr(output, '\0');
5873 }
5874
5875 return n;
5876}
5877
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005878static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005879{
5880 int n;
5881 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005882 o_string output = NULL_O_STRING;
5883
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005884 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005885
5886 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005887 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005888 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005889 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005890 }
5891 debug_print_list("expand_variables", &output, n);
5892
5893 /* output.data (malloced in one block) gets returned in "list" */
5894 list = o_finalize_list(&output, n);
5895 debug_print_strings("expand_variables[1]", list);
5896 return list;
5897}
5898
5899static char **expand_strvec_to_strvec(char **argv)
5900{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005901 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005902}
5903
5904#if ENABLE_HUSH_BASH_COMPAT
5905static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5906{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005907 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005908}
5909#endif
5910
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005911/* Used for expansion of right hand of assignments,
5912 * $((...)), heredocs, variable espansion parts.
5913 *
5914 * NB: should NOT do globbing!
5915 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5916 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005917static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005918{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005919#if !ENABLE_HUSH_BASH_COMPAT
5920 const int do_unbackslash = 1;
5921#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005922 char *argv[2], **list;
5923
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005924 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005925 /* This is generally an optimization, but it also
5926 * handles "", which otherwise trips over !list[0] check below.
5927 * (is this ever happens that we actually get str="" here?)
5928 */
5929 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5930 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005931 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005932 return xstrdup(str);
5933 }
5934
5935 argv[0] = (char*)str;
5936 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005937 list = expand_variables(argv, do_unbackslash
5938 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5939 : EXP_FLAG_SINGLEWORD
5940 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005941 if (HUSH_DEBUG)
5942 if (!list[0] || list[1])
5943 bb_error_msg_and_die("BUG in varexp2");
5944 /* actually, just move string 2*sizeof(char*) bytes back */
5945 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005946 if (do_unbackslash)
5947 unbackslash((char*)list);
5948 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005949 return (char*)list;
5950}
5951
5952/* Used for "eval" builtin */
5953static char* expand_strvec_to_string(char **argv)
5954{
5955 char **list;
5956
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005957 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005958 /* Convert all NULs to spaces */
5959 if (list[0]) {
5960 int n = 1;
5961 while (list[n]) {
5962 if (HUSH_DEBUG)
5963 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5964 bb_error_msg_and_die("BUG in varexp3");
5965 /* bash uses ' ' regardless of $IFS contents */
5966 list[n][-1] = ' ';
5967 n++;
5968 }
5969 }
Denys Vlasenko78c9c732016-09-29 01:44:17 +02005970 overlapping_strcpy((char*)list, list[0] ? list[0] : "");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005971 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5972 return (char*)list;
5973}
5974
5975static char **expand_assignments(char **argv, int count)
5976{
5977 int i;
5978 char **p;
5979
5980 G.expanded_assignments = p = NULL;
5981 /* Expand assignments into one string each */
5982 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005983 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005984 }
5985 G.expanded_assignments = NULL;
5986 return p;
5987}
5988
5989
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005990static void switch_off_special_sigs(unsigned mask)
5991{
5992 unsigned sig = 0;
5993 while ((mask >>= 1) != 0) {
5994 sig++;
5995 if (!(mask & 1))
5996 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01005997#if ENABLE_HUSH_TRAP
5998 if (G_traps) {
5999 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006000 /* trap is '', has to remain SIG_IGN */
6001 continue;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006002 free(G_traps[sig]);
6003 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006004 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006005#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006006 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02006007 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006008 }
6009}
6010
Denys Vlasenkob347df92011-08-09 22:49:15 +02006011#if BB_MMU
6012/* never called */
6013void re_execute_shell(char ***to_free, const char *s,
6014 char *g_argv0, char **g_argv,
6015 char **builtin_argv) NORETURN;
6016
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006017static void reset_traps_to_defaults(void)
6018{
6019 /* This function is always called in a child shell
6020 * after fork (not vfork, NOMMU doesn't use this function).
6021 */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006022 IF_HUSH_TRAP(unsigned sig;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006023 unsigned mask;
6024
6025 /* Child shells are not interactive.
6026 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
6027 * Testcase: (while :; do :; done) + ^Z should background.
6028 * Same goes for SIGTERM, SIGHUP, SIGINT.
6029 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006030 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006031 if (!G_traps && !mask)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006032 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006033
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006034 /* Switch off special sigs */
6035 switch_off_special_sigs(mask);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006036# if ENABLE_HUSH_JOB
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006037 G_fatal_sig_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006038# endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02006039 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02006040 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
6041 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006042
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006043# if ENABLE_HUSH_TRAP
6044 if (!G_traps)
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006045 return;
6046
6047 /* Reset all sigs to default except ones with empty traps */
6048 for (sig = 0; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006049 if (!G_traps[sig])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006050 continue; /* no trap: nothing to do */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006051 if (!G_traps[sig][0])
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006052 continue; /* empty trap: has to remain SIG_IGN */
6053 /* sig has non-empty trap, reset it: */
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006054 free(G_traps[sig]);
6055 G_traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02006056 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006057 if (sig == 0)
6058 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02006059 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006060 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006061# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006062}
6063
6064#else /* !BB_MMU */
6065
6066static void re_execute_shell(char ***to_free, const char *s,
6067 char *g_argv0, char **g_argv,
6068 char **builtin_argv) NORETURN;
6069static void re_execute_shell(char ***to_free, const char *s,
6070 char *g_argv0, char **g_argv,
6071 char **builtin_argv)
6072{
6073# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
6074 /* delims + 2 * (number of bytes in printed hex numbers) */
6075 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
6076 char *heredoc_argv[4];
6077 struct variable *cur;
6078# if ENABLE_HUSH_FUNCTIONS
6079 struct function *funcp;
6080# endif
6081 char **argv, **pp;
6082 unsigned cnt;
6083 unsigned long long empty_trap_mask;
6084
6085 if (!g_argv0) { /* heredoc */
6086 argv = heredoc_argv;
6087 argv[0] = (char *) G.argv0_for_re_execing;
6088 argv[1] = (char *) "-<";
6089 argv[2] = (char *) s;
6090 argv[3] = NULL;
6091 pp = &argv[3]; /* used as pointer to empty environment */
6092 goto do_exec;
6093 }
6094
6095 cnt = 0;
6096 pp = builtin_argv;
6097 if (pp) while (*pp++)
6098 cnt++;
6099
6100 empty_trap_mask = 0;
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006101 if (G_traps) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006102 int sig;
6103 for (sig = 1; sig < NSIG; sig++) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006104 if (G_traps[sig] && !G_traps[sig][0])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006105 empty_trap_mask |= 1LL << sig;
6106 }
6107 }
6108
6109 sprintf(param_buf, NOMMU_HACK_FMT
6110 , (unsigned) G.root_pid
6111 , (unsigned) G.root_ppid
6112 , (unsigned) G.last_bg_pid
6113 , (unsigned) G.last_exitcode
6114 , cnt
6115 , empty_trap_mask
6116 IF_HUSH_LOOPS(, G.depth_of_loop)
6117 );
6118# undef NOMMU_HACK_FMT
6119 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
6120 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
6121 */
6122 cnt += 6;
6123 for (cur = G.top_var; cur; cur = cur->next) {
6124 if (!cur->flg_export || cur->flg_read_only)
6125 cnt += 2;
6126 }
6127# if ENABLE_HUSH_FUNCTIONS
6128 for (funcp = G.top_func; funcp; funcp = funcp->next)
6129 cnt += 3;
6130# endif
6131 pp = g_argv;
6132 while (*pp++)
6133 cnt++;
6134 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
6135 *pp++ = (char *) G.argv0_for_re_execing;
6136 *pp++ = param_buf;
6137 for (cur = G.top_var; cur; cur = cur->next) {
6138 if (strcmp(cur->varstr, hush_version_str) == 0)
6139 continue;
6140 if (cur->flg_read_only) {
6141 *pp++ = (char *) "-R";
6142 *pp++ = cur->varstr;
6143 } else if (!cur->flg_export) {
6144 *pp++ = (char *) "-V";
6145 *pp++ = cur->varstr;
6146 }
6147 }
6148# if ENABLE_HUSH_FUNCTIONS
6149 for (funcp = G.top_func; funcp; funcp = funcp->next) {
6150 *pp++ = (char *) "-F";
6151 *pp++ = funcp->name;
6152 *pp++ = funcp->body_as_string;
6153 }
6154# endif
6155 /* We can pass activated traps here. Say, -Tnn:trap_string
6156 *
6157 * However, POSIX says that subshells reset signals with traps
6158 * to SIG_DFL.
6159 * I tested bash-3.2 and it not only does that with true subshells
6160 * of the form ( list ), but with any forked children shells.
6161 * I set trap "echo W" WINCH; and then tried:
6162 *
6163 * { echo 1; sleep 20; echo 2; } &
6164 * while true; do echo 1; sleep 20; echo 2; break; done &
6165 * true | { echo 1; sleep 20; echo 2; } | cat
6166 *
6167 * In all these cases sending SIGWINCH to the child shell
6168 * did not run the trap. If I add trap "echo V" WINCH;
6169 * _inside_ group (just before echo 1), it works.
6170 *
6171 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006172 */
6173 *pp++ = (char *) "-c";
6174 *pp++ = (char *) s;
6175 if (builtin_argv) {
6176 while (*++builtin_argv)
6177 *pp++ = *builtin_argv;
6178 *pp++ = (char *) "";
6179 }
6180 *pp++ = g_argv0;
6181 while (*g_argv)
6182 *pp++ = *g_argv++;
6183 /* *pp = NULL; - is already there */
6184 pp = environ;
6185
6186 do_exec:
6187 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006188 /* Don't propagate SIG_IGN to the child */
6189 if (SPECIAL_JOBSTOP_SIGS != 0)
6190 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006191 execve(bb_busybox_exec_path, argv, pp);
6192 /* Fallback. Useful for init=/bin/hush usage etc */
6193 if (argv[0][0] == '/')
6194 execve(argv[0], argv, pp);
6195 xfunc_error_retval = 127;
6196 bb_error_msg_and_die("can't re-execute the shell");
6197}
6198#endif /* !BB_MMU */
6199
6200
6201static int run_and_free_list(struct pipe *pi);
6202
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006203/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006204 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6205 * end_trigger controls how often we stop parsing
6206 * NUL: parse all, execute, return
6207 * ';': parse till ';' or newline, execute, repeat till EOF
6208 */
6209static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006210{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006211 /* Why we need empty flag?
6212 * An obscure corner case "false; ``; echo $?":
6213 * empty command in `` should still set $? to 0.
6214 * But we can't just set $? to 0 at the start,
6215 * this breaks "false; echo `echo $?`" case.
6216 */
6217 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006218 while (1) {
6219 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006220
Denys Vlasenkoa1463192011-01-18 17:55:04 +01006221#if ENABLE_HUSH_INTERACTIVE
6222 if (end_trigger == ';')
6223 inp->promptmode = 0; /* PS1 */
6224#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006225 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02006226 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
6227 /* If we are in "big" script
6228 * (not in `cmd` or something similar)...
6229 */
6230 if (pipe_list == ERR_PTR && end_trigger == ';') {
6231 /* Discard cached input (rest of line) */
6232 int ch = inp->last_char;
6233 while (ch != EOF && ch != '\n') {
6234 //bb_error_msg("Discarded:'%c'", ch);
6235 ch = i_getch(inp);
6236 }
6237 /* Force prompt */
6238 inp->p = NULL;
6239 /* This stream isn't empty */
6240 empty = 0;
6241 continue;
6242 }
6243 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01006244 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006245 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006246 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006247 debug_print_tree(pipe_list, 0);
6248 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6249 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006250 empty = 0;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006251 if (G_flag_return_in_progress == 1)
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01006252 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006253 }
Eric Andersen25f27032001-04-26 23:22:31 +00006254}
6255
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006256static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006257{
6258 struct in_str input;
6259 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006260 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006261}
6262
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006263static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006264{
Eric Andersen25f27032001-04-26 23:22:31 +00006265 struct in_str input;
6266 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006267 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006268}
6269
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006270#if ENABLE_HUSH_TICK
6271static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
6272{
6273 pid_t pid;
6274 int channel[2];
6275# if !BB_MMU
6276 char **to_free = NULL;
6277# endif
6278
6279 xpipe(channel);
6280 pid = BB_MMU ? xfork() : xvfork();
6281 if (pid == 0) { /* child */
6282 disable_restore_tty_pgrp_on_exit();
6283 /* Process substitution is not considered to be usual
6284 * 'command execution'.
6285 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
6286 */
6287 bb_signals(0
6288 + (1 << SIGTSTP)
6289 + (1 << SIGTTIN)
6290 + (1 << SIGTTOU)
6291 , SIG_IGN);
6292 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6293 close(channel[0]); /* NB: close _first_, then move fd! */
6294 xmove_fd(channel[1], 1);
6295 /* Prevent it from trying to handle ctrl-z etc */
6296 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006297# if ENABLE_HUSH_TRAP
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006298 /* Awful hack for `trap` or $(trap).
6299 *
6300 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
6301 * contains an example where "trap" is executed in a subshell:
6302 *
6303 * save_traps=$(trap)
6304 * ...
6305 * eval "$save_traps"
6306 *
6307 * Standard does not say that "trap" in subshell shall print
6308 * parent shell's traps. It only says that its output
6309 * must have suitable form, but then, in the above example
6310 * (which is not supposed to be normative), it implies that.
6311 *
6312 * bash (and probably other shell) does implement it
6313 * (traps are reset to defaults, but "trap" still shows them),
6314 * but as a result, "trap" logic is hopelessly messed up:
6315 *
6316 * # trap
6317 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
6318 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
6319 * # true | trap <--- trap is in subshell - no output (ditto)
6320 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
6321 * trap -- 'echo Ho' SIGWINCH
6322 * # echo `(trap)` <--- in subshell in subshell - output
6323 * trap -- 'echo Ho' SIGWINCH
6324 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
6325 * trap -- 'echo Ho' SIGWINCH
6326 *
6327 * The rules when to forget and when to not forget traps
6328 * get really complex and nonsensical.
6329 *
6330 * Our solution: ONLY bare $(trap) or `trap` is special.
6331 */
6332 s = skip_whitespace(s);
Denys Vlasenko8dff01d2015-03-12 17:48:34 +01006333 if (is_prefixed_with(s, "trap")
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006334 && skip_whitespace(s + 4)[0] == '\0'
6335 ) {
6336 static const char *const argv[] = { NULL, NULL };
6337 builtin_trap((char**)argv);
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02006338 fflush_all(); /* important */
6339 _exit(0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006340 }
Denys Vlasenko7a85c602017-01-08 17:40:18 +01006341# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006342# if BB_MMU
6343 reset_traps_to_defaults();
6344 parse_and_run_string(s);
6345 _exit(G.last_exitcode);
6346# else
6347 /* We re-execute after vfork on NOMMU. This makes this script safe:
6348 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
6349 * huge=`cat BIG` # was blocking here forever
6350 * echo OK
6351 */
6352 re_execute_shell(&to_free,
6353 s,
6354 G.global_argv[0],
6355 G.global_argv + 1,
6356 NULL);
6357# endif
6358 }
6359
6360 /* parent */
6361 *pid_p = pid;
6362# if ENABLE_HUSH_FAST
6363 G.count_SIGCHLD++;
6364//bb_error_msg("[%d] fork in generate_stream_from_string:"
6365// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
6366// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6367# endif
6368 enable_restore_tty_pgrp_on_exit();
6369# if !BB_MMU
6370 free(to_free);
6371# endif
6372 close(channel[1]);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006373 return remember_FILE(xfdopen_for_read(channel[0]));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006374}
6375
6376/* Return code is exit status of the process that is run. */
6377static int process_command_subs(o_string *dest, const char *s)
6378{
6379 FILE *fp;
6380 struct in_str pipe_str;
6381 pid_t pid;
6382 int status, ch, eol_cnt;
6383
6384 fp = generate_stream_from_string(s, &pid);
6385
6386 /* Now send results of command back into original context */
6387 setup_file_in_str(&pipe_str, fp);
6388 eol_cnt = 0;
6389 while ((ch = i_getch(&pipe_str)) != EOF) {
6390 if (ch == '\n') {
6391 eol_cnt++;
6392 continue;
6393 }
6394 while (eol_cnt) {
6395 o_addchr(dest, '\n');
6396 eol_cnt--;
6397 }
6398 o_addQchr(dest, ch);
6399 }
6400
6401 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02006402 fclose_and_forget(fp);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006403 /* We need to extract exitcode. Test case
6404 * "true; echo `sleep 1; false` $?"
6405 * should print 1 */
6406 safe_waitpid(pid, &status, 0);
6407 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
6408 return WEXITSTATUS(status);
6409}
6410#endif /* ENABLE_HUSH_TICK */
6411
6412
6413static void setup_heredoc(struct redir_struct *redir)
6414{
6415 struct fd_pair pair;
6416 pid_t pid;
6417 int len, written;
6418 /* the _body_ of heredoc (misleading field name) */
6419 const char *heredoc = redir->rd_filename;
6420 char *expanded;
6421#if !BB_MMU
6422 char **to_free;
6423#endif
6424
6425 expanded = NULL;
6426 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02006427 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006428 if (expanded)
6429 heredoc = expanded;
6430 }
6431 len = strlen(heredoc);
6432
6433 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
6434 xpiped_pair(pair);
6435 xmove_fd(pair.rd, redir->rd_fd);
6436
6437 /* Try writing without forking. Newer kernels have
6438 * dynamically growing pipes. Must use non-blocking write! */
6439 ndelay_on(pair.wr);
6440 while (1) {
6441 written = write(pair.wr, heredoc, len);
6442 if (written <= 0)
6443 break;
6444 len -= written;
6445 if (len == 0) {
6446 close(pair.wr);
6447 free(expanded);
6448 return;
6449 }
6450 heredoc += written;
6451 }
6452 ndelay_off(pair.wr);
6453
6454 /* Okay, pipe buffer was not big enough */
6455 /* Note: we must not create a stray child (bastard? :)
6456 * for the unsuspecting parent process. Child creates a grandchild
6457 * and exits before parent execs the process which consumes heredoc
6458 * (that exec happens after we return from this function) */
6459#if !BB_MMU
6460 to_free = NULL;
6461#endif
6462 pid = xvfork();
6463 if (pid == 0) {
6464 /* child */
6465 disable_restore_tty_pgrp_on_exit();
6466 pid = BB_MMU ? xfork() : xvfork();
6467 if (pid != 0)
6468 _exit(0);
6469 /* grandchild */
6470 close(redir->rd_fd); /* read side of the pipe */
6471#if BB_MMU
6472 full_write(pair.wr, heredoc, len); /* may loop or block */
6473 _exit(0);
6474#else
6475 /* Delegate blocking writes to another process */
6476 xmove_fd(pair.wr, STDOUT_FILENO);
6477 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6478#endif
6479 }
6480 /* parent */
6481#if ENABLE_HUSH_FAST
6482 G.count_SIGCHLD++;
6483//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6484#endif
6485 enable_restore_tty_pgrp_on_exit();
6486#if !BB_MMU
6487 free(to_free);
6488#endif
6489 close(pair.wr);
6490 free(expanded);
6491 wait(NULL); /* wait till child has died */
6492}
6493
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006494/* fd: redirect wants this fd to be used (e.g. 3>file).
6495 * Move all conflicting internally used fds,
6496 * and remember them so that we can restore them later.
6497 */
6498static int save_fds_on_redirect(int fd, int squirrel[3])
6499{
6500 if (squirrel) {
6501 /* Handle redirects of fds 0,1,2 */
6502
6503 /* If we collide with an already moved stdio fd... */
6504 if (fd == squirrel[0]) {
6505 squirrel[0] = xdup_and_close(squirrel[0], F_DUPFD);
6506 return 1;
6507 }
6508 if (fd == squirrel[1]) {
6509 squirrel[1] = xdup_and_close(squirrel[1], F_DUPFD);
6510 return 1;
6511 }
6512 if (fd == squirrel[2]) {
6513 squirrel[2] = xdup_and_close(squirrel[2], F_DUPFD);
6514 return 1;
6515 }
6516 /* If we are about to redirect stdio fd, and did not yet move it... */
6517 if (fd <= 2 && squirrel[fd] < 0) {
6518 /* We avoid taking stdio fds */
6519 squirrel[fd] = fcntl(fd, F_DUPFD, 10);
6520 if (squirrel[fd] < 0 && errno != EBADF)
6521 xfunc_die();
6522 return 0; /* "we did not close fd" */
6523 }
6524 }
6525
6526#if ENABLE_HUSH_INTERACTIVE
6527 if (fd != 0 && fd == G.interactive_fd) {
6528 G.interactive_fd = xdup_and_close(G.interactive_fd, F_DUPFD_CLOEXEC);
6529 return 1;
6530 }
6531#endif
6532
6533 /* Are we called from setup_redirects(squirrel==NULL)? Two cases:
6534 * (1) Redirect in a forked child. No need to save FILEs' fds,
6535 * we aren't going to use them anymore, ok to trash.
6536 * (2) "exec 3>FILE". Bummer. We can save FILEs' fds,
6537 * but how are we doing to use them?
6538 * "fileno(fd) = new_fd" can't be done.
6539 */
6540 if (!squirrel)
6541 return 0;
6542
6543 return save_FILEs_on_redirect(fd);
6544}
6545
6546static void restore_redirects(int squirrel[3])
6547{
6548 int i, fd;
6549 for (i = 0; i <= 2; i++) {
6550 fd = squirrel[i];
6551 if (fd != -1) {
6552 /* We simply die on error */
6553 xmove_fd(fd, i);
6554 }
6555 }
6556
6557 /* Moved G.interactive_fd stays on new fd, not doing anything for it */
6558
6559 restore_redirected_FILEs();
6560}
6561
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006562/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6563 * and stderr if they are redirected. */
6564static int setup_redirects(struct command *prog, int squirrel[])
6565{
6566 int openfd, mode;
6567 struct redir_struct *redir;
6568
6569 for (redir = prog->redirects; redir; redir = redir->next) {
6570 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006571 /* "rd_fd<<HERE" case */
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006572 save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006573 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6574 * of the heredoc */
6575 debug_printf_parse("set heredoc '%s'\n",
6576 redir->rd_filename);
6577 setup_heredoc(redir);
6578 continue;
6579 }
6580
6581 if (redir->rd_dup == REDIRFD_TO_FILE) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006582 /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006583 char *p;
6584 if (redir->rd_filename == NULL) {
Denys Vlasenkod6a37d82016-09-20 16:22:24 +02006585 /*
6586 * Examples:
6587 * "cmd >" (no filename)
6588 * "cmd > <file" (2nd redirect starts too early)
6589 */
6590 die_if_script("syntax error: %s", "invalid redirect");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006591 continue;
6592 }
6593 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006594 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006595 openfd = open_or_warn(p, mode);
6596 free(p);
6597 if (openfd < 0) {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006598 /* Error message from open_or_warn can be lost
6599 * if stderr has been redirected, but bash
6600 * and ash both lose it as well
6601 * (though zsh doesn't!)
6602 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006603 return 1;
6604 }
6605 } else {
Denys Vlasenko869994c2016-08-20 15:16:00 +02006606 /* "rd_fd<*>rd_dup" or "rd_fd<*>-" cases */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006607 openfd = redir->rd_dup;
6608 }
6609
6610 if (openfd != redir->rd_fd) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006611 int closed = save_fds_on_redirect(redir->rd_fd, squirrel);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006612 if (openfd == REDIRFD_CLOSE) {
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006613 /* "rd_fd >&-" means "close me" */
6614 if (!closed) {
6615 /* ^^^ optimization: saving may already
6616 * have closed it. If not... */
6617 close(redir->rd_fd);
6618 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006619 } else {
6620 xdup2(openfd, redir->rd_fd);
6621 if (redir->rd_dup == REDIRFD_TO_FILE)
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006622 /* "rd_fd > FILE" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006623 close(openfd);
Denys Vlasenkoaa3576a2016-08-22 19:54:12 +02006624 /* else: "rd_fd > rd_dup" */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006625 }
6626 }
6627 }
6628 return 0;
6629}
6630
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006631static char *find_in_path(const char *arg)
6632{
6633 char *ret = NULL;
6634 const char *PATH = get_local_var_value("PATH");
6635
6636 if (!PATH)
6637 return NULL;
6638
6639 while (1) {
6640 const char *end = strchrnul(PATH, ':');
6641 int sz = end - PATH; /* must be int! */
6642
6643 free(ret);
6644 if (sz != 0) {
6645 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6646 } else {
6647 /* We have xxx::yyyy in $PATH,
6648 * it means "use current dir" */
6649 ret = xstrdup(arg);
6650 }
6651 if (access(ret, F_OK) == 0)
6652 break;
6653
6654 if (*end == '\0') {
6655 free(ret);
6656 return NULL;
6657 }
6658 PATH = end + 1;
6659 }
6660
6661 return ret;
6662}
6663
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006664static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006665 const struct built_in_command *x,
6666 const struct built_in_command *end)
6667{
6668 while (x != end) {
6669 if (strcmp(name, x->b_cmd) != 0) {
6670 x++;
6671 continue;
6672 }
6673 debug_printf_exec("found builtin '%s'\n", name);
6674 return x;
6675 }
6676 return NULL;
6677}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006678static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006679{
6680 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6681}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006682static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006683{
6684 const struct built_in_command *x = find_builtin1(name);
6685 if (x)
6686 return x;
6687 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6688}
6689
6690#if ENABLE_HUSH_FUNCTIONS
6691static struct function **find_function_slot(const char *name)
6692{
6693 struct function **funcpp = &G.top_func;
6694 while (*funcpp) {
6695 if (strcmp(name, (*funcpp)->name) == 0) {
6696 break;
6697 }
6698 funcpp = &(*funcpp)->next;
6699 }
6700 return funcpp;
6701}
6702
6703static const struct function *find_function(const char *name)
6704{
6705 const struct function *funcp = *find_function_slot(name);
6706 if (funcp)
6707 debug_printf_exec("found function '%s'\n", name);
6708 return funcp;
6709}
6710
6711/* Note: takes ownership on name ptr */
6712static struct function *new_function(char *name)
6713{
6714 struct function **funcpp = find_function_slot(name);
6715 struct function *funcp = *funcpp;
6716
6717 if (funcp != NULL) {
6718 struct command *cmd = funcp->parent_cmd;
6719 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6720 if (!cmd) {
6721 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6722 free(funcp->name);
6723 /* Note: if !funcp->body, do not free body_as_string!
6724 * This is a special case of "-F name body" function:
6725 * body_as_string was not malloced! */
6726 if (funcp->body) {
6727 free_pipe_list(funcp->body);
6728# if !BB_MMU
6729 free(funcp->body_as_string);
6730# endif
6731 }
6732 } else {
6733 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6734 cmd->argv[0] = funcp->name;
6735 cmd->group = funcp->body;
6736# if !BB_MMU
6737 cmd->group_as_string = funcp->body_as_string;
6738# endif
6739 }
6740 } else {
6741 debug_printf_exec("remembering new function '%s'\n", name);
6742 funcp = *funcpp = xzalloc(sizeof(*funcp));
6743 /*funcp->next = NULL;*/
6744 }
6745
6746 funcp->name = name;
6747 return funcp;
6748}
6749
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01006750# if ENABLE_HUSH_UNSET
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006751static void unset_func(const char *name)
6752{
6753 struct function **funcpp = find_function_slot(name);
6754 struct function *funcp = *funcpp;
6755
6756 if (funcp != NULL) {
6757 debug_printf_exec("freeing function '%s'\n", funcp->name);
6758 *funcpp = funcp->next;
6759 /* funcp is unlinked now, deleting it.
6760 * Note: if !funcp->body, the function was created by
6761 * "-F name body", do not free ->body_as_string
6762 * and ->name as they were not malloced. */
6763 if (funcp->body) {
6764 free_pipe_list(funcp->body);
6765 free(funcp->name);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01006766# if !BB_MMU
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006767 free(funcp->body_as_string);
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01006768# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006769 }
6770 free(funcp);
6771 }
6772}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01006773# endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006774
6775# if BB_MMU
6776#define exec_function(to_free, funcp, argv) \
6777 exec_function(funcp, argv)
6778# endif
6779static void exec_function(char ***to_free,
6780 const struct function *funcp,
6781 char **argv) NORETURN;
6782static void exec_function(char ***to_free,
6783 const struct function *funcp,
6784 char **argv)
6785{
6786# if BB_MMU
6787 int n = 1;
6788
6789 argv[0] = G.global_argv[0];
6790 G.global_argv = argv;
6791 while (*++argv)
6792 n++;
6793 G.global_argc = n;
6794 /* On MMU, funcp->body is always non-NULL */
6795 n = run_list(funcp->body);
6796 fflush_all();
6797 _exit(n);
6798# else
6799 re_execute_shell(to_free,
6800 funcp->body_as_string,
6801 G.global_argv[0],
6802 argv + 1,
6803 NULL);
6804# endif
6805}
6806
6807static int run_function(const struct function *funcp, char **argv)
6808{
6809 int rc;
6810 save_arg_t sv;
6811 smallint sv_flg;
6812
6813 save_and_replace_G_args(&sv, argv);
6814
6815 /* "we are in function, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006816 sv_flg = G_flag_return_in_progress;
6817 G_flag_return_in_progress = -1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006818# if ENABLE_HUSH_LOCAL
6819 G.func_nest_level++;
6820# endif
6821
6822 /* On MMU, funcp->body is always non-NULL */
6823# if !BB_MMU
6824 if (!funcp->body) {
6825 /* Function defined by -F */
6826 parse_and_run_string(funcp->body_as_string);
6827 rc = G.last_exitcode;
6828 } else
6829# endif
6830 {
6831 rc = run_list(funcp->body);
6832 }
6833
6834# if ENABLE_HUSH_LOCAL
6835 {
6836 struct variable *var;
6837 struct variable **var_pp;
6838
6839 var_pp = &G.top_var;
6840 while ((var = *var_pp) != NULL) {
6841 if (var->func_nest_level < G.func_nest_level) {
6842 var_pp = &var->next;
6843 continue;
6844 }
6845 /* Unexport */
6846 if (var->flg_export)
6847 bb_unsetenv(var->varstr);
6848 /* Remove from global list */
6849 *var_pp = var->next;
6850 /* Free */
6851 if (!var->max_len)
6852 free(var->varstr);
6853 free(var);
6854 }
6855 G.func_nest_level--;
6856 }
6857# endif
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02006858 G_flag_return_in_progress = sv_flg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006859
6860 restore_G_args(&sv, argv);
6861
6862 return rc;
6863}
6864#endif /* ENABLE_HUSH_FUNCTIONS */
6865
6866
6867#if BB_MMU
6868#define exec_builtin(to_free, x, argv) \
6869 exec_builtin(x, argv)
6870#else
6871#define exec_builtin(to_free, x, argv) \
6872 exec_builtin(to_free, argv)
6873#endif
6874static void exec_builtin(char ***to_free,
6875 const struct built_in_command *x,
6876 char **argv) NORETURN;
6877static void exec_builtin(char ***to_free,
6878 const struct built_in_command *x,
6879 char **argv)
6880{
6881#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006882 int rcode;
6883 fflush_all();
6884 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006885 fflush_all();
6886 _exit(rcode);
6887#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006888 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006889 /* On NOMMU, we must never block!
6890 * Example: { sleep 99 | read line; } & echo Ok
6891 */
6892 re_execute_shell(to_free,
6893 argv[0],
6894 G.global_argv[0],
6895 G.global_argv + 1,
6896 argv);
6897#endif
6898}
6899
6900
6901static void execvp_or_die(char **argv) NORETURN;
6902static void execvp_or_die(char **argv)
6903{
Denys Vlasenko04465da2016-10-03 01:01:15 +02006904 int e;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006905 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006906 /* Don't propagate SIG_IGN to the child */
6907 if (SPECIAL_JOBSTOP_SIGS != 0)
6908 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006909 execvp(argv[0], argv);
Denys Vlasenko04465da2016-10-03 01:01:15 +02006910 e = 2;
6911 if (errno == EACCES) e = 126;
6912 if (errno == ENOENT) e = 127;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006913 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenko04465da2016-10-03 01:01:15 +02006914 _exit(e);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006915}
6916
6917#if ENABLE_HUSH_MODE_X
6918static void dump_cmd_in_x_mode(char **argv)
6919{
6920 if (G_x_mode && argv) {
6921 /* We want to output the line in one write op */
6922 char *buf, *p;
6923 int len;
6924 int n;
6925
6926 len = 3;
6927 n = 0;
6928 while (argv[n])
6929 len += strlen(argv[n++]) + 1;
6930 buf = xmalloc(len);
6931 buf[0] = '+';
6932 p = buf + 1;
6933 n = 0;
6934 while (argv[n])
6935 p += sprintf(p, " %s", argv[n++]);
6936 *p++ = '\n';
6937 *p = '\0';
6938 fputs(buf, stderr);
6939 free(buf);
6940 }
6941}
6942#else
6943# define dump_cmd_in_x_mode(argv) ((void)0)
6944#endif
6945
6946#if BB_MMU
6947#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6948 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6949#define pseudo_exec(nommu_save, command, argv_expanded) \
6950 pseudo_exec(command, argv_expanded)
6951#endif
6952
6953/* Called after [v]fork() in run_pipe, or from builtin_exec.
6954 * Never returns.
6955 * Don't exit() here. If you don't exec, use _exit instead.
6956 * The at_exit handlers apparently confuse the calling process,
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006957 * in particular stdin handling. Not sure why? -- because of vfork! (vda)
Denys Vlasenko215b0ca2016-08-19 18:23:56 +02006958 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006959static void pseudo_exec_argv(nommu_save_t *nommu_save,
6960 char **argv, int assignment_cnt,
6961 char **argv_expanded) NORETURN;
6962static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6963 char **argv, int assignment_cnt,
6964 char **argv_expanded)
6965{
6966 char **new_env;
6967
6968 new_env = expand_assignments(argv, assignment_cnt);
6969 dump_cmd_in_x_mode(new_env);
6970
6971 if (!argv[assignment_cnt]) {
6972 /* Case when we are here: ... | var=val | ...
6973 * (note that we do not exit early, i.e., do not optimize out
6974 * expand_assignments(): think about ... | var=`sleep 1` | ...
6975 */
6976 free_strings(new_env);
6977 _exit(EXIT_SUCCESS);
6978 }
6979
6980#if BB_MMU
6981 set_vars_and_save_old(new_env);
6982 free(new_env); /* optional */
6983 /* we can also destroy set_vars_and_save_old's return value,
6984 * to save memory */
6985#else
6986 nommu_save->new_env = new_env;
6987 nommu_save->old_vars = set_vars_and_save_old(new_env);
6988#endif
6989
6990 if (argv_expanded) {
6991 argv = argv_expanded;
6992 } else {
6993 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6994#if !BB_MMU
6995 nommu_save->argv = argv;
6996#endif
6997 }
6998 dump_cmd_in_x_mode(argv);
6999
7000#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7001 if (strchr(argv[0], '/') != NULL)
7002 goto skip;
7003#endif
7004
7005 /* Check if the command matches any of the builtins.
7006 * Depending on context, this might be redundant. But it's
7007 * easier to waste a few CPU cycles than it is to figure out
7008 * if this is one of those cases.
7009 */
7010 {
7011 /* On NOMMU, it is more expensive to re-execute shell
7012 * just in order to run echo or test builtin.
7013 * It's better to skip it here and run corresponding
7014 * non-builtin later. */
7015 const struct built_in_command *x;
7016 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
7017 if (x) {
7018 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
7019 }
7020 }
7021#if ENABLE_HUSH_FUNCTIONS
7022 /* Check if the command matches any functions */
7023 {
7024 const struct function *funcp = find_function(argv[0]);
7025 if (funcp) {
7026 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
7027 }
7028 }
7029#endif
7030
7031#if ENABLE_FEATURE_SH_STANDALONE
7032 /* Check if the command matches any busybox applets */
7033 {
7034 int a = find_applet_by_name(argv[0]);
7035 if (a >= 0) {
7036# if BB_MMU /* see above why on NOMMU it is not allowed */
7037 if (APPLET_IS_NOEXEC(a)) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02007038 /* Do not leak open fds from opened script files etc */
7039 close_all_FILE_list();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007040 debug_printf_exec("running applet '%s'\n", argv[0]);
7041 run_applet_no_and_exit(a, argv);
7042 }
7043# endif
7044 /* Re-exec ourselves */
7045 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02007046 /* Don't propagate SIG_IGN to the child */
7047 if (SPECIAL_JOBSTOP_SIGS != 0)
7048 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007049 execv(bb_busybox_exec_path, argv);
7050 /* If they called chroot or otherwise made the binary no longer
7051 * executable, fall through */
7052 }
7053 }
7054#endif
7055
7056#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
7057 skip:
7058#endif
7059 execvp_or_die(argv);
7060}
7061
7062/* Called after [v]fork() in run_pipe
7063 */
7064static void pseudo_exec(nommu_save_t *nommu_save,
7065 struct command *command,
7066 char **argv_expanded) NORETURN;
7067static void pseudo_exec(nommu_save_t *nommu_save,
7068 struct command *command,
7069 char **argv_expanded)
7070{
7071 if (command->argv) {
7072 pseudo_exec_argv(nommu_save, command->argv,
7073 command->assignment_cnt, argv_expanded);
7074 }
7075
7076 if (command->group) {
7077 /* Cases when we are here:
7078 * ( list )
7079 * { list } &
7080 * ... | ( list ) | ...
7081 * ... | { list } | ...
7082 */
7083#if BB_MMU
7084 int rcode;
7085 debug_printf_exec("pseudo_exec: run_list\n");
7086 reset_traps_to_defaults();
7087 rcode = run_list(command->group);
7088 /* OK to leak memory by not calling free_pipe_list,
7089 * since this process is about to exit */
7090 _exit(rcode);
7091#else
7092 re_execute_shell(&nommu_save->argv_from_re_execing,
7093 command->group_as_string,
7094 G.global_argv[0],
7095 G.global_argv + 1,
7096 NULL);
7097#endif
7098 }
7099
7100 /* Case when we are here: ... | >file */
7101 debug_printf_exec("pseudo_exec'ed null command\n");
7102 _exit(EXIT_SUCCESS);
7103}
7104
7105#if ENABLE_HUSH_JOB
7106static const char *get_cmdtext(struct pipe *pi)
7107{
7108 char **argv;
7109 char *p;
7110 int len;
7111
7112 /* This is subtle. ->cmdtext is created only on first backgrounding.
7113 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
7114 * On subsequent bg argv is trashed, but we won't use it */
7115 if (pi->cmdtext)
7116 return pi->cmdtext;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007117
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007118 argv = pi->cmds[0].argv;
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007119 if (!argv) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007120 pi->cmdtext = xzalloc(1);
7121 return pi->cmdtext;
7122 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007123 len = 0;
7124 do {
7125 len += strlen(*argv) + 1;
7126 } while (*++argv);
7127 p = xmalloc(len);
7128 pi->cmdtext = p;
7129 argv = pi->cmds[0].argv;
7130 do {
Denys Vlasenko1eada9a2016-11-08 17:28:45 +01007131 p = stpcpy(p, *argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007132 *p++ = ' ';
7133 } while (*++argv);
7134 p[-1] = '\0';
7135 return pi->cmdtext;
7136}
7137
7138static void insert_bg_job(struct pipe *pi)
7139{
7140 struct pipe *job, **jobp;
7141 int i;
7142
7143 /* Linear search for the ID of the job to use */
7144 pi->jobid = 1;
7145 for (job = G.job_list; job; job = job->next)
7146 if (job->jobid >= pi->jobid)
7147 pi->jobid = job->jobid + 1;
7148
7149 /* Add job to the list of running jobs */
7150 jobp = &G.job_list;
7151 while ((job = *jobp) != NULL)
7152 jobp = &job->next;
7153 job = *jobp = xmalloc(sizeof(*job));
7154
7155 *job = *pi; /* physical copy */
7156 job->next = NULL;
7157 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
7158 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
7159 for (i = 0; i < pi->num_cmds; i++) {
7160 job->cmds[i].pid = pi->cmds[i].pid;
7161 /* all other fields are not used and stay zero */
7162 }
7163 job->cmdtext = xstrdup(get_cmdtext(pi));
7164
7165 if (G_interactive_fd)
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01007166 printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007167 G.last_jobid = job->jobid;
7168}
7169
7170static void remove_bg_job(struct pipe *pi)
7171{
7172 struct pipe *prev_pipe;
7173
7174 if (pi == G.job_list) {
7175 G.job_list = pi->next;
7176 } else {
7177 prev_pipe = G.job_list;
7178 while (prev_pipe->next != pi)
7179 prev_pipe = prev_pipe->next;
7180 prev_pipe->next = pi->next;
7181 }
7182 if (G.job_list)
7183 G.last_jobid = G.job_list->jobid;
7184 else
7185 G.last_jobid = 0;
7186}
7187
7188/* Remove a backgrounded job */
7189static void delete_finished_bg_job(struct pipe *pi)
7190{
7191 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007192 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007193}
7194#endif /* JOB */
7195
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007196static int job_exited_or_stopped(struct pipe *pi)
7197{
7198 int rcode, i;
7199
7200 if (pi->alive_cmds != pi->stopped_cmds)
7201 return -1;
7202
7203 /* All processes in fg pipe have exited or stopped */
7204 rcode = 0;
7205 i = pi->num_cmds;
7206 while (--i >= 0) {
7207 rcode = pi->cmds[i].cmd_exitcode;
7208 /* usually last process gives overall exitstatus,
7209 * but with "set -o pipefail", last *failed* process does */
7210 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
7211 break;
7212 }
7213 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7214 return rcode;
7215}
7216
Denys Vlasenko7e675362016-10-28 21:57:31 +02007217static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007218{
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007219#if ENABLE_HUSH_JOB
7220 struct pipe *pi;
7221#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007222 int i, dead;
7223
7224 dead = WIFEXITED(status) || WIFSIGNALED(status);
7225
7226#if DEBUG_JOBS
7227 if (WIFSTOPPED(status))
7228 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
7229 childpid, WSTOPSIG(status), WEXITSTATUS(status));
7230 if (WIFSIGNALED(status))
7231 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
7232 childpid, WTERMSIG(status), WEXITSTATUS(status));
7233 if (WIFEXITED(status))
7234 debug_printf_jobs("pid %d exited, exitcode %d\n",
7235 childpid, WEXITSTATUS(status));
7236#endif
7237 /* Were we asked to wait for a fg pipe? */
7238 if (fg_pipe) {
7239 i = fg_pipe->num_cmds;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007240
Denys Vlasenko7e675362016-10-28 21:57:31 +02007241 while (--i >= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007242 int rcode;
7243
Denys Vlasenko7e675362016-10-28 21:57:31 +02007244 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
7245 if (fg_pipe->cmds[i].pid != childpid)
7246 continue;
7247 if (dead) {
7248 int ex;
7249 fg_pipe->cmds[i].pid = 0;
7250 fg_pipe->alive_cmds--;
7251 ex = WEXITSTATUS(status);
7252 /* bash prints killer signal's name for *last*
7253 * process in pipe (prints just newline for SIGINT/SIGPIPE).
7254 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
7255 */
7256 if (WIFSIGNALED(status)) {
7257 int sig = WTERMSIG(status);
7258 if (i == fg_pipe->num_cmds-1)
7259 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
7260 puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
7261 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
7262 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
7263 * Maybe we need to use sig | 128? */
7264 ex = sig + 128;
7265 }
7266 fg_pipe->cmds[i].cmd_exitcode = ex;
7267 } else {
7268 fg_pipe->stopped_cmds++;
7269 }
7270 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
7271 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007272 rcode = job_exited_or_stopped(fg_pipe);
7273 if (rcode >= 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007274/* Note: *non-interactive* bash does not continue if all processes in fg pipe
7275 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
7276 * and "killall -STOP cat" */
7277 if (G_interactive_fd) {
7278#if ENABLE_HUSH_JOB
7279 if (fg_pipe->alive_cmds != 0)
7280 insert_bg_job(fg_pipe);
7281#endif
7282 return rcode;
7283 }
7284 if (fg_pipe->alive_cmds == 0)
7285 return rcode;
7286 }
7287 /* There are still running processes in the fg_pipe */
7288 return -1;
7289 }
7290 /* It wasnt in fg_pipe, look for process in bg pipes */
7291 }
7292
7293#if ENABLE_HUSH_JOB
7294 /* We were asked to wait for bg or orphaned children */
7295 /* No need to remember exitcode in this case */
7296 for (pi = G.job_list; pi; pi = pi->next) {
7297 for (i = 0; i < pi->num_cmds; i++) {
7298 if (pi->cmds[i].pid == childpid)
7299 goto found_pi_and_prognum;
7300 }
7301 }
7302 /* Happens when shell is used as init process (init=/bin/sh) */
7303 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
7304 return -1; /* this wasn't a process from fg_pipe */
7305
7306 found_pi_and_prognum:
7307 if (dead) {
7308 /* child exited */
7309 pi->cmds[i].pid = 0;
7310 pi->cmds[i].cmd_exitcode = WEXITSTATUS(status);
7311 if (WIFSIGNALED(status))
7312 pi->cmds[i].cmd_exitcode = 128 + WTERMSIG(status);
7313 pi->alive_cmds--;
7314 if (!pi->alive_cmds) {
7315 if (G_interactive_fd)
7316 printf(JOB_STATUS_FORMAT, pi->jobid,
7317 "Done", pi->cmdtext);
7318 delete_finished_bg_job(pi);
7319 }
7320 } else {
7321 /* child stopped */
7322 pi->stopped_cmds++;
7323 }
7324#endif
7325 return -1; /* this wasn't a process from fg_pipe */
7326}
7327
7328/* Check to see if any processes have exited -- if they have,
7329 * figure out why and see if a job has completed.
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007330 *
7331 * If non-NULL fg_pipe: wait for its completion or stop.
7332 * Return its exitcode or zero if stopped.
7333 *
7334 * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
7335 * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
7336 * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7337 * or 0 if no children changed status.
7338 *
7339 * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
7340 * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
7341 * or 0 if no children changed status.
Denys Vlasenko7e675362016-10-28 21:57:31 +02007342 */
7343static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
7344{
7345 int attributes;
7346 int status;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007347 int rcode = 0;
7348
7349 debug_printf_jobs("checkjobs %p\n", fg_pipe);
7350
7351 attributes = WUNTRACED;
7352 if (fg_pipe == NULL)
7353 attributes |= WNOHANG;
7354
7355 errno = 0;
7356#if ENABLE_HUSH_FAST
7357 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
7358//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
7359//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
7360 /* There was neither fork nor SIGCHLD since last waitpid */
7361 /* Avoid doing waitpid syscall if possible */
7362 if (!G.we_have_children) {
7363 errno = ECHILD;
7364 return -1;
7365 }
7366 if (fg_pipe == NULL) { /* is WNOHANG set? */
7367 /* We have children, but they did not exit
7368 * or stop yet (we saw no SIGCHLD) */
7369 return 0;
7370 }
7371 /* else: !WNOHANG, waitpid will block, can't short-circuit */
7372 }
7373#endif
7374
7375/* Do we do this right?
7376 * bash-3.00# sleep 20 | false
7377 * <ctrl-Z pressed>
7378 * [3]+ Stopped sleep 20 | false
7379 * bash-3.00# echo $?
7380 * 1 <========== bg pipe is not fully done, but exitcode is already known!
7381 * [hush 1.14.0: yes we do it right]
7382 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007383 while (1) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02007384 pid_t childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007385#if ENABLE_HUSH_FAST
Denys Vlasenko7e675362016-10-28 21:57:31 +02007386 int i;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007387 i = G.count_SIGCHLD;
7388#endif
7389 childpid = waitpid(-1, &status, attributes);
7390 if (childpid <= 0) {
7391 if (childpid && errno != ECHILD)
7392 bb_perror_msg("waitpid");
7393#if ENABLE_HUSH_FAST
7394 else { /* Until next SIGCHLD, waitpid's are useless */
7395 G.we_have_children = (childpid == 0);
7396 G.handled_SIGCHLD = i;
7397//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7398 }
7399#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02007400 /* ECHILD (no children), or 0 (no change in children status) */
7401 rcode = childpid;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007402 break;
7403 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007404 rcode = process_wait_result(fg_pipe, childpid, status);
7405 if (rcode >= 0) {
7406 /* fg_pipe exited or stopped */
7407 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007408 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007409 if (childpid == waitfor_pid) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007410 debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007411 rcode = WEXITSTATUS(status);
7412 if (WIFSIGNALED(status))
7413 rcode = 128 + WTERMSIG(status);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01007414 if (WIFSTOPPED(status))
7415 /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
7416 rcode = 128 + WSTOPSIG(status);
Denys Vlasenko7e675362016-10-28 21:57:31 +02007417 rcode++;
7418 break; /* "wait PID" called us, give it exitcode+1 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007419 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02007420 /* This wasn't one of our processes, or */
7421 /* fg_pipe still has running processes, do waitpid again */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007422 } /* while (waitpid succeeds)... */
7423
7424 return rcode;
7425}
7426
7427#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02007428static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007429{
7430 pid_t p;
Denys Vlasenko7e675362016-10-28 21:57:31 +02007431 int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007432 if (G_saved_tty_pgrp) {
7433 /* Job finished, move the shell to the foreground */
7434 p = getpgrp(); /* our process group id */
7435 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
7436 tcsetpgrp(G_interactive_fd, p);
7437 }
7438 return rcode;
7439}
7440#endif
7441
7442/* Start all the jobs, but don't wait for anything to finish.
7443 * See checkjobs().
7444 *
7445 * Return code is normally -1, when the caller has to wait for children
7446 * to finish to determine the exit status of the pipe. If the pipe
7447 * is a simple builtin command, however, the action is done by the
7448 * time run_pipe returns, and the exit code is provided as the
7449 * return value.
7450 *
7451 * Returns -1 only if started some children. IOW: we have to
7452 * mask out retvals of builtins etc with 0xff!
7453 *
7454 * The only case when we do not need to [v]fork is when the pipe
7455 * is single, non-backgrounded, non-subshell command. Examples:
7456 * cmd ; ... { list } ; ...
7457 * cmd && ... { list } && ...
7458 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007459 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007460 * or (if SH_STANDALONE) an applet, and we can run the { list }
7461 * with run_list. If it isn't one of these, we fork and exec cmd.
7462 *
7463 * Cases when we must fork:
7464 * non-single: cmd | cmd
7465 * backgrounded: cmd & { list } &
7466 * subshell: ( list ) [&]
7467 */
7468#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01007469#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007470 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
7471#endif
7472static int redirect_and_varexp_helper(char ***new_env_p,
7473 struct variable **old_vars_p,
7474 struct command *command,
7475 int squirrel[3],
7476 char **argv_expanded)
7477{
7478 /* setup_redirects acts on file descriptors, not FILEs.
7479 * This is perfect for work that comes after exec().
7480 * Is it really safe for inline use? Experimentally,
7481 * things seem to work. */
7482 int rcode = setup_redirects(command, squirrel);
7483 if (rcode == 0) {
7484 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
7485 *new_env_p = new_env;
7486 dump_cmd_in_x_mode(new_env);
7487 dump_cmd_in_x_mode(argv_expanded);
7488 if (old_vars_p)
7489 *old_vars_p = set_vars_and_save_old(new_env);
7490 }
7491 return rcode;
7492}
7493static NOINLINE int run_pipe(struct pipe *pi)
7494{
7495 static const char *const null_ptr = NULL;
7496
7497 int cmd_no;
7498 int next_infd;
7499 struct command *command;
7500 char **argv_expanded;
7501 char **argv;
7502 /* it is not always needed, but we aim to smaller code */
7503 int squirrel[] = { -1, -1, -1 };
7504 int rcode;
7505
7506 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
7507 debug_enter();
7508
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02007509 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
7510 * Result should be 3 lines: q w e, qwe, q w e
7511 */
7512 G.ifs = get_local_var_value("IFS");
7513 if (!G.ifs)
7514 G.ifs = defifs;
7515
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007516 IF_HUSH_JOB(pi->pgrp = -1;)
7517 pi->stopped_cmds = 0;
7518 command = &pi->cmds[0];
7519 argv_expanded = NULL;
7520
7521 if (pi->num_cmds != 1
7522 || pi->followup == PIPE_BG
7523 || command->cmd_type == CMD_SUBSHELL
7524 ) {
7525 goto must_fork;
7526 }
7527
7528 pi->alive_cmds = 1;
7529
7530 debug_printf_exec(": group:%p argv:'%s'\n",
7531 command->group, command->argv ? command->argv[0] : "NONE");
7532
7533 if (command->group) {
7534#if ENABLE_HUSH_FUNCTIONS
7535 if (command->cmd_type == CMD_FUNCDEF) {
7536 /* "executing" func () { list } */
7537 struct function *funcp;
7538
7539 funcp = new_function(command->argv[0]);
7540 /* funcp->name is already set to argv[0] */
7541 funcp->body = command->group;
7542# if !BB_MMU
7543 funcp->body_as_string = command->group_as_string;
7544 command->group_as_string = NULL;
7545# endif
7546 command->group = NULL;
7547 command->argv[0] = NULL;
7548 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
7549 funcp->parent_cmd = command;
7550 command->child_func = funcp;
7551
7552 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
7553 debug_leave();
7554 return EXIT_SUCCESS;
7555 }
7556#endif
7557 /* { list } */
7558 debug_printf("non-subshell group\n");
7559 rcode = 1; /* exitcode if redir failed */
7560 if (setup_redirects(command, squirrel) == 0) {
7561 debug_printf_exec(": run_list\n");
7562 rcode = run_list(command->group) & 0xff;
7563 }
7564 restore_redirects(squirrel);
7565 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7566 debug_leave();
7567 debug_printf_exec("run_pipe: return %d\n", rcode);
7568 return rcode;
7569 }
7570
7571 argv = command->argv ? command->argv : (char **) &null_ptr;
7572 {
7573 const struct built_in_command *x;
7574#if ENABLE_HUSH_FUNCTIONS
7575 const struct function *funcp;
7576#else
7577 enum { funcp = 0 };
7578#endif
7579 char **new_env = NULL;
7580 struct variable *old_vars = NULL;
7581
7582 if (argv[command->assignment_cnt] == NULL) {
7583 /* Assignments, but no command */
7584 /* Ensure redirects take effect (that is, create files).
7585 * Try "a=t >file" */
7586#if 0 /* A few cases in testsuite fail with this code. FIXME */
7587 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7588 /* Set shell variables */
7589 if (new_env) {
7590 argv = new_env;
7591 while (*argv) {
7592 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7593 /* Do we need to flag set_local_var() errors?
7594 * "assignment to readonly var" and "putenv error"
7595 */
7596 argv++;
7597 }
7598 }
7599 /* Redirect error sets $? to 1. Otherwise,
7600 * if evaluating assignment value set $?, retain it.
7601 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7602 if (rcode == 0)
7603 rcode = G.last_exitcode;
7604 /* Exit, _skipping_ variable restoring code: */
7605 goto clean_up_and_ret0;
7606
7607#else /* Older, bigger, but more correct code */
7608
7609 rcode = setup_redirects(command, squirrel);
7610 restore_redirects(squirrel);
7611 /* Set shell variables */
7612 if (G_x_mode)
7613 bb_putchar_stderr('+');
7614 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007615 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007616 if (G_x_mode)
7617 fprintf(stderr, " %s", p);
7618 debug_printf_exec("set shell var:'%s'->'%s'\n",
7619 *argv, p);
7620 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7621 /* Do we need to flag set_local_var() errors?
7622 * "assignment to readonly var" and "putenv error"
7623 */
7624 argv++;
7625 }
7626 if (G_x_mode)
7627 bb_putchar_stderr('\n');
7628 /* Redirect error sets $? to 1. Otherwise,
7629 * if evaluating assignment value set $?, retain it.
7630 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7631 if (rcode == 0)
7632 rcode = G.last_exitcode;
7633 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7634 debug_leave();
7635 debug_printf_exec("run_pipe: return %d\n", rcode);
7636 return rcode;
7637#endif
7638 }
7639
7640 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007641#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007642 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007643 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007644 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007645#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007646 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007647 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7648 }
7649
7650 /* if someone gives us an empty string: `cmd with empty output` */
7651 if (!argv_expanded[0]) {
7652 free(argv_expanded);
7653 debug_leave();
7654 return G.last_exitcode;
7655 }
7656
7657 x = find_builtin(argv_expanded[0]);
7658#if ENABLE_HUSH_FUNCTIONS
7659 funcp = NULL;
7660 if (!x)
7661 funcp = find_function(argv_expanded[0]);
7662#endif
7663 if (x || funcp) {
7664 if (!funcp) {
7665 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7666 debug_printf("exec with redirects only\n");
7667 rcode = setup_redirects(command, NULL);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007668 /* rcode=1 can be if redir file can't be opened */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007669 goto clean_up_and_ret1;
7670 }
7671 }
7672 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7673 if (rcode == 0) {
7674 if (!funcp) {
7675 debug_printf_exec(": builtin '%s' '%s'...\n",
7676 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007677 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007678 rcode = x->b_function(argv_expanded) & 0xff;
7679 fflush_all();
7680 }
7681#if ENABLE_HUSH_FUNCTIONS
7682 else {
7683# if ENABLE_HUSH_LOCAL
7684 struct variable **sv;
7685 sv = G.shadowed_vars_pp;
7686 G.shadowed_vars_pp = &old_vars;
7687# endif
7688 debug_printf_exec(": function '%s' '%s'...\n",
7689 funcp->name, argv_expanded[1]);
7690 rcode = run_function(funcp, argv_expanded) & 0xff;
7691# if ENABLE_HUSH_LOCAL
7692 G.shadowed_vars_pp = sv;
7693# endif
7694 }
7695#endif
7696 }
7697 clean_up_and_ret:
7698 unset_vars(new_env);
7699 add_vars(old_vars);
7700/* clean_up_and_ret0: */
7701 restore_redirects(squirrel);
7702 clean_up_and_ret1:
7703 free(argv_expanded);
7704 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7705 debug_leave();
7706 debug_printf_exec("run_pipe return %d\n", rcode);
7707 return rcode;
7708 }
7709
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007710 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007711 int n = find_applet_by_name(argv_expanded[0]);
7712 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7713 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7714 if (rcode == 0) {
7715 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7716 argv_expanded[0], argv_expanded[1]);
7717 rcode = run_nofork_applet(n, argv_expanded);
7718 }
7719 goto clean_up_and_ret;
7720 }
7721 }
7722 /* It is neither builtin nor applet. We must fork. */
7723 }
7724
7725 must_fork:
7726 /* NB: argv_expanded may already be created, and that
7727 * might include `cmd` runs! Do not rerun it! We *must*
7728 * use argv_expanded if it's non-NULL */
7729
7730 /* Going to fork a child per each pipe member */
7731 pi->alive_cmds = 0;
7732 next_infd = 0;
7733
7734 cmd_no = 0;
7735 while (cmd_no < pi->num_cmds) {
7736 struct fd_pair pipefds;
7737#if !BB_MMU
7738 volatile nommu_save_t nommu_save;
7739 nommu_save.new_env = NULL;
7740 nommu_save.old_vars = NULL;
7741 nommu_save.argv = NULL;
7742 nommu_save.argv_from_re_execing = NULL;
7743#endif
7744 command = &pi->cmds[cmd_no];
7745 cmd_no++;
7746 if (command->argv) {
7747 debug_printf_exec(": pipe member '%s' '%s'...\n",
7748 command->argv[0], command->argv[1]);
7749 } else {
7750 debug_printf_exec(": pipe member with no argv\n");
7751 }
7752
7753 /* pipes are inserted between pairs of commands */
7754 pipefds.rd = 0;
7755 pipefds.wr = 1;
7756 if (cmd_no < pi->num_cmds)
7757 xpiped_pair(pipefds);
7758
7759 command->pid = BB_MMU ? fork() : vfork();
7760 if (!command->pid) { /* child */
7761#if ENABLE_HUSH_JOB
7762 disable_restore_tty_pgrp_on_exit();
7763 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7764
7765 /* Every child adds itself to new process group
7766 * with pgid == pid_of_first_child_in_pipe */
7767 if (G.run_list_level == 1 && G_interactive_fd) {
7768 pid_t pgrp;
7769 pgrp = pi->pgrp;
7770 if (pgrp < 0) /* true for 1st process only */
7771 pgrp = getpid();
7772 if (setpgid(0, pgrp) == 0
7773 && pi->followup != PIPE_BG
7774 && G_saved_tty_pgrp /* we have ctty */
7775 ) {
7776 /* We do it in *every* child, not just first,
7777 * to avoid races */
7778 tcsetpgrp(G_interactive_fd, pgrp);
7779 }
7780 }
7781#endif
7782 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7783 /* 1st cmd in backgrounded pipe
7784 * should have its stdin /dev/null'ed */
7785 close(0);
7786 if (open(bb_dev_null, O_RDONLY))
7787 xopen("/", O_RDONLY);
7788 } else {
7789 xmove_fd(next_infd, 0);
7790 }
7791 xmove_fd(pipefds.wr, 1);
7792 if (pipefds.rd > 1)
7793 close(pipefds.rd);
7794 /* Like bash, explicit redirects override pipes,
Denys Vlasenko869994c2016-08-20 15:16:00 +02007795 * and the pipe fd (fd#1) is available for dup'ing:
7796 * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
7797 * of cmd1 goes into pipe.
7798 */
7799 if (setup_redirects(command, NULL)) {
7800 /* Happens when redir file can't be opened:
7801 * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
7802 * FOO
7803 * hush: can't open '/qwe/rty': No such file or directory
7804 * BAZ
7805 * (echo BAR is not executed, it hits _exit(1) below)
7806 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007807 _exit(1);
Denys Vlasenko869994c2016-08-20 15:16:00 +02007808 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007809
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007810 /* Stores to nommu_save list of env vars putenv'ed
7811 * (NOMMU, on MMU we don't need that) */
7812 /* cast away volatility... */
7813 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7814 /* pseudo_exec() does not return */
7815 }
7816
7817 /* parent or error */
7818#if ENABLE_HUSH_FAST
7819 G.count_SIGCHLD++;
7820//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7821#endif
7822 enable_restore_tty_pgrp_on_exit();
7823#if !BB_MMU
7824 /* Clean up after vforked child */
7825 free(nommu_save.argv);
7826 free(nommu_save.argv_from_re_execing);
7827 unset_vars(nommu_save.new_env);
7828 add_vars(nommu_save.old_vars);
7829#endif
7830 free(argv_expanded);
7831 argv_expanded = NULL;
7832 if (command->pid < 0) { /* [v]fork failed */
7833 /* Clearly indicate, was it fork or vfork */
7834 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7835 } else {
7836 pi->alive_cmds++;
7837#if ENABLE_HUSH_JOB
7838 /* Second and next children need to know pid of first one */
7839 if (pi->pgrp < 0)
7840 pi->pgrp = command->pid;
7841#endif
7842 }
7843
7844 if (cmd_no > 1)
7845 close(next_infd);
7846 if (cmd_no < pi->num_cmds)
7847 close(pipefds.wr);
7848 /* Pass read (output) pipe end to next iteration */
7849 next_infd = pipefds.rd;
7850 }
7851
7852 if (!pi->alive_cmds) {
7853 debug_leave();
7854 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7855 return 1;
7856 }
7857
7858 debug_leave();
7859 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7860 return -1;
7861}
7862
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007863/* NB: called by pseudo_exec, and therefore must not modify any
7864 * global data until exec/_exit (we can be a child after vfork!) */
7865static int run_list(struct pipe *pi)
7866{
7867#if ENABLE_HUSH_CASE
7868 char *case_word = NULL;
7869#endif
7870#if ENABLE_HUSH_LOOPS
7871 struct pipe *loop_top = NULL;
7872 char **for_lcur = NULL;
7873 char **for_list = NULL;
7874#endif
7875 smallint last_followup;
7876 smalluint rcode;
7877#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7878 smalluint cond_code = 0;
7879#else
7880 enum { cond_code = 0 };
7881#endif
7882#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007883 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007884 smallint last_rword; /* ditto */
7885#endif
7886
7887 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7888 debug_enter();
7889
7890#if ENABLE_HUSH_LOOPS
7891 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007892 {
7893 struct pipe *cpipe;
7894 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7895 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7896 continue;
7897 /* current word is FOR or IN (BOLD in comments below) */
7898 if (cpipe->next == NULL) {
7899 syntax_error("malformed for");
7900 debug_leave();
7901 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7902 return 1;
7903 }
7904 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7905 if (cpipe->next->res_word == RES_DO)
7906 continue;
7907 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7908 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7909 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7910 ) {
7911 syntax_error("malformed for");
7912 debug_leave();
7913 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7914 return 1;
7915 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007916 }
7917 }
7918#endif
7919
7920 /* Past this point, all code paths should jump to ret: label
7921 * in order to return, no direct "return" statements please.
7922 * This helps to ensure that no memory is leaked. */
7923
7924#if ENABLE_HUSH_JOB
7925 G.run_list_level++;
7926#endif
7927
7928#if HAS_KEYWORDS
7929 rword = RES_NONE;
7930 last_rword = RES_XXXX;
7931#endif
7932 last_followup = PIPE_SEQ;
7933 rcode = G.last_exitcode;
7934
7935 /* Go through list of pipes, (maybe) executing them. */
7936 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01007937 int r;
7938
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007939 if (G.flag_SIGINT)
7940 break;
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02007941 if (G_flag_return_in_progress == 1)
7942 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007943
7944 IF_HAS_KEYWORDS(rword = pi->res_word;)
7945 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7946 rword, cond_code, last_rword);
7947#if ENABLE_HUSH_LOOPS
7948 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7949 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7950 ) {
7951 /* start of a loop: remember where loop starts */
7952 loop_top = pi;
7953 G.depth_of_loop++;
7954 }
7955#endif
7956 /* Still in the same "if...", "then..." or "do..." branch? */
7957 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7958 if ((rcode == 0 && last_followup == PIPE_OR)
7959 || (rcode != 0 && last_followup == PIPE_AND)
7960 ) {
7961 /* It is "<true> || CMD" or "<false> && CMD"
7962 * and we should not execute CMD */
7963 debug_printf_exec("skipped cmd because of || or &&\n");
7964 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02007965 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007966 }
7967 }
7968 last_followup = pi->followup;
7969 IF_HAS_KEYWORDS(last_rword = rword;)
7970#if ENABLE_HUSH_IF
7971 if (cond_code) {
7972 if (rword == RES_THEN) {
7973 /* if false; then ... fi has exitcode 0! */
7974 G.last_exitcode = rcode = EXIT_SUCCESS;
7975 /* "if <false> THEN cmd": skip cmd */
7976 continue;
7977 }
7978 } else {
7979 if (rword == RES_ELSE || rword == RES_ELIF) {
7980 /* "if <true> then ... ELSE/ELIF cmd":
7981 * skip cmd and all following ones */
7982 break;
7983 }
7984 }
7985#endif
7986#if ENABLE_HUSH_LOOPS
7987 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7988 if (!for_lcur) {
7989 /* first loop through for */
7990
7991 static const char encoded_dollar_at[] ALIGN1 = {
7992 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7993 }; /* encoded representation of "$@" */
7994 static const char *const encoded_dollar_at_argv[] = {
7995 encoded_dollar_at, NULL
7996 }; /* argv list with one element: "$@" */
7997 char **vals;
7998
7999 vals = (char**)encoded_dollar_at_argv;
8000 if (pi->next->res_word == RES_IN) {
8001 /* if no variable values after "in" we skip "for" */
8002 if (!pi->next->cmds[0].argv) {
8003 G.last_exitcode = rcode = EXIT_SUCCESS;
8004 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
8005 break;
8006 }
8007 vals = pi->next->cmds[0].argv;
8008 } /* else: "for var; do..." -> assume "$@" list */
8009 /* create list of variable values */
8010 debug_print_strings("for_list made from", vals);
8011 for_list = expand_strvec_to_strvec(vals);
8012 for_lcur = for_list;
8013 debug_print_strings("for_list", for_list);
8014 }
8015 if (!*for_lcur) {
8016 /* "for" loop is over, clean up */
8017 free(for_list);
8018 for_list = NULL;
8019 for_lcur = NULL;
8020 break;
8021 }
8022 /* Insert next value from for_lcur */
8023 /* note: *for_lcur already has quotes removed, $var expanded, etc */
8024 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
8025 continue;
8026 }
8027 if (rword == RES_IN) {
8028 continue; /* "for v IN list;..." - "in" has no cmds anyway */
8029 }
8030 if (rword == RES_DONE) {
8031 continue; /* "done" has no cmds too */
8032 }
8033#endif
8034#if ENABLE_HUSH_CASE
8035 if (rword == RES_CASE) {
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008036 debug_printf_exec("CASE cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008037 case_word = expand_strvec_to_string(pi->cmds->argv);
8038 continue;
8039 }
8040 if (rword == RES_MATCH) {
8041 char **argv;
8042
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008043 debug_printf_exec("MATCH cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008044 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
8045 break;
8046 /* all prev words didn't match, does this one match? */
8047 argv = pi->cmds->argv;
8048 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02008049 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008050 /* TODO: which FNM_xxx flags to use? */
8051 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
8052 free(pattern);
8053 if (cond_code == 0) { /* match! we will execute this branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008054 free(case_word);
8055 case_word = NULL; /* make future "word)" stop */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008056 break;
8057 }
8058 argv++;
8059 }
8060 continue;
8061 }
8062 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008063 debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008064 if (cond_code != 0)
8065 continue; /* not matched yet, skip this pipe */
8066 }
Denys Vlasenkoaeaee432016-11-04 20:14:04 +01008067 if (rword == RES_ESAC) {
8068 debug_printf_exec("ESAC cond_code:%d\n", cond_code);
8069 if (case_word) {
8070 /* "case" did not match anything: still set $? (to 0) */
8071 G.last_exitcode = rcode = EXIT_SUCCESS;
8072 }
8073 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008074#endif
8075 /* Just pressing <enter> in shell should check for jobs.
8076 * OTOH, in non-interactive shell this is useless
8077 * and only leads to extra job checks */
8078 if (pi->num_cmds == 0) {
8079 if (G_interactive_fd)
8080 goto check_jobs_and_continue;
8081 continue;
8082 }
8083
8084 /* After analyzing all keywords and conditions, we decided
8085 * to execute this pipe. NB: have to do checkjobs(NULL)
8086 * after run_pipe to collect any background children,
8087 * even if list execution is to be stopped. */
8088 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008089#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008090 G.flag_break_continue = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008091#endif
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008092 rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
8093 if (r != -1) {
8094 /* We ran a builtin, function, or group.
8095 * rcode is already known
8096 * and we don't need to wait for anything. */
8097 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
8098 G.last_exitcode = rcode;
8099 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008100#if ENABLE_HUSH_LOOPS
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008101 /* Was it "break" or "continue"? */
8102 if (G.flag_break_continue) {
8103 smallint fbc = G.flag_break_continue;
8104 /* We might fall into outer *loop*,
8105 * don't want to break it too */
8106 if (loop_top) {
8107 G.depth_break_continue--;
8108 if (G.depth_break_continue == 0)
8109 G.flag_break_continue = 0;
8110 /* else: e.g. "continue 2" should *break* once, *then* continue */
8111 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
8112 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02008113 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008114 break;
8115 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008116 /* "continue": simulate end of loop */
8117 rword = RES_DONE;
8118 continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008119 }
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008120#endif
8121 if (G_flag_return_in_progress == 1) {
8122 checkjobs(NULL, 0 /*(no pid to wait for)*/);
8123 break;
8124 }
8125 } else if (pi->followup == PIPE_BG) {
8126 /* What does bash do with attempts to background builtins? */
8127 /* even bash 3.2 doesn't do that well with nested bg:
8128 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
8129 * I'm NOT treating inner &'s as jobs */
8130#if ENABLE_HUSH_JOB
8131 if (G.run_list_level == 1)
8132 insert_bg_job(pi);
8133#endif
8134 /* Last command's pid goes to $! */
8135 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
8136 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
8137/* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash says 0 */
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008138 rcode = EXIT_SUCCESS;
8139 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008140 } else {
8141#if ENABLE_HUSH_JOB
8142 if (G.run_list_level == 1 && G_interactive_fd) {
8143 /* Waits for completion, then fg's main shell */
8144 rcode = checkjobs_and_fg_shell(pi);
8145 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008146 goto check_traps;
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008147 }
Denys Vlasenko6c635d62016-11-08 20:26:11 +01008148#endif
8149 /* This one just waits for completion */
8150 rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
8151 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
8152 check_traps:
Denys Vlasenko5cc9bf62016-11-08 17:34:44 +01008153 G.last_exitcode = rcode;
8154 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008155 }
8156
8157 /* Analyze how result affects subsequent commands */
8158#if ENABLE_HUSH_IF
8159 if (rword == RES_IF || rword == RES_ELIF)
8160 cond_code = rcode;
8161#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02008162 check_jobs_and_continue:
Denys Vlasenko7e675362016-10-28 21:57:31 +02008163 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denys Vlasenko3beab832013-04-07 18:16:58 +02008164 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008165#if ENABLE_HUSH_LOOPS
8166 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008167 if (pi->next
8168 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02008169 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02008170 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008171 if (rword == RES_WHILE) {
8172 if (rcode) {
8173 /* "while false; do...done" - exitcode 0 */
8174 G.last_exitcode = rcode = EXIT_SUCCESS;
8175 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02008176 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008177 }
8178 }
8179 if (rword == RES_UNTIL) {
8180 if (!rcode) {
8181 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008182 break;
8183 }
8184 }
8185 }
8186#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008187 } /* for (pi) */
8188
8189#if ENABLE_HUSH_JOB
8190 G.run_list_level--;
8191#endif
8192#if ENABLE_HUSH_LOOPS
8193 if (loop_top)
8194 G.depth_of_loop--;
8195 free(for_list);
8196#endif
8197#if ENABLE_HUSH_CASE
8198 free(case_word);
8199#endif
8200 debug_leave();
8201 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
8202 return rcode;
8203}
8204
8205/* Select which version we will use */
8206static int run_and_free_list(struct pipe *pi)
8207{
8208 int rcode = 0;
8209 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08008210 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02008211 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
8212 rcode = run_list(pi);
8213 }
8214 /* free_pipe_list has the side effect of clearing memory.
8215 * In the long run that function can be merged with run_list,
8216 * but doing that now would hobble the debugging effort. */
8217 free_pipe_list(pi);
8218 debug_printf_exec("run_and_free_list return %d\n", rcode);
8219 return rcode;
8220}
8221
8222
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008223static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00008224{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008225 sighandler_t old_handler;
8226 unsigned sig = 0;
8227 while ((mask >>= 1) != 0) {
8228 sig++;
8229 if (!(mask & 1))
8230 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02008231 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008232 /* POSIX allows shell to re-enable SIGCHLD
8233 * even if it was SIG_IGN on entry.
8234 * Therefore we skip IGN check for it:
8235 */
8236 if (sig == SIGCHLD)
8237 continue;
8238 if (old_handler == SIG_IGN) {
8239 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008240 install_sighandler(sig, old_handler);
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008241#if ENABLE_HUSH_TRAP
8242 if (!G_traps)
8243 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
8244 free(G_traps[sig]);
8245 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
8246#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008247 }
8248 }
8249}
8250
8251/* Called a few times only (or even once if "sh -c") */
8252static void install_special_sighandlers(void)
8253{
Denis Vlasenkof9375282009-04-05 19:13:39 +00008254 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008255
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008256 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008257 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008258 if (G_interactive_fd) {
8259 mask |= SPECIAL_INTERACTIVE_SIGS;
8260 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008261 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008262 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008263 /* Careful, do not re-install handlers we already installed */
8264 if (G.special_sig_mask != mask) {
8265 unsigned diff = mask & ~G.special_sig_mask;
8266 G.special_sig_mask = mask;
8267 install_sighandlers(diff);
8268 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008269}
8270
8271#if ENABLE_HUSH_JOB
8272/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008273/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008274static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00008275{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008276 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008277
8278 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008279 mask = 0
Denys Vlasenko830ea352016-11-08 04:59:11 +01008280 /*+ (1 << SIGILL ) * HUSH_DEBUG*/
8281 /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008282 + (1 << SIGBUS ) * HUSH_DEBUG
8283 + (1 << SIGSEGV) * HUSH_DEBUG
Denys Vlasenko830ea352016-11-08 04:59:11 +01008284 /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008285 + (1 << SIGABRT)
8286 /* bash 3.2 seems to handle these just like 'fatal' ones */
8287 + (1 << SIGPIPE)
8288 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008289 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008290 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008291 * we never want to restore pgrp on exit, and this fn is not called
8292 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008293 /*+ (1 << SIGHUP )*/
8294 /*+ (1 << SIGTERM)*/
8295 /*+ (1 << SIGINT )*/
8296 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008297 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02008298
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008299 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008300}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00008301#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00008302
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008303static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00008304{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008305 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008306 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008307 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08008308 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008309 break;
8310 case 'x':
8311 IF_HUSH_MODE_X(G_x_mode = state;)
8312 break;
8313 case 'o':
8314 if (!o_opt) {
8315 /* "set -+o" without parameter.
8316 * in bash, set -o produces this output:
8317 * pipefail off
8318 * and set +o:
8319 * set +o pipefail
8320 * We always use the second form.
8321 */
8322 const char *p = o_opt_strings;
8323 idx = 0;
8324 while (*p) {
8325 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
8326 idx++;
8327 p += strlen(p) + 1;
8328 }
8329 break;
8330 }
8331 idx = index_in_strings(o_opt_strings, o_opt);
8332 if (idx >= 0) {
8333 G.o_opt[idx] = state;
8334 break;
8335 }
8336 default:
8337 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008338 }
8339 return EXIT_SUCCESS;
8340}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008341
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00008342int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00008343int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00008344{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008345 enum {
8346 OPT_login = (1 << 0),
8347 };
8348 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00008349 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008350 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008351 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008352 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008353 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00008354
Denis Vlasenko574f2f42008-02-27 18:41:59 +00008355 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02008356 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008357 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008358
Denys Vlasenko10c01312011-05-11 11:49:21 +02008359#if ENABLE_HUSH_FAST
8360 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
8361#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008362#if !BB_MMU
8363 G.argv0_for_re_execing = argv[0];
8364#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008365 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008366 shell_ver = xzalloc(sizeof(*shell_ver));
8367 shell_ver->flg_export = 1;
8368 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02008369 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02008370 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008371 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02008372 /* Create shell local variables from the values
8373 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00008374 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008375 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008376 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008377 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00008378 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008379 if (e) while (*e) {
8380 char *value = strchr(*e, '=');
8381 if (value) { /* paranoia */
8382 cur_var->next = xzalloc(sizeof(*cur_var));
8383 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00008384 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008385 cur_var->max_len = strlen(*e);
8386 cur_var->flg_export = 1;
8387 }
8388 e++;
8389 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02008390 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01008391 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
8392 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02008393
8394 /* Export PWD */
8395 set_pwd_var(/*exp:*/ 1);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008396
8397#if ENABLE_HUSH_BASH_COMPAT
8398 /* Set (but not export) HOSTNAME unless already set */
8399 if (!get_local_var_value("HOSTNAME")) {
8400 struct utsname uts;
8401 uname(&uts);
8402 set_local_var_from_halves("HOSTNAME", uts.nodename);
8403 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008404 /* bash also exports SHLVL and _,
8405 * and sets (but doesn't export) the following variables:
8406 * BASH=/bin/bash
8407 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
8408 * BASH_VERSION='3.2.0(1)-release'
8409 * HOSTTYPE=i386
8410 * MACHTYPE=i386-pc-linux-gnu
8411 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02008412 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02008413 * EUID=<NNNNN>
8414 * UID=<NNNNN>
8415 * GROUPS=()
8416 * LINES=<NNN>
8417 * COLUMNS=<NNN>
8418 * BASH_ARGC=()
8419 * BASH_ARGV=()
8420 * BASH_LINENO=()
8421 * BASH_SOURCE=()
8422 * DIRSTACK=()
8423 * PIPESTATUS=([0]="0")
8424 * HISTFILE=/<xxx>/.bash_history
8425 * HISTFILESIZE=500
8426 * HISTSIZE=500
8427 * MAILCHECK=60
8428 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
8429 * SHELL=/bin/bash
8430 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
8431 * TERM=dumb
8432 * OPTERR=1
8433 * OPTIND=1
8434 * IFS=$' \t\n'
8435 * PS1='\s-\v\$ '
8436 * PS2='> '
8437 * PS4='+ '
8438 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02008439#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02008440
Denis Vlasenko38f63192007-01-22 09:03:07 +00008441#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02008442 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008443#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02008444
Eric Andersen94ac2442001-05-22 19:05:18 +00008445 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00008446 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00008447
Denys Vlasenkoe9abe752016-08-19 20:15:26 +02008448 die_func = restore_ttypgrp_and__exit;
Denis Vlasenkoed782372009-04-10 00:45:02 +00008449
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008450 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008451 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008452 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008453 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008454 * in order to intercept (more) signals.
8455 */
8456
8457 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008458 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008459 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008460 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008461 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008462 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008463#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00008464 "<:$:R:V:"
8465# if ENABLE_HUSH_FUNCTIONS
8466 "F:"
8467# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008468#endif
8469 );
8470 if (opt <= 0)
8471 break;
Eric Andersen25f27032001-04-26 23:22:31 +00008472 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008473 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008474 /* Possibilities:
8475 * sh ... -c 'script'
8476 * sh ... -c 'script' ARG0 [ARG1...]
8477 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01008478 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008479 * "" needs to be replaced with NULL
8480 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01008481 * Note: the form without ARG0 never happens:
8482 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008483 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02008484 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008485 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008486 G.root_ppid = getppid();
8487 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008488 G.global_argv = argv + optind;
8489 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008490 if (builtin_argc) {
8491 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
8492 const struct built_in_command *x;
8493
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008494 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008495 x = find_builtin(optarg);
8496 if (x) { /* paranoia */
8497 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
8498 G.global_argv += builtin_argc;
8499 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01008500 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01008501 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008502 }
8503 goto final_return;
8504 }
8505 if (!G.global_argv[0]) {
8506 /* -c 'script' (no params): prevent empty $0 */
8507 G.global_argv--; /* points to argv[i] of 'script' */
8508 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02008509 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008510 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008511 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008512 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008513 goto final_return;
8514 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00008515 /* Well, we cannot just declare interactiveness,
8516 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008517 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008518 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00008519 case 's':
8520 /* "-s" means "read from stdin", but this is how we always
8521 * operate, so simply do nothing here. */
8522 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008523 case 'l':
8524 flags |= OPT_login;
8525 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008526#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008527 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02008528 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00008529 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008530 case '$': {
8531 unsigned long long empty_trap_mask;
8532
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008533 G.root_pid = bb_strtou(optarg, &optarg, 16);
8534 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02008535 G.root_ppid = bb_strtou(optarg, &optarg, 16);
8536 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008537 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
8538 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008539 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008540 optarg++;
8541 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008542 optarg++;
8543 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
8544 if (empty_trap_mask != 0) {
8545 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008546 install_special_sighandlers();
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008547 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008548 for (sig = 1; sig < NSIG; sig++) {
8549 if (empty_trap_mask & (1LL << sig)) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01008550 G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02008551 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008552 }
8553 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008554 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008555# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008556 optarg++;
8557 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008558# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00008559 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008560 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008561 case 'R':
8562 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02008563 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008564 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00008565# if ENABLE_HUSH_FUNCTIONS
8566 case 'F': {
8567 struct function *funcp = new_function(optarg);
8568 /* funcp->name is already set to optarg */
8569 /* funcp->body is set to NULL. It's a special case. */
8570 funcp->body_as_string = argv[optind];
8571 optind++;
8572 break;
8573 }
8574# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00008575#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008576 case 'n':
8577 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008578 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008579 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008580 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008581#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008582 fprintf(stderr, "Usage: sh [FILE]...\n"
8583 " or: sh -c command [args]...\n\n");
8584 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008585#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00008586 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00008587#endif
Eric Andersen25f27032001-04-26 23:22:31 +00008588 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008589 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008590
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008591 /* Skip options. Try "hush -l": $1 should not be "-l"! */
8592 G.global_argc = argc - (optind - 1);
8593 G.global_argv = argv + (optind - 1);
8594 G.global_argv[0] = argv[0];
8595
Denys Vlasenkodea47882009-10-09 15:40:49 +02008596 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008597 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02008598 G.root_ppid = getppid();
8599 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008600
8601 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008602 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008603 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008604 debug_printf("sourcing /etc/profile\n");
8605 input = fopen_for_read("/etc/profile");
8606 if (input != NULL) {
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008607 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008608 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008609 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008610 fclose_and_forget(input);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008611 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008612 /* bash: after sourcing /etc/profile,
8613 * tries to source (in the given order):
8614 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008615 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008616 * bash also sources ~/.bash_logout on exit.
8617 * If called as sh, skips .bash_XXX files.
8618 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008619 }
8620
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008621 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008622 FILE *input;
8623 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008624 * "bash <script>" (which is never interactive (unless -i?))
8625 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008626 * If called as sh, does the same but with $ENV.
Denys Vlasenko2eb0a7e2016-10-27 11:28:59 +02008627 * Also NB, per POSIX, $ENV should undergo parameter expansion.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008628 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008629 G.global_argc--;
8630 G.global_argv++;
8631 debug_printf("running script '%s'\n", G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02008632 xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008633 input = xfopen_for_read(G.global_argv[0]);
Denys Vlasenkob7adf7a2016-10-25 17:00:13 +02008634 xfunc_error_retval = 1;
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008635 remember_FILE(input);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008636 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008637 parse_and_run_file(input);
8638#if ENABLE_FEATURE_CLEAN_UP
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02008639 fclose_and_forget(input);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008640#endif
8641 goto final_return;
8642 }
8643
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008644 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008645 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008646 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008647
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008648 /* A shell is interactive if the '-i' flag was given,
8649 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008650 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008651 * no arguments remaining or the -s flag given
8652 * standard input is a terminal
8653 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008654 * Refer to Posix.2, the description of the 'sh' utility.
8655 */
8656#if ENABLE_HUSH_JOB
8657 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008658 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8659 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8660 if (G_saved_tty_pgrp < 0)
8661 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008662
8663 /* try to dup stdin to high fd#, >= 255 */
8664 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8665 if (G_interactive_fd < 0) {
8666 /* try to dup to any fd */
8667 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008668 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008669 /* give up */
8670 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008671 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008672 }
8673 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008674// TODO: track & disallow any attempts of user
8675// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008676 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008677 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008678 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008679 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008680
Mike Frysinger38478a62009-05-20 04:48:06 -04008681 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008682 /* If we were run as 'hush &', sleep until we are
8683 * in the foreground (tty pgrp == our pgrp).
8684 * If we get started under a job aware app (like bash),
8685 * make sure we are now in charge so we don't fight over
8686 * who gets the foreground */
8687 while (1) {
8688 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008689 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8690 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008691 break;
8692 /* send TTIN to ourself (should stop us) */
8693 kill(- shell_pgrp, SIGTTIN);
8694 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008695 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008696
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008697 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008698 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008699
Mike Frysinger38478a62009-05-20 04:48:06 -04008700 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008701 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008702 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008703 /* Put ourselves in our own process group
8704 * (bash, too, does this only if ctty is available) */
8705 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8706 /* Grab control of the terminal */
8707 tcsetpgrp(G_interactive_fd, getpid());
8708 }
Denys Vlasenko550bf5b2015-10-09 16:42:57 +02008709 enable_restore_tty_pgrp_on_exit();
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008710
8711# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8712 {
8713 const char *hp = get_local_var_value("HISTFILE");
8714 if (!hp) {
8715 hp = get_local_var_value("HOME");
8716 if (hp)
8717 hp = concat_path_file(hp, ".hush_history");
8718 } else {
8719 hp = xstrdup(hp);
8720 }
8721 if (hp) {
8722 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008723 //set_local_var(xasprintf("HISTFILE=%s", ...));
8724 }
8725# if ENABLE_FEATURE_SH_HISTFILESIZE
8726 hp = get_local_var_value("HISTFILESIZE");
8727 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8728# endif
8729 }
8730# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008731 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008732 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008733 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008734#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008735 /* No job control compiled in, only prompt/line editing */
8736 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008737 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8738 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008739 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008740 G_interactive_fd = dup(STDIN_FILENO);
8741 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008742 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008743 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008744 }
8745 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008746 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008747 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008748 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008749 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008750#else
8751 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008752 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008753#endif
8754 /* bash:
8755 * if interactive but not a login shell, sources ~/.bashrc
8756 * (--norc turns this off, --rcfile <file> overrides)
8757 */
8758
8759 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008760 /* note: ash and hush share this string */
8761 printf("\n\n%s %s\n"
8762 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8763 "\n",
8764 bb_banner,
8765 "hush - the humble shell"
8766 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008767 }
8768
Denis Vlasenkof9375282009-04-05 19:13:39 +00008769 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008770
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008771 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008772 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008773}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008774
8775
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008776#if ENABLE_MSH
8777int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8778int msh_main(int argc, char **argv)
8779{
Denys Vlasenkoed6ff5e2016-09-30 12:28:37 +02008780 bb_error_msg("msh is deprecated, please use hush instead");
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008781 return hush_main(argc, argv);
8782}
8783#endif
8784
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008785
8786/*
8787 * Built-ins
8788 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008789static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008790{
8791 return 0;
8792}
8793
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008794static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008795{
8796 int argc = 0;
8797 while (*argv) {
8798 argc++;
8799 argv++;
8800 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008801 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008802}
8803
8804static int FAST_FUNC builtin_test(char **argv)
8805{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008806 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008807}
8808
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008809static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008810{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008811 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008812}
8813
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01008814#if ENABLE_HUSH_PRINTF
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008815static int FAST_FUNC builtin_printf(char **argv)
8816{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008817 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008818}
8819#endif
8820
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008821static char **skip_dash_dash(char **argv)
8822{
8823 argv++;
8824 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8825 argv++;
8826 return argv;
8827}
8828
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008829static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008830{
8831 int rcode = EXIT_SUCCESS;
8832
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008833 argv = skip_dash_dash(argv);
8834 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008835 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008836 /* bash:
8837 * eval "echo Hi; done" ("done" is syntax error):
8838 * "echo Hi" will not execute too.
8839 */
8840 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008841 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008842 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008843 }
8844 return rcode;
8845}
8846
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008847static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008848{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008849 const char *newdir;
8850
8851 argv = skip_dash_dash(argv);
8852 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008853 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008854 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008855 * bash says "bash: cd: HOME not set" and does nothing
8856 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008857 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008858 const char *home = get_local_var_value("HOME");
8859 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008860 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008861 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008862 /* Mimic bash message exactly */
8863 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008864 return EXIT_FAILURE;
8865 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008866 /* Read current dir (get_cwd(1) is inside) and set PWD.
8867 * Note: do not enforce exporting. If PWD was unset or unexported,
8868 * set it again, but do not export. bash does the same.
8869 */
8870 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008871 return EXIT_SUCCESS;
8872}
8873
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008874static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008875{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008876 argv = skip_dash_dash(argv);
8877 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008878 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008879
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008880 /* Careful: we can end up here after [v]fork. Do not restore
8881 * tty pgrp then, only top-level shell process does that */
8882 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8883 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8884
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008885 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008886 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008887 * and tcsetpgrp, and this is inherently racy.
8888 */
8889 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008890}
8891
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008892static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008893{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008894 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008895
8896 /* interactive bash:
8897 * # trap "echo EEE" EXIT
8898 * # exit
8899 * exit
8900 * There are stopped jobs.
8901 * (if there are _stopped_ jobs, running ones don't count)
8902 * # exit
8903 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01008904 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00008905 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008906 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008907 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008908
8909 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008910 argv = skip_dash_dash(argv);
8911 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008912 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008913 /* mimic bash: exit 123abc == exit 255 + error msg */
8914 xfunc_error_retval = 255;
8915 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008916 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008917}
8918
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008919static void print_escaped(const char *s)
8920{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008921 if (*s == '\'')
8922 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008923 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008924 const char *p = strchrnul(s, '\'');
8925 /* print 'xxxx', possibly just '' */
8926 printf("'%.*s'", (int)(p - s), s);
8927 if (*p == '\0')
8928 break;
8929 s = p;
8930 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008931 /* s points to '; print "'''...'''" */
8932 putchar('"');
8933 do putchar('\''); while (*++s == '\'');
8934 putchar('"');
8935 } while (*s);
8936}
8937
Denys Vlasenko295fef82009-06-03 12:47:26 +02008938#if !ENABLE_HUSH_LOCAL
8939#define helper_export_local(argv, exp, lvl) \
8940 helper_export_local(argv, exp)
8941#endif
8942static void helper_export_local(char **argv, int exp, int lvl)
8943{
8944 do {
8945 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008946 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008947
8948 /* So far we do not check that name is valid (TODO?) */
8949
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008950 if (*name_end == '\0') {
8951 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008952
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008953 vpp = get_ptr_to_local_var(name, name_end - name);
8954 var = vpp ? *vpp : NULL;
8955
Denys Vlasenko295fef82009-06-03 12:47:26 +02008956 if (exp == -1) { /* unexporting? */
8957 /* export -n NAME (without =VALUE) */
8958 if (var) {
8959 var->flg_export = 0;
8960 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8961 unsetenv(name);
8962 } /* else: export -n NOT_EXISTING_VAR: no-op */
8963 continue;
8964 }
8965 if (exp == 1) { /* exporting? */
8966 /* export NAME (without =VALUE) */
8967 if (var) {
8968 var->flg_export = 1;
8969 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8970 putenv(var->varstr);
8971 continue;
8972 }
8973 }
Denys Vlasenko61508d92016-10-02 21:12:02 +02008974#if ENABLE_HUSH_LOCAL
8975 if (exp == 0 /* local? */
8976 && var && var->func_nest_level == lvl
8977 ) {
8978 /* "local x=abc; ...; local x" - ignore second local decl */
Denys Vlasenko80729a42016-10-02 22:33:15 +02008979 continue;
Denys Vlasenko61508d92016-10-02 21:12:02 +02008980 }
8981#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02008982 /* Exporting non-existing variable.
8983 * bash does not put it in environment,
8984 * but remembers that it is exported,
8985 * and does put it in env when it is set later.
8986 * We just set it to "" and export. */
8987 /* Or, it's "local NAME" (without =VALUE).
8988 * bash sets the value to "". */
8989 name = xasprintf("%s=", name);
8990 } else {
8991 /* (Un)exporting/making local NAME=VALUE */
8992 name = xstrdup(name);
8993 }
8994 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8995 } while (*++argv);
8996}
8997
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008998static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008999{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00009000 unsigned opt_unexport;
9001
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02009002#if ENABLE_HUSH_EXPORT_N
9003 /* "!": do not abort on errors */
9004 opt_unexport = getopt32(argv, "!n");
9005 if (opt_unexport == (uint32_t)-1)
9006 return EXIT_FAILURE;
9007 argv += optind;
9008#else
9009 opt_unexport = 0;
9010 argv++;
9011#endif
9012
9013 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009014 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009015 if (e) {
9016 while (*e) {
9017#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009018 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009019#else
9020 /* ash emits: export VAR='VAL'
9021 * bash: declare -x VAR="VAL"
9022 * we follow ash example */
9023 const char *s = *e++;
9024 const char *p = strchr(s, '=');
9025
9026 if (!p) /* wtf? take next variable */
9027 continue;
9028 /* export var= */
9029 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009030 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009031 putchar('\n');
9032#endif
9033 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009034 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00009035 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009036 return EXIT_SUCCESS;
9037 }
9038
Denys Vlasenko295fef82009-06-03 12:47:26 +02009039 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009040
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009041 return EXIT_SUCCESS;
9042}
9043
Denys Vlasenko295fef82009-06-03 12:47:26 +02009044#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009045static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02009046{
9047 if (G.func_nest_level == 0) {
9048 bb_error_msg("%s: not in a function", argv[0]);
9049 return EXIT_FAILURE; /* bash compat */
9050 }
9051 helper_export_local(argv, 0, G.func_nest_level);
9052 return EXIT_SUCCESS;
9053}
9054#endif
9055
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009056#if ENABLE_HUSH_UNSET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009057/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
9058static int FAST_FUNC builtin_unset(char **argv)
9059{
9060 int ret;
9061 unsigned opts;
9062
9063 /* "!": do not abort on errors */
9064 /* "+": stop at 1st non-option */
9065 opts = getopt32(argv, "!+vf");
9066 if (opts == (unsigned)-1)
9067 return EXIT_FAILURE;
9068 if (opts == 3) {
9069 bb_error_msg("unset: -v and -f are exclusive");
9070 return EXIT_FAILURE;
9071 }
9072 argv += optind;
9073
9074 ret = EXIT_SUCCESS;
9075 while (*argv) {
9076 if (!(opts & 2)) { /* not -f */
9077 if (unset_local_var(*argv)) {
9078 /* unset <nonexistent_var> doesn't fail.
9079 * Error is when one tries to unset RO var.
9080 * Message was printed by unset_local_var. */
9081 ret = EXIT_FAILURE;
9082 }
9083 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009084# if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko61508d92016-10-02 21:12:02 +02009085 else {
9086 unset_func(*argv);
9087 }
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009088# endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009089 argv++;
9090 }
9091 return ret;
9092}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009093#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009094
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009095#if ENABLE_HUSH_SET
Denys Vlasenko61508d92016-10-02 21:12:02 +02009096/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
9097 * built-in 'set' handler
9098 * SUSv3 says:
9099 * set [-abCefhmnuvx] [-o option] [argument...]
9100 * set [+abCefhmnuvx] [+o option] [argument...]
9101 * set -- [argument...]
9102 * set -o
9103 * set +o
9104 * Implementations shall support the options in both their hyphen and
9105 * plus-sign forms. These options can also be specified as options to sh.
9106 * Examples:
9107 * Write out all variables and their values: set
9108 * Set $1, $2, and $3 and set "$#" to 3: set c a b
9109 * Turn on the -x and -v options: set -xv
9110 * Unset all positional parameters: set --
9111 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
9112 * Set the positional parameters to the expansion of x, even if x expands
9113 * with a leading '-' or '+': set -- $x
9114 *
9115 * So far, we only support "set -- [argument...]" and some of the short names.
9116 */
9117static int FAST_FUNC builtin_set(char **argv)
9118{
9119 int n;
9120 char **pp, **g_argv;
9121 char *arg = *++argv;
9122
9123 if (arg == NULL) {
9124 struct variable *e;
9125 for (e = G.top_var; e; e = e->next)
9126 puts(e->varstr);
9127 return EXIT_SUCCESS;
9128 }
9129
9130 do {
9131 if (strcmp(arg, "--") == 0) {
9132 ++argv;
9133 goto set_argv;
9134 }
9135 if (arg[0] != '+' && arg[0] != '-')
9136 break;
9137 for (n = 1; arg[n]; ++n) {
9138 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
9139 goto error;
9140 if (arg[n] == 'o' && argv[1])
9141 argv++;
9142 }
9143 } while ((arg = *++argv) != NULL);
9144 /* Now argv[0] is 1st argument */
9145
9146 if (arg == NULL)
9147 return EXIT_SUCCESS;
9148 set_argv:
9149
9150 /* NB: G.global_argv[0] ($0) is never freed/changed */
9151 g_argv = G.global_argv;
9152 if (G.global_args_malloced) {
9153 pp = g_argv;
9154 while (*++pp)
9155 free(*pp);
9156 g_argv[1] = NULL;
9157 } else {
9158 G.global_args_malloced = 1;
9159 pp = xzalloc(sizeof(pp[0]) * 2);
9160 pp[0] = g_argv[0]; /* retain $0 */
9161 g_argv = pp;
9162 }
9163 /* This realloc's G.global_argv */
9164 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
9165
9166 n = 1;
9167 while (*++pp)
9168 n++;
9169 G.global_argc = n;
9170
9171 return EXIT_SUCCESS;
9172
9173 /* Nothing known, so abort */
9174 error:
9175 bb_error_msg("set: %s: invalid option", arg);
9176 return EXIT_FAILURE;
9177}
Denys Vlasenko10d5ece2017-01-08 18:28:43 +01009178#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009179
9180static int FAST_FUNC builtin_shift(char **argv)
9181{
9182 int n = 1;
9183 argv = skip_dash_dash(argv);
9184 if (argv[0]) {
9185 n = atoi(argv[0]);
9186 }
9187 if (n >= 0 && n < G.global_argc) {
9188 if (G.global_args_malloced) {
9189 int m = 1;
9190 while (m <= n)
9191 free(G.global_argv[m++]);
9192 }
9193 G.global_argc -= n;
9194 memmove(&G.global_argv[1], &G.global_argv[n+1],
9195 G.global_argc * sizeof(G.global_argv[0]));
9196 return EXIT_SUCCESS;
9197 }
9198 return EXIT_FAILURE;
9199}
9200
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009201#if ENABLE_HUSH_READ
Denys Vlasenko61508d92016-10-02 21:12:02 +02009202/* Interruptibility of read builtin in bash
9203 * (tested on bash-4.2.8 by sending signals (not by ^C)):
9204 *
9205 * Empty trap makes read ignore corresponding signal, for any signal.
9206 *
9207 * SIGINT:
9208 * - terminates non-interactive shell;
9209 * - interrupts read in interactive shell;
9210 * if it has non-empty trap:
9211 * - executes trap and returns to command prompt in interactive shell;
9212 * - executes trap and returns to read in non-interactive shell;
9213 * SIGTERM:
9214 * - is ignored (does not interrupt) read in interactive shell;
9215 * - terminates non-interactive shell;
9216 * if it has non-empty trap:
9217 * - executes trap and returns to read;
9218 * SIGHUP:
9219 * - terminates shell (regardless of interactivity);
9220 * if it has non-empty trap:
9221 * - executes trap and returns to read;
9222 */
9223static int FAST_FUNC builtin_read(char **argv)
9224{
9225 const char *r;
9226 char *opt_n = NULL;
9227 char *opt_p = NULL;
9228 char *opt_t = NULL;
9229 char *opt_u = NULL;
9230 const char *ifs;
9231 int read_flags;
9232
9233 /* "!": do not abort on errors.
9234 * Option string must start with "sr" to match BUILTIN_READ_xxx
9235 */
9236 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
9237 if (read_flags == (uint32_t)-1)
9238 return EXIT_FAILURE;
9239 argv += optind;
9240 ifs = get_local_var_value("IFS"); /* can be NULL */
9241
9242 again:
9243 r = shell_builtin_read(set_local_var_from_halves,
9244 argv,
9245 ifs,
9246 read_flags,
9247 opt_n,
9248 opt_p,
9249 opt_t,
9250 opt_u
9251 );
9252
9253 if ((uintptr_t)r == 1 && errno == EINTR) {
9254 unsigned sig = check_and_run_traps();
9255 if (sig && sig != SIGINT)
9256 goto again;
9257 }
9258
9259 if ((uintptr_t)r > 1) {
9260 bb_error_msg("%s", r);
9261 r = (char*)(uintptr_t)1;
9262 }
9263
9264 return (uintptr_t)r;
9265}
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009266#endif
Denys Vlasenko61508d92016-10-02 21:12:02 +02009267
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009268#if ENABLE_HUSH_TRAP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009269static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009270{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009271 int sig;
9272 char *new_cmd;
9273
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009274 if (!G_traps)
9275 G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009276
9277 argv++;
9278 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00009279 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009280 /* No args: print all trapped */
9281 for (i = 0; i < NSIG; ++i) {
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009282 if (G_traps[i]) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009283 printf("trap -- ");
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009284 print_escaped(G_traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02009285 /* note: bash adds "SIG", but only if invoked
9286 * as "bash". If called as "sh", or if set -o posix,
9287 * then it prints short signal names.
9288 * We are printing short names: */
9289 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009290 }
9291 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009292 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009293 return EXIT_SUCCESS;
9294 }
9295
9296 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009297 /* If first arg is a number: reset all specified signals */
9298 sig = bb_strtou(*argv, NULL, 10);
9299 if (errno == 0) {
9300 int ret;
9301 process_sig_list:
9302 ret = EXIT_SUCCESS;
9303 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009304 sighandler_t handler;
9305
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009306 sig = get_signum(*argv++);
9307 if (sig < 0 || sig >= NSIG) {
9308 ret = EXIT_FAILURE;
9309 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00009310 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009311 continue;
9312 }
9313
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009314 free(G_traps[sig]);
9315 G_traps[sig] = xstrdup(new_cmd);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009316
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01009317 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009318 get_signame(sig), sig, G_traps[sig]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009319
9320 /* There is no signal for 0 (EXIT) */
9321 if (sig == 0)
9322 continue;
9323
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009324 if (new_cmd)
9325 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
9326 else
9327 /* We are removing trap handler */
9328 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02009329 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009330 }
9331 return ret;
9332 }
9333
9334 if (!argv[1]) { /* no second arg */
9335 bb_error_msg("trap: invalid arguments");
9336 return EXIT_FAILURE;
9337 }
9338
9339 /* First arg is "-": reset all specified to default */
9340 /* First arg is "--": skip it, the rest is "handler SIGs..." */
9341 /* Everything else: set arg as signal handler
9342 * (includes "" case, which ignores signal) */
9343 if (argv[0][0] == '-') {
9344 if (argv[0][1] == '\0') { /* "-" */
9345 /* new_cmd remains NULL: "reset these sigs" */
9346 goto reset_traps;
9347 }
9348 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
9349 argv++;
9350 }
9351 /* else: "-something", no special meaning */
9352 }
9353 new_cmd = *argv;
9354 reset_traps:
9355 argv++;
9356 goto process_sig_list;
9357}
Denys Vlasenko7a85c602017-01-08 17:40:18 +01009358#endif
Denis Vlasenko38e626d2009-04-18 12:58:19 +00009359
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009360#if ENABLE_HUSH_TYPE
Mike Frysinger93cadc22009-05-27 17:06:25 -04009361/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009362static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04009363{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009364 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04009365
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009366 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04009367 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02009368 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04009369
9370 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009371 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009372 type = "an alias";*/
9373#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009374 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009375 type = "a function";
9376#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009377 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04009378 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009379 else if ((path = find_in_path(*argv)) != NULL)
9380 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009381 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02009382 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04009383 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009384 continue;
9385 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04009386
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02009387 printf("%s is %s\n", *argv, type);
9388 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04009389 }
9390
9391 return ret;
9392}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009393#endif
Mike Frysinger93cadc22009-05-27 17:06:25 -04009394
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009395#if ENABLE_HUSH_JOB
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009396static struct pipe *parse_jobspec(const char *str)
9397{
9398 struct pipe *pi;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01009399 unsigned jobnum;
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009400
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01009401 if (sscanf(str, "%%%u", &jobnum) != 1) {
9402 if (str[0] != '%'
9403 || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
9404 ) {
9405 bb_error_msg("bad argument '%s'", str);
9406 return NULL;
9407 }
9408 /* It is "%%", "%+" or "%" - current job */
9409 jobnum = G.last_jobid;
9410 if (jobnum == 0) {
9411 bb_error_msg("no current job");
9412 return NULL;
9413 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009414 }
9415 for (pi = G.job_list; pi; pi = pi->next) {
9416 if (pi->jobid == jobnum) {
9417 return pi;
9418 }
9419 }
9420 bb_error_msg("%d: no such job", jobnum);
9421 return NULL;
9422}
9423
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009424/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009425static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009426{
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009427 int i;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009428 struct pipe *pi;
9429
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009430 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009431 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00009432
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009433 /* If they gave us no args, assume they want the last backgrounded task */
9434 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00009435 for (pi = G.job_list; pi; pi = pi->next) {
9436 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009437 goto found;
9438 }
9439 }
9440 bb_error_msg("%s: no current job", argv[0]);
9441 return EXIT_FAILURE;
9442 }
Denys Vlasenko4e1c8b42016-11-07 20:06:40 +01009443
9444 pi = parse_jobspec(argv[1]);
9445 if (!pi)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009446 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009447 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00009448 /* TODO: bash prints a string representation
9449 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04009450 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009451 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00009452 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009453 }
9454
9455 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009456 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
9457 for (i = 0; i < pi->num_cmds; i++) {
9458 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009459 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009460 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009461
9462 i = kill(- pi->pgrp, SIGCONT);
9463 if (i < 0) {
9464 if (errno == ESRCH) {
9465 delete_finished_bg_job(pi);
9466 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009467 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009468 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009469 }
9470
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009471 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009472 remove_bg_job(pi);
9473 return checkjobs_and_fg_shell(pi);
9474 }
9475 return EXIT_SUCCESS;
9476}
9477#endif
9478
9479#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009480static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009481{
9482 const struct built_in_command *x;
9483
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009484 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00009485 "Built-in commands:\n"
9486 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009487 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01009488 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009489 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009490 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009491 return EXIT_SUCCESS;
9492}
9493#endif
9494
Denys Vlasenkoff463a82013-05-12 02:45:23 +02009495#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02009496static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
9497{
9498 show_history(G.line_input_state);
9499 return EXIT_SUCCESS;
9500}
9501#endif
9502
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009503#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009504static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009505{
9506 struct pipe *job;
9507 const char *status_string;
9508
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009509 checkjobs(NULL, 0 /*(no pid to wait for)*/);
Denis Vlasenko87a86552008-07-29 19:43:10 +00009510 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00009511 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009512 status_string = "Stopped";
9513 else
9514 status_string = "Running";
9515
9516 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
9517 }
9518 return EXIT_SUCCESS;
9519}
9520#endif
9521
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009522#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009523static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009524{
9525 void *p;
9526 unsigned long l;
9527
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009528# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02009529 /* Optional. Reduces probability of false positives */
9530 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02009531# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009532 /* Crude attempt to find where "free memory" starts,
9533 * sans fragmentation. */
9534 p = malloc(240);
9535 l = (unsigned long)p;
9536 free(p);
9537 p = malloc(3400);
9538 if (l < (unsigned long)p) l = (unsigned long)p;
9539 free(p);
9540
Denys Vlasenko7f0ebbc2016-10-03 17:42:53 +02009541
9542# if 0 /* debug */
9543 {
9544 struct mallinfo mi = mallinfo();
9545 printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
9546 mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
9547 }
9548# endif
9549
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009550 if (!G.memleak_value)
9551 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02009552
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00009553 l -= G.memleak_value;
9554 if ((long)l < 0)
9555 l = 0;
9556 l /= 1024;
9557 if (l > 127)
9558 l = 127;
9559
9560 /* Exitcode is "how many kilobytes we leaked since 1st call" */
9561 return l;
9562}
9563#endif
9564
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009565static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009566{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02009567 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009568 return EXIT_SUCCESS;
9569}
9570
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009571static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009572{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009573 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009574 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009575 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009576#if ENABLE_HUSH_FUNCTIONS
9577 smallint sv_flg;
9578#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009579
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009580 argv = skip_dash_dash(argv);
9581 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009582 if (!filename) {
9583 /* bash says: "bash: .: filename argument required" */
9584 return 2; /* bash compat */
9585 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009586 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009587 if (!strchr(filename, '/')) {
9588 arg_path = find_in_path(filename);
9589 if (arg_path)
9590 filename = arg_path;
9591 }
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009592 input = remember_FILE(fopen_or_warn(filename, "r"));
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02009593 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009594 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009595 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009596 /* POSIX: non-interactive shell should abort here,
9597 * not merely fail. So far no one complained :)
9598 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009599 return EXIT_FAILURE;
9600 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009601
Mike Frysinger885b6f22009-04-18 21:04:25 +00009602#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009603 sv_flg = G_flag_return_in_progress;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009604 /* "we are inside sourced file, ok to use return" */
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009605 G_flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009606#endif
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009607 if (argv[1])
9608 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009609
Denys Vlasenko992e0ff2016-09-29 01:27:09 +02009610 /* "false; . ./empty_line; echo Zero:$?" should print 0 */
9611 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00009612 parse_and_run_file(input);
Denys Vlasenko7b25b1c2016-08-20 15:58:34 +02009613 fclose_and_forget(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00009614
Denys Vlasenko88b532d2013-03-17 14:11:04 +01009615 if (argv[1])
9616 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00009617#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009618 G_flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00009619#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009620
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00009621 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009622}
9623
Denys Vlasenkod5933b12017-01-08 18:31:39 +01009624#if ENABLE_HUSH_UMASK
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009625static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009626{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009627 int rc;
9628 mode_t mask;
9629
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009630 rc = 1;
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009631 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009632 argv = skip_dash_dash(argv);
9633 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009634 mode_t old_mask = mask;
9635
Denys Vlasenko6283f982015-10-07 16:56:20 +02009636 /* numeric umasks are taken as-is */
9637 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
9638 if (!isdigit(argv[0][0]))
9639 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009640 mask = bb_parse_mode(argv[0], mask);
Denys Vlasenko6283f982015-10-07 16:56:20 +02009641 if (!isdigit(argv[0][0]))
9642 mask ^= 0777;
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009643 if ((unsigned)mask > 0777) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009644 mask = old_mask;
9645 /* bash messages:
9646 * bash: umask: 'q': invalid symbolic mode operator
9647 * bash: umask: 999: octal number out of range
9648 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02009649 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denys Vlasenko5711a2a2015-10-07 17:55:33 +02009650 rc = 0;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009651 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009652 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009653 /* Mimic bash */
9654 printf("%04o\n", (unsigned) mask);
9655 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009656 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00009657 umask(mask);
9658
9659 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009660}
Denys Vlasenkod5933b12017-01-08 18:31:39 +01009661#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009662
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009663#if ENABLE_HUSH_KILL
9664static int FAST_FUNC builtin_kill(char **argv)
9665{
9666 int ret = 0;
9667
9668 argv = skip_dash_dash(argv);
9669 if (argv[0] && strcmp(argv[0], "-l") != 0) {
9670 int i = 0;
9671
9672 do {
9673 struct pipe *pi;
9674 char *dst;
9675 int j, n;
9676
9677 if (argv[i][0] != '%')
9678 continue;
9679 /*
9680 * "kill %N" - job kill
9681 * Converting to pgrp / pid kill
9682 */
9683 pi = parse_jobspec(argv[i]);
9684 if (!pi) {
9685 /* Eat bad jobspec */
9686 j = i;
9687 do {
9688 j++;
9689 argv[j - 1] = argv[j];
9690 } while (argv[j]);
9691 ret = 1;
9692 i--;
9693 continue;
9694 }
9695 /*
9696 * In jobs started under job control, we signal
9697 * entire process group by kill -PGRP_ID.
9698 * This happens, f.e., in interactive shell.
9699 *
9700 * Otherwise, we signal each child via
9701 * kill PID1 PID2 PID3.
9702 * Testcases:
9703 * sh -c 'sleep 1|sleep 1 & kill %1'
9704 * sh -c 'true|sleep 2 & sleep 1; kill %1'
9705 * sh -c 'true|sleep 1 & sleep 2; kill %1'
9706 */
9707 n = pi->num_cmds;
9708 if (ENABLE_HUSH_JOB && G_interactive_fd)
9709 n = 1;
9710 dst = alloca(n * sizeof(int)*4);
9711 argv[i] = dst;
9712#if ENABLE_HUSH_JOB
9713 if (G_interactive_fd)
9714 dst += sprintf(dst, " -%u", (int)pi->pgrp);
9715 else
9716#endif
9717 for (j = 0; j < n; j++) {
9718 struct command *cmd = &pi->cmds[j];
9719 /* Skip exited members of the job */
9720 if (cmd->pid == 0)
9721 continue;
9722 /*
9723 * kill_main has matching code to expect
9724 * leading space. Needed to not confuse
9725 * negative pids with "kill -SIGNAL_NO" syntax
9726 */
9727 dst += sprintf(dst, " %u", (int)cmd->pid);
9728 }
9729 *dst = '\0';
9730 } while (argv[++i]);
9731 }
9732
9733 if (argv[0] || ret == 0) {
9734 argv--;
9735 argv[0] = (char*)"kill"; /* why? think about "kill -- PID" */
9736 /* kill_main also handles "killall" etc, so it does look at argv[0]! */
9737 ret = run_applet_main(argv, kill_main);
9738 }
9739 return ret;
9740}
9741#endif
9742
9743#if ENABLE_HUSH_WAIT
Mike Frysinger56bdea12009-03-28 20:01:58 +00009744/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009745#if !ENABLE_HUSH_JOB
9746# define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
9747#endif
9748static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
Denys Vlasenko7e675362016-10-28 21:57:31 +02009749{
9750 int ret = 0;
9751 for (;;) {
9752 int sig;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009753 sigset_t oldset;
Denys Vlasenko7e675362016-10-28 21:57:31 +02009754
Denys Vlasenko830ea352016-11-08 04:59:11 +01009755 if (!sigisemptyset(&G.pending_set))
9756 goto check_sig;
9757
Denys Vlasenko7e675362016-10-28 21:57:31 +02009758 /* waitpid is not interruptible by SA_RESTARTed
9759 * signals which we use. Thus, this ugly dance:
9760 */
9761
9762 /* Make sure possible SIGCHLD is stored in kernel's
9763 * pending signal mask before we call waitpid.
9764 * Or else we may race with SIGCHLD, lose it,
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009765 * and get stuck in sigsuspend...
Denys Vlasenko7e675362016-10-28 21:57:31 +02009766 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009767 sigfillset(&oldset); /* block all signals, remember old set */
9768 sigprocmask(SIG_SETMASK, &oldset, &oldset);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009769
9770 if (!sigisemptyset(&G.pending_set)) {
9771 /* Crap! we raced with some signal! */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009772 goto restore;
9773 }
9774
9775 /*errno = 0; - checkjobs does this */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009776/* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009777 ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009778 debug_printf_exec("checkjobs:%d\n", ret);
9779#if ENABLE_HUSH_JOB
9780 if (waitfor_pipe) {
9781 int rcode = job_exited_or_stopped(waitfor_pipe);
9782 debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
9783 if (rcode >= 0) {
9784 ret = rcode;
9785 sigprocmask(SIG_SETMASK, &oldset, NULL);
9786 break;
9787 }
9788 }
9789#endif
Denys Vlasenko7e675362016-10-28 21:57:31 +02009790 /* if ECHILD, there are no children (ret is -1 or 0) */
9791 /* if ret == 0, no children changed state */
9792 /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009793 if (errno == ECHILD || ret) {
9794 ret--;
9795 if (ret < 0) /* if ECHILD, may need to fix "ret" */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009796 ret = 0;
9797 sigprocmask(SIG_SETMASK, &oldset, NULL);
9798 break;
9799 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009800 /* Wait for SIGCHLD or any other signal */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009801 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9802 /* Note: sigsuspend invokes signal handler */
9803 sigsuspend(&oldset);
9804 restore:
9805 sigprocmask(SIG_SETMASK, &oldset, NULL);
Denys Vlasenko830ea352016-11-08 04:59:11 +01009806 check_sig:
Denys Vlasenko7e675362016-10-28 21:57:31 +02009807 /* So, did we get a signal? */
Denys Vlasenko7e675362016-10-28 21:57:31 +02009808 sig = check_and_run_traps();
9809 if (sig /*&& sig != SIGCHLD - always true */) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009810 ret = 128 + sig;
9811 break;
9812 }
9813 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9814 }
9815 return ret;
9816}
9817
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009818static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00009819{
Denys Vlasenko7e675362016-10-28 21:57:31 +02009820 int ret;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009821 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009822
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009823 argv = skip_dash_dash(argv);
9824 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009825 /* Don't care about wait results */
9826 /* Note 1: must wait until there are no more children */
9827 /* Note 2: must be interruptible */
9828 /* Examples:
9829 * $ sleep 3 & sleep 6 & wait
9830 * [1] 30934 sleep 3
9831 * [2] 30935 sleep 6
9832 * [1] Done sleep 3
9833 * [2] Done sleep 6
9834 * $ sleep 3 & sleep 6 & wait
9835 * [1] 30936 sleep 3
9836 * [2] 30937 sleep 6
9837 * [1] Done sleep 3
9838 * ^C <-- after ~4 sec from keyboard
9839 * $
9840 */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009841 return wait_for_child_or_signal(NULL, 0 /*(no job and no pid to wait for)*/);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009842 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009843
Denys Vlasenko7e675362016-10-28 21:57:31 +02009844 do {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009845 pid_t pid = bb_strtou(*argv, NULL, 10);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009846 if (errno || pid <= 0) {
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009847#if ENABLE_HUSH_JOB
9848 if (argv[0][0] == '%') {
Denys Vlasenko02affb42016-11-08 00:59:29 +01009849 struct pipe *wait_pipe;
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01009850 ret = 127; /* bash compat for bad jobspecs */
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009851 wait_pipe = parse_jobspec(*argv);
9852 if (wait_pipe) {
Denys Vlasenko02affb42016-11-08 00:59:29 +01009853 ret = job_exited_or_stopped(wait_pipe);
9854 if (ret < 0)
9855 ret = wait_for_child_or_signal(wait_pipe, 0);
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009856 }
Denys Vlasenkod5b5c2f2017-01-08 15:46:04 +01009857 /* else: parse_jobspec() already emitted error msg */
9858 continue;
Denys Vlasenko62b717b2016-11-07 22:12:18 +01009859 }
9860#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00009861 /* mimic bash message */
9862 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009863 ret = EXIT_FAILURE;
9864 continue; /* bash checks all argv[] */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009865 }
Denys Vlasenko02affb42016-11-08 00:59:29 +01009866
Denys Vlasenko7e675362016-10-28 21:57:31 +02009867 /* Do we have such child? */
9868 ret = waitpid(pid, &status, WNOHANG);
9869 if (ret < 0) {
9870 /* No */
9871 if (errno == ECHILD) {
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009872 if (G.last_bg_pid > 0 && pid == G.last_bg_pid) {
9873 /* "wait $!" but last bg task has already exited. Try:
9874 * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
9875 * In bash it prints exitcode 0, then 3.
Denys Vlasenko26ad94b2016-11-07 23:07:21 +01009876 * In dash, it is 127.
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009877 */
Denys Vlasenko26ad94b2016-11-07 23:07:21 +01009878 /* ret = G.last_bg_pid_exitstatus - FIXME */
9879 } else {
9880 /* Example: "wait 1". mimic bash message */
9881 bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009882 }
Denys Vlasenko7e675362016-10-28 21:57:31 +02009883 } else {
9884 /* ??? */
9885 bb_perror_msg("wait %s", *argv);
9886 }
9887 ret = 127;
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009888 continue; /* bash checks all argv[] */
9889 }
9890 if (ret == 0) {
Denys Vlasenko7e675362016-10-28 21:57:31 +02009891 /* Yes, and it still runs */
Denys Vlasenko02affb42016-11-08 00:59:29 +01009892 ret = wait_for_child_or_signal(NULL, pid);
Denys Vlasenko7e675362016-10-28 21:57:31 +02009893 } else {
9894 /* Yes, and it just exited */
Denys Vlasenko02affb42016-11-08 00:59:29 +01009895 process_wait_result(NULL, pid, status);
Denys Vlasenko85378cd2015-10-11 21:47:11 +02009896 ret = WEXITSTATUS(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009897 if (WIFSIGNALED(status))
9898 ret = 128 + WTERMSIG(status);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009899 }
Denys Vlasenko9db74e42016-10-28 22:39:12 +02009900 } while (*++argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009901
9902 return ret;
9903}
Denys Vlasenko1125d7d2017-01-08 17:19:38 +01009904#endif
Mike Frysinger56bdea12009-03-28 20:01:58 +00009905
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009906#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9907static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9908{
9909 if (argv[1]) {
9910 def = bb_strtou(argv[1], NULL, 10);
9911 if (errno || def < def_min || argv[2]) {
9912 bb_error_msg("%s: bad arguments", argv[0]);
9913 def = UINT_MAX;
9914 }
9915 }
9916 return def;
9917}
9918#endif
9919
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009920#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009921static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009922{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009923 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009924 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009925 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denys Vlasenko49117b42016-07-21 14:40:08 +02009926 /* if we came from builtin_continue(), need to undo "= 1" */
9927 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009928 return EXIT_SUCCESS; /* bash compat */
9929 }
Denys Vlasenko49117b42016-07-21 14:40:08 +02009930 G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009931
9932 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9933 if (depth == UINT_MAX)
9934 G.flag_break_continue = BC_BREAK;
9935 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009936 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009937
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009938 return EXIT_SUCCESS;
9939}
9940
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009941static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009942{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009943 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9944 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009945}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009946#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009947
9948#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009949static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009950{
9951 int rc;
9952
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009953 if (G_flag_return_in_progress != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009954 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9955 return EXIT_FAILURE; /* bash compat */
9956 }
9957
Denys Vlasenko04b46bc2016-10-01 22:28:03 +02009958 G_flag_return_in_progress = 1;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009959
9960 /* bash:
9961 * out of range: wraps around at 256, does not error out
9962 * non-numeric param:
9963 * f() { false; return qwe; }; f; echo $?
9964 * bash: return: qwe: numeric argument required <== we do this
9965 * 255 <== we also do this
9966 */
9967 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9968 return rc;
9969}
9970#endif