blob: e1d0ece29f7b9732a57f60a61c7bcad1aae99f0b [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +00008 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
Denys Vlasenkobbecd742010-10-03 17:22:52 +020011 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 *
Eric Andersen25f27032001-04-26 23:22:31 +000013 * Credits:
14 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000015 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000019 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
24 *
Eric Andersen25f27032001-04-26 23:22:31 +000025 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000026 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000027 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000028 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000030 *
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
41 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020042 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
45 * tilde expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000046 * aliases
Denys Vlasenko349ef962010-05-21 15:46:24 +020047 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020050 * make complex ${var%...} constructs support optional
51 * make here documents optional
Mike Frysinger25a6ca02009-03-28 13:59:26 +000052 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020053 * Bash compat TODO:
54 * redirection of stdout+stderr: &> and >&
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020055 * reserved words: function select
56 * advanced test: [[ ]]
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020057 * process substitution: <(list) and >(list)
58 * =~: regex operator
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020059 * let EXPR [EXPR...]
Denys Vlasenko349ef962010-05-21 15:46:24 +020060 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020063 * ((EXPR))
Denys Vlasenko349ef962010-05-21 15:46:24 +020064 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020066 * $[EXPR]: synonym for $((EXPR))
Denys Vlasenkobbecd742010-10-03 17:22:52 +020067 *
68 * Won't do:
69 * In bash, export builtin is special, its arguments are assignments
Denys Vlasenko08218012009-06-03 14:43:56 +020070 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
72 * compare with:
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020076 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020077 * Note2: bash 3.2.33(1) does this only if export word itself
78 * is not quoted:
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
80 * aaa bbb
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
82 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000083 */
Denys Vlasenko8da415e2010-12-05 01:30:14 +010084#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85 || defined(__APPLE__) \
86 )
87# include <malloc.h> /* for malloc_trim */
88#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +000089#include <glob.h>
90/* #include <dmalloc.h> */
91#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000092# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000093#endif
Denys Vlasenko3fa97af2014-04-15 11:43:29 +020094#include <sys/utsname.h> /* for setting $HOSTNAME */
Denys Vlasenko03dad222010-01-12 23:29:57 +010095
Denys Vlasenko20704f02011-03-23 17:59:27 +010096#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
97#include "unicode.h"
Denys Vlasenko03dad222010-01-12 23:29:57 +010098#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000099#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +0000100#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +0200101#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200102# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +0200103#else
104# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200105#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000106#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200107# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000108#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000109
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200110//config:config HUSH
111//config: bool "hush"
112//config: default y
113//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200114//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200115//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
116//config: case/esac. Redirections, here documents, $((arithmetic))
117//config: and functions are supported.
118//config:
119//config: It will compile and work on no-mmu systems.
120//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +0200121//config: It does not handle select, aliases, tilde expansion,
122//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200123//config:
124//config:config HUSH_BASH_COMPAT
125//config: bool "bash-compatible extensions"
126//config: default y
127//config: depends on HUSH
128//config: help
129//config: Enable bash-compatible extensions.
130//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200131//config:config HUSH_BRACE_EXPANSION
132//config: bool "Brace expansion"
133//config: default y
134//config: depends on HUSH_BASH_COMPAT
135//config: help
136//config: Enable {abc,def} extension.
137//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200138//config:config HUSH_HELP
139//config: bool "help builtin"
140//config: default y
141//config: depends on HUSH
142//config: help
143//config: Enable help builtin in hush. Code size + ~1 kbyte.
144//config:
145//config:config HUSH_INTERACTIVE
146//config: bool "Interactive mode"
147//config: default y
148//config: depends on HUSH
149//config: help
150//config: Enable interactive mode (prompt and command editing).
151//config: Without this, hush simply reads and executes commands
152//config: from stdin just like a shell script from a file.
153//config: No prompt, no PS1/PS2 magic shell variables.
154//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200155//config:config HUSH_SAVEHISTORY
156//config: bool "Save command history to .hush_history"
157//config: default y
158//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
159//config: help
160//config: Enable history saving in hush.
161//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200162//config:config HUSH_JOB
163//config: bool "Job control"
164//config: default y
165//config: depends on HUSH_INTERACTIVE
166//config: help
167//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
168//config: command (not entire shell), fg/bg builtins work. Without this option,
169//config: "cmd &" still works by simply spawning a process and immediately
170//config: prompting for next command (or executing next command in a script),
171//config: but no separate process group is formed.
172//config:
173//config:config HUSH_TICK
174//config: bool "Process substitution"
175//config: default y
176//config: depends on HUSH
177//config: help
178//config: Enable process substitution `command` and $(command) in hush.
179//config:
180//config:config HUSH_IF
181//config: bool "Support if/then/elif/else/fi"
182//config: default y
183//config: depends on HUSH
184//config: help
185//config: Enable if/then/elif/else/fi in hush.
186//config:
187//config:config HUSH_LOOPS
188//config: bool "Support for, while and until loops"
189//config: default y
190//config: depends on HUSH
191//config: help
192//config: Enable for, while and until loops in hush.
193//config:
194//config:config HUSH_CASE
195//config: bool "Support case ... esac statement"
196//config: default y
197//config: depends on HUSH
198//config: help
199//config: Enable case ... esac statement in hush. +400 bytes.
200//config:
201//config:config HUSH_FUNCTIONS
202//config: bool "Support funcname() { commands; } syntax"
203//config: default y
204//config: depends on HUSH
205//config: help
206//config: Enable support for shell functions in hush. +800 bytes.
207//config:
208//config:config HUSH_LOCAL
209//config: bool "Support local builtin"
210//config: default y
211//config: depends on HUSH_FUNCTIONS
212//config: help
213//config: Enable support for local variables in functions.
214//config:
215//config:config HUSH_RANDOM_SUPPORT
216//config: bool "Pseudorandom generator and $RANDOM variable"
217//config: default y
218//config: depends on HUSH
219//config: help
220//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
221//config: Each read of "$RANDOM" will generate a new pseudorandom value.
222//config:
223//config:config HUSH_EXPORT_N
224//config: bool "Support 'export -n' option"
225//config: default y
226//config: depends on HUSH
227//config: help
228//config: export -n unexports variables. It is a bash extension.
229//config:
230//config:config HUSH_MODE_X
231//config: bool "Support 'hush -x' option and 'set -x' command"
232//config: default y
233//config: depends on HUSH
234//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200235//config: This instructs hush to print commands before execution.
236//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200237//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200238//config:config MSH
239//config: bool "msh (deprecated: aliased to hush)"
240//config: default n
241//config: select HUSH
242//config: help
243//config: msh is deprecated and will be removed, please migrate to hush.
244//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200245
Denys Vlasenko20704f02011-03-23 17:59:27 +0100246//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
247//applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
248//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
249//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
250
251//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
252//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
253
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100254/* -i (interactive) and -s (read stdin) are also accepted,
255 * but currently do nothing, therefore aren't shown in help.
256 * NOMMU-specific options are not meant to be used by users,
257 * therefore we don't show them either.
258 */
259//usage:#define hush_trivial_usage
Denys Vlasenkof58f7052011-05-12 02:10:33 +0200260//usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100261//usage:#define hush_full_usage "\n\n"
262//usage: "Unix shell interpreter"
263
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100264//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100265//usage:#define msh_full_usage hush_full_usage
266
267//usage:#if ENABLE_FEATURE_SH_IS_HUSH
268//usage:# define sh_trivial_usage hush_trivial_usage
269//usage:# define sh_full_usage hush_full_usage
270//usage:#endif
271//usage:#if ENABLE_FEATURE_BASH_IS_HUSH
272//usage:# define bash_trivial_usage hush_trivial_usage
273//usage:# define bash_full_usage hush_full_usage
274//usage:#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200275
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000276
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200277/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000278#define LEAK_HUNTING 0
279#define BUILD_AS_NOMMU 0
280/* Enable/disable sanity checks. Ok to enable in production,
281 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
282 * Keeping 1 for now even in released versions.
283 */
284#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200285/* Slightly bigger (+200 bytes), but faster hush.
286 * So far it only enables a trick with counting SIGCHLDs and forks,
287 * which allows us to do fewer waitpid's.
288 * (we can detect a case where neither forks were done nor SIGCHLDs happened
289 * and therefore waitpid will return the same result as last time)
290 */
291#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200292/* TODO: implement simplified code for users which do not need ${var%...} ops
293 * So far ${var%...} ops are always enabled:
294 */
295#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000296
297
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000298#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000299# undef BB_MMU
300# undef USE_FOR_NOMMU
301# undef USE_FOR_MMU
302# define BB_MMU 0
303# define USE_FOR_NOMMU(...) __VA_ARGS__
304# define USE_FOR_MMU(...)
305#endif
306
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200307#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100308#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000309/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000310# undef CONFIG_FEATURE_SH_STANDALONE
311# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000312# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100313# undef IF_NOT_FEATURE_SH_STANDALONE
314# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000315# define IF_FEATURE_SH_STANDALONE(...)
316# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000317#endif
318
Denis Vlasenko05743d72008-02-10 12:10:08 +0000319#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000320# undef ENABLE_FEATURE_EDITING
321# define ENABLE_FEATURE_EDITING 0
322# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
323# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denys Vlasenko8cab6672012-04-20 14:48:00 +0200324# undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
325# define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000326#endif
327
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000328/* Do we support ANY keywords? */
329#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000330# define HAS_KEYWORDS 1
331# define IF_HAS_KEYWORDS(...) __VA_ARGS__
332# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000333#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000334# define HAS_KEYWORDS 0
335# define IF_HAS_KEYWORDS(...)
336# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000337#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000338
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000339/* If you comment out one of these below, it will be #defined later
340 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000341#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000342/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000343#define debug_printf_parse(...) do {} while (0)
344#define debug_print_tree(a, b) do {} while (0)
345#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000346#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000347#define debug_printf_jobs(...) do {} while (0)
348#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200349#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000350#define debug_printf_glob(...) do {} while (0)
351#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000352#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000353#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000354
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000355#define ERR_PTR ((void*)(long)1)
356
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200357#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000358
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200359#define _SPECIAL_VARS_STR "_*@$!?#"
360#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
361#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200362#if ENABLE_HUSH_BASH_COMPAT
363/* Support / and // replace ops */
364/* Note that // is stored as \ in "encoded" string representation */
365# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
366# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
367# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
368#else
369# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
370# define VAR_SUBST_OPS "%#:-=+?"
371# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
372#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200373
374#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000375
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200376struct variable;
377
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000378static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
379
380/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000381 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000382 */
383#if !BB_MMU
384typedef struct nommu_save_t {
385 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200386 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000387 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000388 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000389} nommu_save_t;
390#endif
391
Denys Vlasenko9b782552010-09-08 13:33:26 +0200392enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000393 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000394#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000395 RES_IF ,
396 RES_THEN ,
397 RES_ELIF ,
398 RES_ELSE ,
399 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000400#endif
401#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000402 RES_FOR ,
403 RES_WHILE ,
404 RES_UNTIL ,
405 RES_DO ,
406 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000407#endif
408#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000409 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000410#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000411#if ENABLE_HUSH_CASE
412 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200413 /* three pseudo-keywords support contrived "case" syntax: */
414 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
415 RES_MATCH , /* "word)" */
416 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000417 RES_ESAC ,
418#endif
419 RES_XXXX ,
420 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200421};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000422
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000423typedef struct o_string {
424 char *data;
425 int length; /* position where data is appended */
426 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200427 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000428 /* At least some part of the string was inside '' or "",
429 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200430 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000431 smallint has_empty_slot;
432 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
433} o_string;
434enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200435 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
436 EXP_FLAG_GLOB = 0x2,
437 /* Protect newly added chars against globbing
438 * by prepending \ to *, ?, [, \ */
439 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
440};
441enum {
442 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000443 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200444 NOT_ASSIGNMENT = 2,
445 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
446 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000447};
448/* Used for initialization: o_string foo = NULL_O_STRING; */
449#define NULL_O_STRING { NULL }
450
Denys Vlasenko29f9b722011-05-14 11:27:36 +0200451#ifndef debug_printf_parse
452static const char *const assignment_flag[] = {
453 "MAYBE_ASSIGNMENT",
454 "DEFINITELY_ASSIGNMENT",
455 "NOT_ASSIGNMENT",
456 "WORD_IS_KEYWORD",
457};
458#endif
459
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000460typedef struct in_str {
461 const char *p;
462 /* eof_flag=1: last char in ->p is really an EOF */
463 char eof_flag; /* meaningless if ->p == NULL */
464 char peek_buf[2];
465#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000466 smallint promptmode; /* 0: PS1, 1: PS2 */
467#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +0200468 int last_char;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000469 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200470 int (*get) (struct in_str *) FAST_FUNC;
471 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000472} in_str;
473#define i_getch(input) ((input)->get(input))
474#define i_peek(input) ((input)->peek(input))
475
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200476/* The descrip member of this structure is only used to make
477 * debugging output pretty */
478static const struct {
479 int mode;
480 signed char default_fd;
481 char descrip[3];
482} redir_table[] = {
483 { O_RDONLY, 0, "<" },
484 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
485 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
486 { O_CREAT|O_RDWR, 1, "<>" },
487 { O_RDONLY, 0, "<<" },
488/* Should not be needed. Bogus default_fd helps in debugging */
489/* { O_RDONLY, 77, "<<" }, */
490};
491
Eric Andersen25f27032001-04-26 23:22:31 +0000492struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000493 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000494 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000495 int rd_fd; /* fd to redirect */
496 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
497 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000498 smallint rd_type; /* (enum redir_type) */
499 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000500 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200501 * bit 0: do we need to trim leading tabs?
502 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000503 */
Eric Andersen25f27032001-04-26 23:22:31 +0000504};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000505typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200506 REDIRECT_INPUT = 0,
507 REDIRECT_OVERWRITE = 1,
508 REDIRECT_APPEND = 2,
509 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000510 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200511 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000512
513 REDIRFD_CLOSE = -3,
514 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000515 REDIRFD_TO_FILE = -1,
516 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000517
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000518 HEREDOC_SKIPTABS = 1,
519 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000520} redir_type;
521
Eric Andersen25f27032001-04-26 23:22:31 +0000522
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000523struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000524 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000525 int assignment_cnt; /* how many argv[i] are assignments? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200526 smallint cmd_type; /* CMD_xxx */
527#define CMD_NORMAL 0
528#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200529#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200530/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200531# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000532#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200533#if ENABLE_HUSH_FUNCTIONS
534# define CMD_FUNCDEF 3
535#endif
536
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100537 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200538 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
539 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000540#if !BB_MMU
541 char *group_as_string;
542#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000543#if ENABLE_HUSH_FUNCTIONS
544 struct function *child_func;
545/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200546 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000547 * When we execute "f1() {a;}" cmd, we create new function and clear
548 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200549 * When we execute "f1() {b;}", we notice that f1 exists,
550 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000551 * we put those fields back into cmd->xxx
552 * (struct function has ->parent_cmd ptr to facilitate that).
553 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
554 * Without this trick, loop would execute a;b;b;b;...
555 * instead of correct sequence a;b;a;b;...
556 * When command is freed, it severs the link
557 * (sets ->child_func->parent_cmd to NULL).
558 */
559#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000560 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000561/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
562 * and on execution these are substituted with their values.
563 * Substitution can make _several_ words out of one argv[n]!
564 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000565 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000566 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000567 struct redir_struct *redirects; /* I/O redirections */
568};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000569/* Is there anything in this command at all? */
570#define IS_NULL_CMD(cmd) \
571 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
572
Eric Andersen25f27032001-04-26 23:22:31 +0000573struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000574 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000575 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000576 int alive_cmds; /* number of commands running (not exited) */
577 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000578#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000579 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000580 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000581 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000582#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000583 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000584 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000585 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
586 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000587};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000588typedef enum pipe_style {
589 PIPE_SEQ = 1,
590 PIPE_AND = 2,
591 PIPE_OR = 3,
592 PIPE_BG = 4,
593} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000594/* Is there anything in this pipe at all? */
595#define IS_NULL_PIPE(pi) \
596 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000597
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000598/* This holds pointers to the various results of parsing */
599struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000600 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000601 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000602 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000603 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000604 /* last command in pipe (being constructed right now) */
605 struct command *command;
606 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000607 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000608#if !BB_MMU
609 o_string as_string;
610#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000611#if HAS_KEYWORDS
612 smallint ctx_res_w;
613 smallint ctx_inverted; /* "! cmd | cmd" */
614#if ENABLE_HUSH_CASE
615 smallint ctx_dsemicolon; /* ";;" seen */
616#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000617 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
618 int old_flag;
619 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000620 * example: "if pipe1; pipe2; then pipe3; fi"
621 * when we see "if" or "then", we malloc and copy current context,
622 * and make ->stack point to it. then we parse pipeN.
623 * when closing "then" / fi" / whatever is found,
624 * we move list_head into ->stack->command->group,
625 * copy ->stack into current context, and delete ->stack.
626 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000627 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000628 struct parse_context *stack;
629#endif
630};
631
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000632/* On program start, environ points to initial environment.
633 * putenv adds new pointers into it, unsetenv removes them.
634 * Neither of these (de)allocates the strings.
635 * setenv allocates new strings in malloc space and does putenv,
636 * and thus setenv is unusable (leaky) for shell's purposes */
637#define setenv(...) setenv_is_leaky_dont_use()
638struct variable {
639 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000640 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200641#if ENABLE_HUSH_LOCAL
642 unsigned func_nest_level;
643#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000644 int max_len; /* if > 0, name is part of initial env; else name is malloced */
645 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000646 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000647};
648
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000649enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000650 BC_BREAK = 1,
651 BC_CONTINUE = 2,
652};
653
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000654#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000655struct function {
656 struct function *next;
657 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000658 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000659 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200660# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000661 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200662# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000663};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000664#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000665
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000666
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100667/* set -/+o OPT support. (TODO: make it optional)
668 * bash supports the following opts:
669 * allexport off
670 * braceexpand on
671 * emacs on
672 * errexit off
673 * errtrace off
674 * functrace off
675 * hashall on
676 * histexpand off
677 * history on
678 * ignoreeof off
679 * interactive-comments on
680 * keyword off
681 * monitor on
682 * noclobber off
683 * noexec off
684 * noglob off
685 * nolog off
686 * notify off
687 * nounset off
688 * onecmd off
689 * physical off
690 * pipefail off
691 * posix off
692 * privileged off
693 * verbose off
694 * vi off
695 * xtrace off
696 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800697static const char o_opt_strings[] ALIGN1 =
698 "pipefail\0"
699 "noexec\0"
700#if ENABLE_HUSH_MODE_X
701 "xtrace\0"
702#endif
703 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100704enum {
705 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800706 OPT_O_NOEXEC,
707#if ENABLE_HUSH_MODE_X
708 OPT_O_XTRACE,
709#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100710 NUM_OPT_O
711};
712
713
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000714/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000715/* Sorted roughly by size (smaller offsets == smaller code) */
716struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000717 /* interactive_fd != 0 means we are an interactive shell.
718 * If we are, then saved_tty_pgrp can also be != 0, meaning
719 * that controlling tty is available. With saved_tty_pgrp == 0,
720 * job control still works, but terminal signals
721 * (^C, ^Z, ^Y, ^\) won't work at all, and background
722 * process groups can only be created with "cmd &".
723 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
724 * to give tty to the foreground process group,
725 * and will take it back when the group is stopped (^Z)
726 * or killed (^C).
727 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000728#if ENABLE_HUSH_INTERACTIVE
729 /* 'interactive_fd' is a fd# open to ctty, if we have one
730 * _AND_ if we decided to act interactively */
731 int interactive_fd;
732 const char *PS1;
733 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000734# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000735#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000736# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000737#endif
738#if ENABLE_FEATURE_EDITING
739 line_input_t *line_input_state;
740#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000741 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200742 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000743 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200744#if ENABLE_HUSH_RANDOM_SUPPORT
745 random_t random_gen;
746#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000747#if ENABLE_HUSH_JOB
748 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000749 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000750 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000751 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400752# define G_saved_tty_pgrp (G.saved_tty_pgrp)
753#else
754# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000755#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100756 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100757#if ENABLE_HUSH_MODE_X
758# define G_x_mode (G.o_opt[OPT_O_XTRACE])
759#else
760# define G_x_mode 0
761#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000762 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000763#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000764 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000765#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000766#if ENABLE_HUSH_FUNCTIONS
767 /* 0: outside of a function (or sourced file)
768 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000769 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000770 */
771 smallint flag_return_in_progress;
772#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000773 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000774 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000775 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000776 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000777 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000778 /* how many non-NULL argv's we have. NB: $# + 1 */
779 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000780 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000781#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000782 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000783#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000784#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000785 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000786 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000787#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000788 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000789 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200790 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200791 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000792#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000793 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200794# if ENABLE_HUSH_LOCAL
795 struct variable **shadowed_vars_pp;
796 unsigned func_nest_level;
797# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000798#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000799 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200800#if ENABLE_HUSH_FAST
801 unsigned count_SIGCHLD;
802 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200803 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200804#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +0200805 /* Which signals have non-DFL handler (even with no traps set)?
806 * Set at the start to:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200807 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
Denys Vlasenko10c01312011-05-11 11:49:21 +0200808 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200809 * The rest is cleared right before execv syscalls.
Denys Vlasenko10c01312011-05-11 11:49:21 +0200810 * Other than these two times, never modified.
811 */
812 unsigned special_sig_mask;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200813#if ENABLE_HUSH_JOB
814 unsigned fatal_sig_mask;
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200815# define G_fatal_sig_mask G.fatal_sig_mask
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200816#else
Denys Vlasenko75e77de2011-05-12 13:12:47 +0200817# define G_fatal_sig_mask 0
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200818#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000819 char **traps; /* char *traps[NSIG] */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +0200820 sigset_t pending_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000821#if HUSH_DEBUG
822 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000823 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000824#endif
Denys Vlasenko0806e402011-05-12 23:06:20 +0200825 struct sigaction sa;
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200826 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000827};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000828#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000829/* Not #defining name to G.name - this quickly gets unwieldy
830 * (too many defines). Also, I actually prefer to see when a variable
831 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000832#define INIT_G() do { \
833 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
Denys Vlasenko0806e402011-05-12 23:06:20 +0200834 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
835 sigfillset(&G.sa.sa_mask); \
836 G.sa.sa_flags = SA_RESTART; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000837} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000838
839
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000840/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200841static int builtin_cd(char **argv) FAST_FUNC;
842static int builtin_echo(char **argv) FAST_FUNC;
843static int builtin_eval(char **argv) FAST_FUNC;
844static int builtin_exec(char **argv) FAST_FUNC;
845static int builtin_exit(char **argv) FAST_FUNC;
846static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000847#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200848static int builtin_fg_bg(char **argv) FAST_FUNC;
849static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000850#endif
851#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200852static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000853#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200854#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200855static int builtin_history(char **argv) FAST_FUNC;
856#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200857#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200858static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200859#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000860#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200861static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000862#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400863#if ENABLE_PRINTF
864static int builtin_printf(char **argv) FAST_FUNC;
865#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200866static int builtin_pwd(char **argv) FAST_FUNC;
867static int builtin_read(char **argv) FAST_FUNC;
868static int builtin_set(char **argv) FAST_FUNC;
869static int builtin_shift(char **argv) FAST_FUNC;
870static int builtin_source(char **argv) FAST_FUNC;
871static int builtin_test(char **argv) FAST_FUNC;
872static int builtin_trap(char **argv) FAST_FUNC;
873static int builtin_type(char **argv) FAST_FUNC;
874static int builtin_true(char **argv) FAST_FUNC;
875static int builtin_umask(char **argv) FAST_FUNC;
876static int builtin_unset(char **argv) FAST_FUNC;
877static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000878#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200879static int builtin_break(char **argv) FAST_FUNC;
880static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000881#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000882#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200883static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000884#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000885
886/* Table of built-in functions. They can be forked or not, depending on
887 * context: within pipes, they fork. As simple commands, they do not.
888 * When used in non-forking context, they can change global variables
889 * in the parent shell process. If forked, of course they cannot.
890 * For example, 'unset foo | whatever' will parse and run, but foo will
891 * still be set at the end. */
892struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100893 const char *b_cmd;
894 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000895#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100896 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200897# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000898#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200899# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000900#endif
901};
902
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200903static const struct built_in_command bltins1[] = {
904 BLTIN("." , builtin_source , "Run commands in a file"),
905 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000906#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200907 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000908#endif
909#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200910 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000911#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200912 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000913#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200914 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000915#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200916 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
917 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
918 BLTIN("exit" , builtin_exit , "Exit"),
919 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000920#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200921 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000922#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000923#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200924 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000925#endif
Denys Vlasenkoff463a82013-05-12 02:45:23 +0200926#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +0200927 BLTIN("history" , builtin_history , "Show command history"),
928#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000929#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200930 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000931#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200932#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200933 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200934#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000935#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200936 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000937#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200938 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000939#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200940 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000941#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200942 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
943 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200944#if ENABLE_HUSH_BASH_COMPAT
945 BLTIN("source" , builtin_source , "Run commands in a file"),
946#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200947 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko2bba5912014-03-14 12:43:57 +0100948 BLTIN("true" , builtin_true , NULL),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100949 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100950 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200951 BLTIN("umask" , builtin_umask , "Set file creation mask"),
952 BLTIN("unset" , builtin_unset , "Unset variables"),
953 BLTIN("wait" , builtin_wait , "Wait for process"),
954};
955/* For now, echo and test are unconditionally enabled.
956 * Maybe make it configurable? */
957static const struct built_in_command bltins2[] = {
958 BLTIN("[" , builtin_test , NULL),
959 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400960#if ENABLE_PRINTF
961 BLTIN("printf" , builtin_printf , NULL),
962#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200963 BLTIN("pwd" , builtin_pwd , NULL),
964 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000965};
966
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000967
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000968/* Debug printouts.
969 */
970#if HUSH_DEBUG
971/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100972# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000973# define debug_enter() (G.debug_indent++)
974# define debug_leave() (G.debug_indent--)
975#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200976# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000977# define debug_enter() ((void)0)
978# define debug_leave() ((void)0)
979#endif
980
981#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100982# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000983#endif
984
985#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100986# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000987#endif
988
989#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100990#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000991#endif
992
993#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100994# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000995#endif
996
997#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100998# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000999# define DEBUG_JOBS 1
1000#else
1001# define DEBUG_JOBS 0
1002#endif
1003
1004#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001005# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001006# define DEBUG_EXPAND 1
1007#else
1008# define DEBUG_EXPAND 0
1009#endif
1010
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001011#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001012# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02001013#endif
1014
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001015#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001016# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001017# define DEBUG_GLOB 1
1018#else
1019# define DEBUG_GLOB 0
1020#endif
1021
1022#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001023# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001024#endif
1025
1026#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001027# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001028#endif
1029
1030#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001031# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001032# define DEBUG_CLEAN 1
1033#else
1034# define DEBUG_CLEAN 0
1035#endif
1036
1037#if DEBUG_EXPAND
1038static void debug_print_strings(const char *prefix, char **vv)
1039{
1040 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001041 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001042 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001043 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001044}
1045#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001046# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001047#endif
1048
1049
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001050/* Leak hunting. Use hush_leaktool.sh for post-processing.
1051 */
1052#if LEAK_HUNTING
1053static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001054{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001055 void *ptr = xmalloc((size + 0xff) & ~0xff);
1056 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1057 return ptr;
1058}
1059static void *xxrealloc(int lineno, void *ptr, size_t size)
1060{
1061 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1062 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1063 return ptr;
1064}
1065static char *xxstrdup(int lineno, const char *str)
1066{
1067 char *ptr = xstrdup(str);
1068 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1069 return ptr;
1070}
1071static void xxfree(void *ptr)
1072{
1073 fdprintf(2, "free %p\n", ptr);
1074 free(ptr);
1075}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001076# define xmalloc(s) xxmalloc(__LINE__, s)
1077# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1078# define xstrdup(s) xxstrdup(__LINE__, s)
1079# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001080#endif
1081
1082
1083/* Syntax and runtime errors. They always abort scripts.
1084 * In interactive use they usually discard unparsed and/or unexecuted commands
1085 * and return to the prompt.
1086 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1087 */
1088#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001089# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001090# define syntax_error(lineno, msg) syntax_error(msg)
1091# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1092# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1093# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1094# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001095#endif
1096
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001097static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001098{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001099 va_list p;
1100
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001101#if HUSH_DEBUG >= 2
1102 bb_error_msg("hush.c:%u", lineno);
1103#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001104 va_start(p, fmt);
1105 bb_verror_msg(fmt, p, NULL);
1106 va_end(p);
1107 if (!G_interactive_fd)
1108 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001109}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001110
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001111static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001112{
1113 if (msg)
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001114 bb_error_msg("syntax error: %s", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001115 else
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001116 bb_error_msg("syntax error");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001117}
1118
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001119static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001120{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001121 bb_error_msg("syntax error at '%s'", msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001122}
1123
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001124static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001125{
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001126 bb_error_msg("syntax error: unterminated %s", s);
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001127}
1128
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001129static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001130{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001131 char msg[2] = { ch, '\0' };
1132 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001133}
1134
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001135static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001136{
1137 char msg[2];
1138 msg[0] = ch;
1139 msg[1] = '\0';
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001140 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001141}
1142
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001143#if HUSH_DEBUG < 2
1144# undef die_if_script
1145# undef syntax_error
1146# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001147# undef syntax_error_unterm_ch
1148# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001149# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001150#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001151# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001152# define syntax_error(msg) syntax_error(__LINE__, msg)
1153# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1154# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1155# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1156# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001157#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001158
Denis Vlasenko552433b2009-04-04 19:29:21 +00001159
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001160#if ENABLE_HUSH_INTERACTIVE
1161static void cmdedit_update_prompt(void);
1162#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001163# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001164#endif
1165
1166
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001167/* Utility functions
1168 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001169/* Replace each \x with x in place, return ptr past NUL. */
1170static char *unbackslash(char *src)
1171{
Denys Vlasenko71885402009-09-24 01:44:13 +02001172 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001173 while (1) {
1174 if (*src == '\\')
1175 src++;
1176 if ((*dst++ = *src++) == '\0')
1177 break;
1178 }
1179 return dst;
1180}
1181
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001182static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001183{
1184 int i;
1185 unsigned count1;
1186 unsigned count2;
1187 char **v;
1188
1189 v = strings;
1190 count1 = 0;
1191 if (v) {
1192 while (*v) {
1193 count1++;
1194 v++;
1195 }
1196 }
1197 count2 = 0;
1198 v = add;
1199 while (*v) {
1200 count2++;
1201 v++;
1202 }
1203 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1204 v[count1 + count2] = NULL;
1205 i = count2;
1206 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001207 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001208 return v;
1209}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001210#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001211static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1212{
1213 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1214 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1215 return ptr;
1216}
1217#define add_strings_to_strings(strings, add, need_to_dup) \
1218 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1219#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001220
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001221/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001222static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001223{
1224 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001225 v[0] = add;
1226 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001227 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001228}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001229#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001230static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1231{
1232 char **ptr = add_string_to_strings(strings, add);
1233 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1234 return ptr;
1235}
1236#define add_string_to_strings(strings, add) \
1237 xx_add_string_to_strings(__LINE__, strings, add)
1238#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001239
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001240static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001241{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001242 char **v;
1243
1244 if (!strings)
1245 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001246 v = strings;
1247 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001248 free(*v);
1249 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001250 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001251 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001252}
1253
Denis Vlasenko76d50412008-06-10 16:19:39 +00001254
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001255/* Helpers for setting new $n and restoring them back
1256 */
1257typedef struct save_arg_t {
1258 char *sv_argv0;
1259 char **sv_g_argv;
1260 int sv_g_argc;
1261 smallint sv_g_malloced;
1262} save_arg_t;
1263
1264static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1265{
1266 int n;
1267
1268 sv->sv_argv0 = argv[0];
1269 sv->sv_g_argv = G.global_argv;
1270 sv->sv_g_argc = G.global_argc;
1271 sv->sv_g_malloced = G.global_args_malloced;
1272
1273 argv[0] = G.global_argv[0]; /* retain $0 */
1274 G.global_argv = argv;
1275 G.global_args_malloced = 0;
1276
1277 n = 1;
1278 while (*++argv)
1279 n++;
1280 G.global_argc = n;
1281}
1282
1283static void restore_G_args(save_arg_t *sv, char **argv)
1284{
1285 char **pp;
1286
1287 if (G.global_args_malloced) {
1288 /* someone ran "set -- arg1 arg2 ...", undo */
1289 pp = G.global_argv;
1290 while (*++pp) /* note: does not free $0 */
1291 free(*pp);
1292 free(G.global_argv);
1293 }
1294 argv[0] = sv->sv_argv0;
1295 G.global_argv = sv->sv_g_argv;
1296 G.global_argc = sv->sv_g_argc;
1297 G.global_args_malloced = sv->sv_g_malloced;
1298}
1299
1300
Denis Vlasenkod5762932009-03-31 11:22:57 +00001301/* Basic theory of signal handling in shell
1302 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001303 * This does not describe what hush does, rather, it is current understanding
1304 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001305 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1306 *
1307 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1308 * is finished or backgrounded. It is the same in interactive and
1309 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001310 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001311 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001312 * backgrounds (i.e. stops) or kills all members of currently running
1313 * pipe.
1314 *
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001315 * Wait builtin is interruptible by signals for which user trap is set
Denis Vlasenkod5762932009-03-31 11:22:57 +00001316 * or by SIGINT in interactive shell.
1317 *
1318 * Trap handlers will execute even within trap handlers. (right?)
1319 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001320 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1321 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001322 *
1323 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001324 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001325 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001326 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001327 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001328 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001329 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001330 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001331 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001332 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001333 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001334 *
1335 * SIGQUIT: ignore
1336 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001337 * SIGHUP (interactive):
1338 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001339 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001340 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1341 * that all pipe members are stopped. Try this in bash:
1342 * while :; do :; done - ^Z does not background it
1343 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001344 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001345 * of the command line, show prompt. NB: ^C does not send SIGINT
1346 * to interactive shell while shell is waiting for a pipe,
1347 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001348 * Example 1: this waits 5 sec, but does not execute ls:
1349 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1350 * Example 2: this does not wait and does not execute ls:
1351 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1352 * Example 3: this does not wait 5 sec, but executes ls:
1353 * "sleep 5; ls -l" + press ^C
Denys Vlasenkob8709032011-05-08 21:20:01 +02001354 * Example 4: this does not wait and does not execute ls:
1355 * "sleep 5 & wait; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001356 *
1357 * (What happens to signals which are IGN on shell start?)
1358 * (What happens with signal mask on shell start?)
1359 *
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001360 * Old implementation
1361 * ==================
Denis Vlasenkod5762932009-03-31 11:22:57 +00001362 * We use in-kernel pending signal mask to determine which signals were sent.
1363 * We block all signals which we don't want to take action immediately,
1364 * i.e. we block all signals which need to have special handling as described
1365 * above, and all signals which have traps set.
1366 * After each pipe execution, we extract any pending signals via sigtimedwait()
1367 * and act on them.
1368 *
Denys Vlasenko10c01312011-05-11 11:49:21 +02001369 * unsigned special_sig_mask: a mask of such "special" signals
Denis Vlasenkod5762932009-03-31 11:22:57 +00001370 * sigset_t blocked_set: current blocked signal set
1371 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001372 * "trap - SIGxxx":
Denys Vlasenko10c01312011-05-11 11:49:21 +02001373 * clear bit in blocked_set unless it is also in special_sig_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001374 * "trap 'cmd' SIGxxx":
1375 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001376 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001377 * unblock signals with special interactive handling
1378 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001379 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001380 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001381 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001382 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001383 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001384 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001385 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001386 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001387 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001388 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001389 * Standard says "When a subshell is entered, traps that are not being ignored
1390 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001391 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001392 *
1393 * Problem: the above approach makes it unwieldy to catch signals while
Denys Vlasenkoe95738f2013-07-08 03:13:08 +02001394 * we are in read builtin, or while we read commands from stdin:
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001395 * masked signals are not visible!
1396 *
1397 * New implementation
1398 * ==================
1399 * We record each signal we are interested in by installing signal handler
1400 * for them - a bit like emulating kernel pending signal mask in userspace.
1401 * We are interested in: signals which need to have special handling
1402 * as described above, and all signals which have traps set.
Denys Vlasenko8bd810b2013-11-28 01:50:01 +01001403 * Signals are recorded in pending_set.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001404 * After each pipe execution, we extract any pending signals
1405 * and act on them.
1406 *
1407 * unsigned special_sig_mask: a mask of shell-special signals.
1408 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1409 * char *traps[sig] if trap for sig is set (even if it's '').
1410 * sigset_t pending_set: set of sigs we received.
1411 *
1412 * "trap - SIGxxx":
1413 * if sig is in special_sig_mask, set handler back to:
1414 * record_pending_signo, or to IGN if it's a tty stop signal
1415 * if sig is in fatal_sig_mask, set handler back to sigexit.
1416 * else: set handler back to SIG_DFL
1417 * "trap 'cmd' SIGxxx":
1418 * set handler to record_pending_signo.
1419 * "trap '' SIGxxx":
1420 * set handler to SIG_IGN.
1421 * after [v]fork, if we plan to be a shell:
1422 * set signals with special interactive handling to SIG_DFL
1423 * (because child shell is not interactive),
1424 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1425 * after [v]fork, if we plan to exec:
1426 * POSIX says fork clears pending signal mask in child - no need to clear it.
1427 *
1428 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1429 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1430 *
1431 * Note (compat):
1432 * Standard says "When a subshell is entered, traps that are not being ignored
1433 * are set to the default actions". bash interprets it so that traps which
1434 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001435 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001436enum {
1437 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001438 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001439 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001440 | (1 << SIGHUP)
1441 ,
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001442 SPECIAL_JOBSTOP_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001443#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001444 | (1 << SIGTTIN)
1445 | (1 << SIGTTOU)
1446 | (1 << SIGTSTP)
1447#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001448 ,
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001449};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001450
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001451static void record_pending_signo(int sig)
Denys Vlasenko54e9e122011-05-09 00:52:15 +02001452{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001453 sigaddset(&G.pending_set, sig);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001454#if ENABLE_HUSH_FAST
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001455 if (sig == SIGCHLD) {
1456 G.count_SIGCHLD++;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001457//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 +02001458 }
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001459#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001460}
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001461
Denys Vlasenko0806e402011-05-12 23:06:20 +02001462static sighandler_t install_sighandler(int sig, sighandler_t handler)
1463{
1464 struct sigaction old_sa;
1465
1466 /* We could use signal() to install handlers... almost:
1467 * except that we need to mask ALL signals while handlers run.
1468 * I saw signal nesting in strace, race window isn't small.
1469 * SA_RESTART is also needed, but in Linux, signal()
1470 * sets SA_RESTART too.
1471 */
1472 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1473 /* sigfillset(&G.sa.sa_mask); - already done */
1474 /* G.sa.sa_flags = SA_RESTART; - already done */
1475 G.sa.sa_handler = handler;
1476 sigaction(sig, &G.sa, &old_sa);
1477 return old_sa.sa_handler;
1478}
1479
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001480#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001481
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001482/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001483# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001484/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001485# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001486
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001487/* Restores tty foreground process group, and exits.
1488 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001489 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001490 * or called directly with -EXITCODE.
1491 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001492static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001493static void sigexit(int sig)
1494{
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001495 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001496 * tty pgrp then, only top-level shell process does that */
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001497 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1498 /* Disable all signals: job control, SIGPIPE, etc.
1499 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1500 */
1501 sigprocmask_allsigs(SIG_BLOCK);
Mike Frysinger38478a62009-05-20 04:48:06 -04001502 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denys Vlasenkoebc1ee22011-05-12 10:59:18 +02001503 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001504
1505 /* Not a signal, just exit */
1506 if (sig <= 0)
1507 _exit(- sig);
1508
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001509 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001510}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001511#else
1512
Denys Vlasenko8391c482010-05-22 17:50:43 +02001513# define disable_restore_tty_pgrp_on_exit() ((void)0)
1514# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001515
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001516#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001517
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001518static sighandler_t pick_sighandler(unsigned sig)
1519{
1520 sighandler_t handler = SIG_DFL;
1521 if (sig < sizeof(unsigned)*8) {
1522 unsigned sigmask = (1 << sig);
1523
1524#if ENABLE_HUSH_JOB
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001525 /* is sig fatal? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001526 if (G_fatal_sig_mask & sigmask)
1527 handler = sigexit;
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001528 else
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001529#endif
1530 /* sig has special handling? */
Denys Vlasenko75e77de2011-05-12 13:12:47 +02001531 if (G.special_sig_mask & sigmask) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001532 handler = record_pending_signo;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001533 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001534 * in order to ignore them: they will be raised
Denys Vlasenkof58f7052011-05-12 02:10:33 +02001535 * in an endless loop when we try to do some
1536 * terminal ioctls! We do have to _ignore_ these.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001537 */
1538 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1539 handler = SIG_IGN;
Denys Vlasenko0c40a732011-05-12 09:50:12 +02001540 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001541 }
1542 return handler;
1543}
1544
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001545/* Restores tty foreground process group, and exits. */
1546static void hush_exit(int exitcode) NORETURN;
1547static void hush_exit(int exitcode)
1548{
Denys Vlasenkobede2152011-09-04 16:12:33 +02001549#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1550 save_history(G.line_input_state);
1551#endif
1552
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001553 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001554 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001555 char *argv[3];
1556 /* argv[0] is unused */
1557 argv[1] = G.traps[0];
1558 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001559 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001560 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001561 * "trap" will still show it, if executed
1562 * in the handler */
1563 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001564 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001565
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001566#if ENABLE_FEATURE_CLEAN_UP
1567 {
1568 struct variable *cur_var;
1569 if (G.cwd != bb_msg_unknown)
1570 free((char*)G.cwd);
1571 cur_var = G.top_var;
1572 while (cur_var) {
1573 struct variable *tmp = cur_var;
1574 if (!cur_var->max_len)
1575 free(cur_var->varstr);
1576 cur_var = cur_var->next;
1577 free(tmp);
1578 }
1579 }
1580#endif
1581
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001582#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001583 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001584 sigexit(- (exitcode & 0xff));
1585#else
1586 exit(exitcode);
1587#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001588}
1589
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001590
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001591//TODO: return a mask of ALL handled sigs?
1592static int check_and_run_traps(void)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001593{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001594 int last_sig = 0;
1595
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001596 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001597 int sig;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02001598
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001599 if (sigisemptyset(&G.pending_set))
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001600 break;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001601 sig = 0;
1602 do {
1603 sig++;
1604 if (sigismember(&G.pending_set, sig)) {
1605 sigdelset(&G.pending_set, sig);
1606 goto got_sig;
1607 }
1608 } while (sig < NSIG);
1609 break;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001610 got_sig:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001611 if (G.traps && G.traps[sig]) {
1612 if (G.traps[sig][0]) {
1613 /* We have user-defined handler */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001614 smalluint save_rcode;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001615 char *argv[3];
1616 /* argv[0] is unused */
1617 argv[1] = G.traps[sig];
1618 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001619 save_rcode = G.last_exitcode;
1620 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001621 G.last_exitcode = save_rcode;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001622 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001623 } /* else: "" trap, ignoring signal */
1624 continue;
1625 }
1626 /* not a trap: special action */
1627 switch (sig) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001628 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001629 /* Builtin was ^C'ed, make it look prettier: */
1630 bb_putchar('\n');
1631 G.flag_SIGINT = 1;
Denys Vlasenkob8709032011-05-08 21:20:01 +02001632 last_sig = sig;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001633 break;
1634#if ENABLE_HUSH_JOB
1635 case SIGHUP: {
1636 struct pipe *job;
1637 /* bash is observed to signal whole process groups,
1638 * not individual processes */
1639 for (job = G.job_list; job; job = job->next) {
1640 if (job->pgrp <= 0)
1641 continue;
1642 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1643 if (kill(- job->pgrp, SIGHUP) == 0)
1644 kill(- job->pgrp, SIGCONT);
1645 }
1646 sigexit(SIGHUP);
1647 }
1648#endif
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001649#if ENABLE_HUSH_FAST
1650 case SIGCHLD:
1651 G.count_SIGCHLD++;
1652//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1653 /* Note:
1654 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1655 * This simplifies wait builtin a bit.
1656 */
1657 break;
1658#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001659 default: /* ignored: */
1660 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02001661 /* Note:
1662 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1663 * Example: wait is not interrupted by TERM
Denys Vlasenkob8709032011-05-08 21:20:01 +02001664 * in interactive shell, because TERM is ignored.
1665 */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001666 break;
1667 }
1668 }
1669 return last_sig;
1670}
1671
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001672
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001673static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001674{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001675 if (force || G.cwd == NULL) {
1676 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1677 * we must not try to free(bb_msg_unknown) */
1678 if (G.cwd == bb_msg_unknown)
1679 G.cwd = NULL;
1680 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1681 if (!G.cwd)
1682 G.cwd = bb_msg_unknown;
1683 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001684 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001685}
1686
Denis Vlasenko83506862007-11-23 13:11:42 +00001687
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001688/*
1689 * Shell and environment variable support
1690 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001691static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001692{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001693 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001694 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001695
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001696 pp = &G.top_var;
1697 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001698 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001699 return pp;
1700 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001701 }
1702 return NULL;
1703}
1704
Denys Vlasenko03dad222010-01-12 23:29:57 +01001705static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001706{
Denys Vlasenko29082232010-07-16 13:52:32 +02001707 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001708 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001709
1710 if (G.expanded_assignments) {
1711 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001712 while (*cpp) {
1713 char *cp = *cpp;
1714 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1715 return cp + len + 1;
1716 cpp++;
1717 }
1718 }
1719
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001720 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001721 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001722 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001723
Denys Vlasenkodea47882009-10-09 15:40:49 +02001724 if (strcmp(name, "PPID") == 0)
1725 return utoa(G.root_ppid);
1726 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001727#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001728 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001729 return utoa(next_random(&G.random_gen));
1730#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001731 return NULL;
1732}
1733
1734/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001735 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001736 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001737 * 0: do not change export flag
1738 * (if creating new variable, flag will be 0)
1739 * 1: set export flag and putenv the variable
1740 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001741 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001742 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001743#if !BB_MMU && ENABLE_HUSH_LOCAL
1744/* all params are used */
1745#elif BB_MMU && ENABLE_HUSH_LOCAL
1746#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1747 set_local_var(str, flg_export, local_lvl)
1748#elif BB_MMU && !ENABLE_HUSH_LOCAL
1749#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001750 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001751#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1752#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1753 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001754#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001755static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001756{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001757 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001758 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001759 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001760 int name_len;
1761
Denis Vlasenko950bd722009-04-21 11:23:56 +00001762 eq_sign = strchr(str, '=');
1763 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001764 free(str);
1765 return -1;
1766 }
1767
Denis Vlasenko950bd722009-04-21 11:23:56 +00001768 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001769 var_pp = &G.top_var;
1770 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001771 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001772 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001773 continue;
1774 }
1775 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001776 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001777#if !BB_MMU
1778 if (!flg_read_only)
1779#endif
1780 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001781 free(str);
1782 return -1;
1783 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001784 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001785 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1786 *eq_sign = '\0';
1787 unsetenv(str);
1788 *eq_sign = '=';
1789 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001790#if ENABLE_HUSH_LOCAL
1791 if (cur->func_nest_level < local_lvl) {
1792 /* New variable is declared as local,
1793 * and existing one is global, or local
1794 * from enclosing function.
1795 * Remove and save old one: */
1796 *var_pp = cur->next;
1797 cur->next = *G.shadowed_vars_pp;
1798 *G.shadowed_vars_pp = cur;
1799 /* bash 3.2.33(1) and exported vars:
1800 * # export z=z
1801 * # f() { local z=a; env | grep ^z; }
1802 * # f
1803 * z=a
1804 * # env | grep ^z
1805 * z=z
1806 */
1807 if (cur->flg_export)
1808 flg_export = 1;
1809 break;
1810 }
1811#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001812 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001813 free_and_exp:
1814 free(str);
1815 goto exp;
1816 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001817 if (cur->max_len != 0) {
1818 if (cur->max_len >= strlen(str)) {
1819 /* This one is from startup env, reuse space */
1820 strcpy(cur->varstr, str);
1821 goto free_and_exp;
1822 }
1823 } else {
1824 /* max_len == 0 signifies "malloced" var, which we can
1825 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001826 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001827 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001828 cur->max_len = 0;
1829 goto set_str_and_exp;
1830 }
1831
Denys Vlasenko295fef82009-06-03 12:47:26 +02001832 /* Not found - create new variable struct */
1833 cur = xzalloc(sizeof(*cur));
1834#if ENABLE_HUSH_LOCAL
1835 cur->func_nest_level = local_lvl;
1836#endif
1837 cur->next = *var_pp;
1838 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001839
1840 set_str_and_exp:
1841 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001842#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001843 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001844#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001845 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001846 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001847 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001848 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1849 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001850 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001851 if (flg_export == -1) {
1852 cur->flg_export = 0;
1853 /* unsetenv was already done */
1854 } else {
1855 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1856 return putenv(cur->varstr);
1857 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001858 }
1859 return 0;
1860}
1861
Denys Vlasenko6db47842009-09-05 20:15:17 +02001862/* Used at startup and after each cd */
1863static void set_pwd_var(int exp)
1864{
1865 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1866 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1867}
1868
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001869static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001870{
1871 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001872 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001873
1874 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001875 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001876 var_pp = &G.top_var;
1877 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001878 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1879 if (cur->flg_read_only) {
1880 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001881 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001882 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001883 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001884 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1885 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001886 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1887 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001888 if (!cur->max_len)
1889 free(cur->varstr);
1890 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001891 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001892 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001893 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001894 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001895 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001896}
1897
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001898static int unset_local_var(const char *name)
1899{
1900 return unset_local_var_len(name, strlen(name));
1901}
1902
1903static void unset_vars(char **strings)
1904{
1905 char **v;
1906
1907 if (!strings)
1908 return;
1909 v = strings;
1910 while (*v) {
1911 const char *eq = strchrnul(*v, '=');
1912 unset_local_var_len(*v, (int)(eq - *v));
1913 v++;
1914 }
1915 free(strings);
1916}
1917
Denys Vlasenko03dad222010-01-12 23:29:57 +01001918static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001919{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001920 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001921 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001922}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001923
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001924
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001925/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001926 * Helpers for "var1=val1 var2=val2 cmd" feature
1927 */
1928static void add_vars(struct variable *var)
1929{
1930 struct variable *next;
1931
1932 while (var) {
1933 next = var->next;
1934 var->next = G.top_var;
1935 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001936 if (var->flg_export) {
1937 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001938 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001939 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001940 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001941 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001942 var = next;
1943 }
1944}
1945
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001946static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001947{
1948 char **s;
1949 struct variable *old = NULL;
1950
1951 if (!strings)
1952 return old;
1953 s = strings;
1954 while (*s) {
1955 struct variable *var_p;
1956 struct variable **var_pp;
1957 char *eq;
1958
1959 eq = strchr(*s, '=');
1960 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001961 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001962 if (var_pp) {
1963 /* Remove variable from global linked list */
1964 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001965 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001966 *var_pp = var_p->next;
1967 /* Add it to returned list */
1968 var_p->next = old;
1969 old = var_p;
1970 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001971 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001972 }
1973 s++;
1974 }
1975 return old;
1976}
1977
1978
1979/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001980 * in_str support
1981 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001982static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001983{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001984 int ch = *i->p;
1985 if (ch != '\0') {
1986 i->p++;
Denys Vlasenkocecbc982011-03-30 18:54:52 +02001987 i->last_char = ch;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001988 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001989 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001990 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001991}
1992
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001993static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001994{
1995 return *i->p;
1996}
1997
1998#if ENABLE_HUSH_INTERACTIVE
1999
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002000static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002001{
Mike Frysingerec2c6552009-03-28 12:24:44 +00002002 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002003 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00002004 if (G.PS1 == NULL)
2005 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002006 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02002007 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00002008 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02002009 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00002010 if (G.PS2 == NULL)
2011 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002012}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002013
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002014static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002015{
2016 const char *prompt_str;
2017 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00002018 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2019 /* Set up the prompt */
2020 if (promptmode == 0) { /* PS1 */
2021 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02002022 /* bash uses $PWD value, even if it is set by user.
2023 * It uses current dir only if PWD is unset.
2024 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002025 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00002026 prompt_str = G.PS1;
2027 } else
2028 prompt_str = G.PS2;
2029 } else
2030 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002031 debug_printf("result '%s'\n", prompt_str);
2032 return prompt_str;
2033}
2034
2035static void get_user_input(struct in_str *i)
2036{
2037 int r;
2038 const char *prompt_str;
2039
2040 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002041# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002042 /* Enable command line editing only while a command line
2043 * is actually being read */
2044 do {
Denys Vlasenko20704f02011-03-23 17:59:27 +01002045 /* Unicode support should be activated even if LANG is set
2046 * _during_ shell execution, not only if it was set when
2047 * shell was started. Therefore, re-check LANG every time:
2048 */
Denys Vlasenko3e7ecb12013-07-02 17:30:23 +02002049 const char *s = get_local_var_value("LC_ALL");
Denys Vlasenko2301d122013-07-05 22:00:57 +02002050 if (!s) s = get_local_var_value("LC_CTYPE");
Denys Vlasenko3e7ecb12013-07-02 17:30:23 +02002051 if (!s) s = get_local_var_value("LANG");
2052 reinit_unicode(s);
Denys Vlasenko20704f02011-03-23 17:59:27 +01002053
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002054 G.flag_SIGINT = 0;
2055 /* buglet: SIGINT will not make new prompt to appear _at once_,
2056 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01002057 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002058 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002059 check_and_run_traps();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002060 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002061 i->eof_flag = (r < 0);
2062 if (i->eof_flag) { /* EOF/error detected */
2063 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2064 G.user_input_buf[1] = '\0';
2065 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02002066# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002067 do {
2068 G.flag_SIGINT = 0;
Denys Vlasenkob8709032011-05-08 21:20:01 +02002069 if (i->last_char == '\0' || i->last_char == '\n') {
2070 /* Why check_and_run_traps here? Try this interactively:
2071 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2072 * $ <[enter], repeatedly...>
2073 * Without check_and_run_traps, handler never runs.
2074 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02002075 check_and_run_traps();
Denys Vlasenkob8709032011-05-08 21:20:01 +02002076 fputs(prompt_str, stdout);
2077 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01002078 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002079 G.user_input_buf[0] = r = fgetc(i->file);
2080 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00002081 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002082 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02002083# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002084 i->p = G.user_input_buf;
2085}
2086
2087#endif /* INTERACTIVE */
2088
2089/* This is the magic location that prints prompts
2090 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002091static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002092{
2093 int ch;
2094
2095 /* If there is data waiting, eat it up */
2096 if (i->p && *i->p) {
2097#if ENABLE_HUSH_INTERACTIVE
2098 take_cached:
2099#endif
2100 ch = *i->p++;
2101 if (i->eof_flag && !*i->p)
2102 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002103 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002104 } else {
2105 /* need to double check i->file because we might be doing something
2106 * more complicated by now, like sourcing or substituting. */
2107#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002108 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002109 do {
2110 get_user_input(i);
2111 } while (!*i->p); /* need non-empty line */
2112 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002113 goto take_cached;
2114 }
2115#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00002116 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002117 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002118 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02002119 i->last_char = ch;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002120 return ch;
2121}
2122
Denis Vlasenko913a2012009-04-05 22:17:04 +00002123/* All callers guarantee this routine will never
2124 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002125 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002126static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002127{
2128 int ch;
2129 if (i->p && *i->p) {
2130 if (i->eof_flag && !i->p[1])
2131 return EOF;
2132 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002133 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002134 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00002135 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002136 i->eof_flag = (ch == EOF);
2137 i->peek_buf[0] = ch;
2138 i->peek_buf[1] = '\0';
2139 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00002140 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002141 return ch;
2142}
2143
2144static void setup_file_in_str(struct in_str *i, FILE *f)
2145{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002146 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002147 i->peek = file_peek;
2148 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002149 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002150 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002151 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002152}
2153
2154static void setup_string_in_str(struct in_str *i, const char *s)
2155{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002156 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002157 i->peek = static_peek;
2158 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002159 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002160 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002161 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002162}
2163
2164
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002165/*
2166 * o_string support
2167 */
2168#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002169
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002170static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002171{
2172 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002173 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002174 if (o->data)
2175 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002176}
2177
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002178static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002179{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002180 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002181 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002182}
2183
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002184static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2185{
2186 free(o->data);
2187}
2188
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002189static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002190{
2191 if (o->length + len > o->maxlen) {
2192 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2193 o->data = xrealloc(o->data, 1 + o->maxlen);
2194 }
2195}
2196
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002197static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002198{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002199 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2200 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002201 o->data[o->length] = ch;
2202 o->length++;
2203 o->data[o->length] = '\0';
2204}
2205
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002206static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002207{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002208 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002209 memcpy(&o->data[o->length], str, len);
2210 o->length += len;
2211 o->data[o->length] = '\0';
2212}
2213
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002214static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002215{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002216 o_addblock(o, str, strlen(str));
2217}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002218
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002219#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002220static void nommu_addchr(o_string *o, int ch)
2221{
2222 if (o)
2223 o_addchr(o, ch);
2224}
2225#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002226# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002227#endif
2228
2229static void o_addstr_with_NUL(o_string *o, const char *str)
2230{
2231 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002232}
2233
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002234/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002235 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002236 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2237 * Apparently, on unquoted $v bash still does globbing
2238 * ("v='*.txt'; echo $v" prints all .txt files),
2239 * but NOT brace expansion! Thus, there should be TWO independent
2240 * quoting mechanisms on $v expansion side: one protects
2241 * $v from brace expansion, and other additionally protects "$v" against globbing.
2242 * We have only second one.
2243 */
2244
Denys Vlasenko9e800222010-10-03 14:28:04 +02002245#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002246# define MAYBE_BRACES "{}"
2247#else
2248# define MAYBE_BRACES ""
2249#endif
2250
Eric Andersen25f27032001-04-26 23:22:31 +00002251/* My analysis of quoting semantics tells me that state information
2252 * is associated with a destination, not a source.
2253 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002254static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002255{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002256 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002257 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002258 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002259 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002260 o_grow_by(o, sz);
2261 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002262 o->data[o->length] = '\\';
2263 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002264 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002265 o->data[o->length] = ch;
2266 o->length++;
2267 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002268}
2269
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002270static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002271{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002272 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002273 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2274 && strchr("*?[\\" MAYBE_BRACES, ch)
2275 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002276 sz++;
2277 o->data[o->length] = '\\';
2278 o->length++;
2279 }
2280 o_grow_by(o, sz);
2281 o->data[o->length] = ch;
2282 o->length++;
2283 o->data[o->length] = '\0';
2284}
2285
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002286static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002287{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002288 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002289 char ch;
2290 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002291 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002292 if (ordinary_cnt > len) /* paranoia */
2293 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002294 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002295 if (ordinary_cnt == len)
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002296 return; /* NUL is already added by o_addblock */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002297 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002298 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002299
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002300 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002301 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002302 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002303 sz++;
2304 o->data[o->length] = '\\';
2305 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002306 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002307 o_grow_by(o, sz);
2308 o->data[o->length] = ch;
2309 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002310 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002311 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002312}
2313
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002314static void o_addQblock(o_string *o, const char *str, int len)
2315{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002316 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002317 o_addblock(o, str, len);
2318 return;
2319 }
2320 o_addqblock(o, str, len);
2321}
2322
Denys Vlasenko38292b62010-09-05 14:49:40 +02002323static void o_addQstr(o_string *o, const char *str)
2324{
2325 o_addQblock(o, str, strlen(str));
2326}
2327
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002328/* A special kind of o_string for $VAR and `cmd` expansion.
2329 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002330 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002331 * list[i] contains an INDEX (int!) into this string data.
2332 * It means that if list[] needs to grow, data needs to be moved higher up
2333 * but list[i]'s need not be modified.
2334 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002335 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002336 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2337 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002338#if DEBUG_EXPAND || DEBUG_GLOB
2339static void debug_print_list(const char *prefix, o_string *o, int n)
2340{
2341 char **list = (char**)o->data;
2342 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2343 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002344
2345 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002346 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 +02002347 prefix, list, n, string_start, o->length, o->maxlen,
2348 !!(o->o_expflags & EXP_FLAG_GLOB),
2349 o->has_quoted_part,
2350 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002351 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002352 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002353 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2354 o->data + (int)(uintptr_t)list[i] + string_start,
2355 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002356 i++;
2357 }
2358 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002359 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002360 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002361 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002362 }
2363}
2364#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002365# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002366#endif
2367
2368/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2369 * in list[n] so that it points past last stored byte so far.
2370 * It returns n+1. */
2371static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002372{
2373 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002374 int string_start;
2375 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002376
2377 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002378 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2379 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002380 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002381 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002382 /* list[n] points to string_start, make space for 16 more pointers */
2383 o->maxlen += 0x10 * sizeof(list[0]);
2384 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002385 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002386 memmove(list + n + 0x10, list + n, string_len);
2387 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002388 } else {
2389 debug_printf_list("list[%d]=%d string_start=%d\n",
2390 n, string_len, string_start);
2391 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002392 } else {
2393 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002394 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2395 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002396 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2397 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002398 o->has_empty_slot = 0;
2399 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02002400 o->has_quoted_part = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002401 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002402 return n + 1;
2403}
2404
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002405/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002406static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002407{
2408 char **list = (char**)o->data;
2409 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2410
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002411 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002412}
2413
Denys Vlasenko9e800222010-10-03 14:28:04 +02002414#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002415/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2416 * first, it processes even {a} (no commas), second,
2417 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002418 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002419 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002420
2421/* Helper */
2422static int glob_needed(const char *s)
2423{
2424 while (*s) {
2425 if (*s == '\\') {
2426 if (!s[1])
2427 return 0;
2428 s += 2;
2429 continue;
2430 }
2431 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2432 return 1;
2433 s++;
2434 }
2435 return 0;
2436}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002437/* Return pointer to next closing brace or to comma */
2438static const char *next_brace_sub(const char *cp)
2439{
2440 unsigned depth = 0;
2441 cp++;
2442 while (*cp != '\0') {
2443 if (*cp == '\\') {
2444 if (*++cp == '\0')
2445 break;
2446 cp++;
2447 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002448 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002449 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002450 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002451 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002452 depth++;
2453 }
2454
2455 return *cp != '\0' ? cp : NULL;
2456}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002457/* Recursive brace globber. Note: may garble pattern[]. */
2458static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002459{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002460 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002461 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002462 const char *next;
2463 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002464 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002465 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002466
2467 debug_printf_glob("glob_brace('%s')\n", pattern);
2468
2469 begin = pattern;
2470 while (1) {
2471 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002472 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002473 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002474 /* Find the first sub-pattern and at the same time
2475 * find the rest after the closing brace */
2476 next = next_brace_sub(begin);
2477 if (next == NULL) {
2478 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002479 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002480 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002481 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002482 /* "{abc}" with no commas - illegal
2483 * brace expr, disregard and skip it */
2484 begin = next + 1;
2485 continue;
2486 }
2487 break;
2488 }
2489 if (*begin == '\\' && begin[1] != '\0')
2490 begin++;
2491 begin++;
2492 }
2493 debug_printf_glob("begin:%s\n", begin);
2494 debug_printf_glob("next:%s\n", next);
2495
2496 /* Now find the end of the whole brace expression */
2497 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002498 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002499 rest = next_brace_sub(rest);
2500 if (rest == NULL) {
2501 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002502 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002503 }
2504 debug_printf_glob("rest:%s\n", rest);
2505 }
2506 rest_len = strlen(++rest) + 1;
2507
2508 /* We are sure the brace expression is well-formed */
2509
2510 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002511 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002512
2513 /* We have a brace expression. BEGIN points to the opening {,
2514 * NEXT points past the terminator of the first element, and REST
2515 * points past the final }. We will accumulate result names from
2516 * recursive runs for each brace alternative in the buffer using
2517 * GLOB_APPEND. */
2518
2519 p = begin + 1;
2520 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002521 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002522 memcpy(
2523 mempcpy(
2524 mempcpy(new_pattern_buf,
2525 /* We know the prefix for all sub-patterns */
2526 pattern, begin - pattern),
2527 p, next - p),
2528 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002529
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002530 /* Note: glob_brace() may garble new_pattern_buf[].
2531 * That's why we re-copy prefix every time (1st memcpy above).
2532 */
2533 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002534 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002535 /* We saw the last entry */
2536 break;
2537 }
2538 p = next + 1;
2539 next = next_brace_sub(next);
2540 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002541 free(new_pattern_buf);
2542 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002543
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002544 simple_glob:
2545 {
2546 int gr;
2547 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002548
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002549 memset(&globdata, 0, sizeof(globdata));
2550 gr = glob(pattern, 0, NULL, &globdata);
2551 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2552 if (gr != 0) {
2553 if (gr == GLOB_NOMATCH) {
2554 globfree(&globdata);
2555 /* NB: garbles parameter */
2556 unbackslash(pattern);
2557 o_addstr_with_NUL(o, pattern);
2558 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2559 return o_save_ptr_helper(o, n);
2560 }
2561 if (gr == GLOB_NOSPACE)
2562 bb_error_msg_and_die(bb_msg_memory_exhausted);
2563 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2564 * but we didn't specify it. Paranoia again. */
2565 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2566 }
2567 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2568 char **argv = globdata.gl_pathv;
2569 while (1) {
2570 o_addstr_with_NUL(o, *argv);
2571 n = o_save_ptr_helper(o, n);
2572 argv++;
2573 if (!*argv)
2574 break;
2575 }
2576 }
2577 globfree(&globdata);
2578 }
2579 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002580}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002581/* Performs globbing on last list[],
2582 * saving each result as a new list[].
2583 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002584static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002585{
2586 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002587
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002588 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002589 if (!o->data)
2590 return o_save_ptr_helper(o, n);
2591 pattern = o->data + o_get_last_ptr(o, n);
2592 debug_printf_glob("glob pattern '%s'\n", pattern);
2593 if (!glob_needed(pattern)) {
2594 /* unbackslash last string in o in place, fix length */
2595 o->length = unbackslash(pattern) - o->data;
2596 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2597 return o_save_ptr_helper(o, n);
2598 }
2599
2600 copy = xstrdup(pattern);
2601 /* "forget" pattern in o */
2602 o->length = pattern - o->data;
2603 n = glob_brace(copy, o, n);
2604 free(copy);
2605 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002606 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002607 return n;
2608}
2609
Denys Vlasenko238081f2010-10-03 14:26:26 +02002610#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002611
2612/* Helper */
2613static int glob_needed(const char *s)
2614{
2615 while (*s) {
2616 if (*s == '\\') {
2617 if (!s[1])
2618 return 0;
2619 s += 2;
2620 continue;
2621 }
2622 if (*s == '*' || *s == '[' || *s == '?')
2623 return 1;
2624 s++;
2625 }
2626 return 0;
2627}
2628/* Performs globbing on last list[],
2629 * saving each result as a new list[].
2630 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002631static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002632{
2633 glob_t globdata;
2634 int gr;
2635 char *pattern;
2636
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002637 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002638 if (!o->data)
2639 return o_save_ptr_helper(o, n);
2640 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002641 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002642 if (!glob_needed(pattern)) {
2643 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002644 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002645 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002646 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002647 return o_save_ptr_helper(o, n);
2648 }
2649
2650 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002651 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2652 * If we glob "*.\*" and don't find anything, we need
2653 * to fall back to using literal "*.*", but GLOB_NOCHECK
2654 * will return "*.\*"!
2655 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002656 gr = glob(pattern, 0, NULL, &globdata);
2657 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002658 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002659 if (gr == GLOB_NOMATCH) {
2660 globfree(&globdata);
2661 goto literal;
2662 }
2663 if (gr == GLOB_NOSPACE)
2664 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002665 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2666 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002667 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002668 }
2669 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2670 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002671 /* "forget" pattern in o */
2672 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002673 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002674 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002675 n = o_save_ptr_helper(o, n);
2676 argv++;
2677 if (!*argv)
2678 break;
2679 }
2680 }
2681 globfree(&globdata);
2682 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002683 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002684 return n;
2685}
2686
Denys Vlasenko238081f2010-10-03 14:26:26 +02002687#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002688
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002689/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002690 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002691static int o_save_ptr(o_string *o, int n)
2692{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002693 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002694 /* If o->has_empty_slot, list[n] was already globbed
2695 * (if it was requested back then when it was filled)
2696 * so don't do that again! */
2697 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002698 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002699 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002700 return o_save_ptr_helper(o, n);
2701}
2702
2703/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002704static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002705{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002706 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002707 int string_start;
2708
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002709 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2710 if (DEBUG_EXPAND)
2711 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002712 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002713 list = (char**)o->data;
2714 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2715 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002716 while (n) {
2717 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002718 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002719 }
2720 return list;
2721}
2722
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002723static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002724
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002725/* Returns pi->next - next pipe in the list */
2726static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002727{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002728 struct pipe *next;
2729 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002730
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002731 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002732 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002733 struct command *command;
2734 struct redir_struct *r, *rnext;
2735
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002736 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002737 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002738 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002739 if (DEBUG_CLEAN) {
2740 int a;
2741 char **p;
2742 for (a = 0, p = command->argv; *p; a++, p++) {
2743 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2744 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002745 }
2746 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002747 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002748 }
2749 /* not "else if": on syntax error, we may have both! */
2750 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002751 debug_printf_clean(" begin group (cmd_type:%d)\n",
2752 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002753 free_pipe_list(command->group);
2754 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002755 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002756 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002757 /* else is crucial here.
2758 * If group != NULL, child_func is meaningless */
2759#if ENABLE_HUSH_FUNCTIONS
2760 else if (command->child_func) {
2761 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2762 command->child_func->parent_cmd = NULL;
2763 }
2764#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002765#if !BB_MMU
2766 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002767 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002768#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002769 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002770 debug_printf_clean(" redirect %d%s",
2771 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002772 /* guard against the case >$FOO, where foo is unset or blank */
2773 if (r->rd_filename) {
2774 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2775 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002776 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002777 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002778 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002779 rnext = r->next;
2780 free(r);
2781 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002782 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002783 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002784 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002785 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002786#if ENABLE_HUSH_JOB
2787 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002788 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002789#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002790
2791 next = pi->next;
2792 free(pi);
2793 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002794}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002795
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002796static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002797{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002798 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002799#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002800 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002801#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002802 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002803 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002804 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002805}
2806
2807
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002808/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002809
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002810#ifndef debug_print_tree
2811static void debug_print_tree(struct pipe *pi, int lvl)
2812{
2813 static const char *const PIPE[] = {
2814 [PIPE_SEQ] = "SEQ",
2815 [PIPE_AND] = "AND",
2816 [PIPE_OR ] = "OR" ,
2817 [PIPE_BG ] = "BG" ,
2818 };
2819 static const char *RES[] = {
2820 [RES_NONE ] = "NONE" ,
2821# if ENABLE_HUSH_IF
2822 [RES_IF ] = "IF" ,
2823 [RES_THEN ] = "THEN" ,
2824 [RES_ELIF ] = "ELIF" ,
2825 [RES_ELSE ] = "ELSE" ,
2826 [RES_FI ] = "FI" ,
2827# endif
2828# if ENABLE_HUSH_LOOPS
2829 [RES_FOR ] = "FOR" ,
2830 [RES_WHILE] = "WHILE",
2831 [RES_UNTIL] = "UNTIL",
2832 [RES_DO ] = "DO" ,
2833 [RES_DONE ] = "DONE" ,
2834# endif
2835# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2836 [RES_IN ] = "IN" ,
2837# endif
2838# if ENABLE_HUSH_CASE
2839 [RES_CASE ] = "CASE" ,
2840 [RES_CASE_IN ] = "CASE_IN" ,
2841 [RES_MATCH] = "MATCH",
2842 [RES_CASE_BODY] = "CASE_BODY",
2843 [RES_ESAC ] = "ESAC" ,
2844# endif
2845 [RES_XXXX ] = "XXXX" ,
2846 [RES_SNTX ] = "SNTX" ,
2847 };
2848 static const char *const CMDTYPE[] = {
2849 "{}",
2850 "()",
2851 "[noglob]",
2852# if ENABLE_HUSH_FUNCTIONS
2853 "func()",
2854# endif
2855 };
2856
2857 int pin, prn;
2858
2859 pin = 0;
2860 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002861 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002862 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2863 prn = 0;
2864 while (prn < pi->num_cmds) {
2865 struct command *command = &pi->cmds[prn];
2866 char **argv = command->argv;
2867
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002868 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002869 lvl*2, "", prn,
2870 command->assignment_cnt);
2871 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002872 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002873 CMDTYPE[command->cmd_type],
2874 argv
2875# if !BB_MMU
2876 , " group_as_string:", command->group_as_string
2877# else
2878 , "", ""
2879# endif
2880 );
2881 debug_print_tree(command->group, lvl+1);
2882 prn++;
2883 continue;
2884 }
2885 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002886 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002887 argv++;
2888 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002889 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002890 prn++;
2891 }
2892 pi = pi->next;
2893 pin++;
2894 }
2895}
2896#endif /* debug_print_tree */
2897
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002898static struct pipe *new_pipe(void)
2899{
Eric Andersen25f27032001-04-26 23:22:31 +00002900 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002901 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002902 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002903 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002904 return pi;
2905}
2906
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002907/* Command (member of a pipe) is complete, or we start a new pipe
2908 * if ctx->command is NULL.
2909 * No errors possible here.
2910 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002911static int done_command(struct parse_context *ctx)
2912{
2913 /* The command is really already in the pipe structure, so
2914 * advance the pipe counter and make a new, null command. */
2915 struct pipe *pi = ctx->pipe;
2916 struct command *command = ctx->command;
2917
2918 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002919 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002920 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002921 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002922 }
2923 pi->num_cmds++;
2924 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002925 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002926 } else {
2927 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2928 }
2929
2930 /* Only real trickiness here is that the uncommitted
2931 * command structure is not counted in pi->num_cmds. */
2932 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002933 ctx->command = command = &pi->cmds[pi->num_cmds];
2934 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002935 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002936 return pi->num_cmds; /* used only for 0/nonzero check */
2937}
2938
2939static void done_pipe(struct parse_context *ctx, pipe_style type)
2940{
2941 int not_null;
2942
2943 debug_printf_parse("done_pipe entered, followup %d\n", type);
2944 /* Close previous command */
2945 not_null = done_command(ctx);
2946 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002947#if HAS_KEYWORDS
2948 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2949 ctx->ctx_inverted = 0;
2950 ctx->pipe->res_word = ctx->ctx_res_w;
2951#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002952
2953 /* Without this check, even just <enter> on command line generates
2954 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002955 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002956 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002957#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002958 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002959#endif
2960#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002961 || ctx->ctx_res_w == RES_DONE
2962 || ctx->ctx_res_w == RES_FOR
2963 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002964#endif
2965#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002966 || ctx->ctx_res_w == RES_ESAC
2967#endif
2968 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002969 struct pipe *new_p;
2970 debug_printf_parse("done_pipe: adding new pipe: "
2971 "not_null:%d ctx->ctx_res_w:%d\n",
2972 not_null, ctx->ctx_res_w);
2973 new_p = new_pipe();
2974 ctx->pipe->next = new_p;
2975 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002976 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002977 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002978 * This is used to control execution.
2979 * RES_FOR and RES_IN are NOT sticky (needed to support
2980 * cases where variable or value happens to match a keyword):
2981 */
2982#if ENABLE_HUSH_LOOPS
2983 if (ctx->ctx_res_w == RES_FOR
2984 || ctx->ctx_res_w == RES_IN)
2985 ctx->ctx_res_w = RES_NONE;
2986#endif
2987#if ENABLE_HUSH_CASE
2988 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002989 ctx->ctx_res_w = RES_CASE_BODY;
2990 if (ctx->ctx_res_w == RES_CASE)
2991 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002992#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002993 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002994 /* Create the memory for command, roughly:
2995 * ctx->pipe->cmds = new struct command;
2996 * ctx->command = &ctx->pipe->cmds[0];
2997 */
2998 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002999 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003000 }
3001 debug_printf_parse("done_pipe return\n");
3002}
3003
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003004static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003005{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003006 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003007 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003008 /* Create the memory for command, roughly:
3009 * ctx->pipe->cmds = new struct command;
3010 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003011 */
3012 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003013}
3014
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003015/* If a reserved word is found and processed, parse context is modified
3016 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003017 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003018#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003019struct reserved_combo {
3020 char literal[6];
3021 unsigned char res;
3022 unsigned char assignment_flag;
3023 int flag;
3024};
3025enum {
3026 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003027# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003028 FLAG_IF = (1 << RES_IF ),
3029 FLAG_THEN = (1 << RES_THEN ),
3030 FLAG_ELIF = (1 << RES_ELIF ),
3031 FLAG_ELSE = (1 << RES_ELSE ),
3032 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003033# endif
3034# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003035 FLAG_FOR = (1 << RES_FOR ),
3036 FLAG_WHILE = (1 << RES_WHILE),
3037 FLAG_UNTIL = (1 << RES_UNTIL),
3038 FLAG_DO = (1 << RES_DO ),
3039 FLAG_DONE = (1 << RES_DONE ),
3040 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003041# endif
3042# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003043 FLAG_MATCH = (1 << RES_MATCH),
3044 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003045# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003046 FLAG_START = (1 << RES_XXXX ),
3047};
3048
3049static const struct reserved_combo* match_reserved_word(o_string *word)
3050{
Eric Andersen25f27032001-04-26 23:22:31 +00003051 /* Mostly a list of accepted follow-up reserved words.
3052 * FLAG_END means we are done with the sequence, and are ready
3053 * to turn the compound list into a command.
3054 * FLAG_START means the word must start a new compound list.
3055 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003056 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003057# if ENABLE_HUSH_IF
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003058 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3059 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3060 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3061 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3062 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3063 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003064# endif
3065# if ENABLE_HUSH_LOOPS
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003066 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3067 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3068 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3069 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3070 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3071 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003072# endif
3073# if ENABLE_HUSH_CASE
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003074 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3075 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003076# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003077 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003078 const struct reserved_combo *r;
3079
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02003080 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003081 if (strcmp(word->data, r->literal) == 0)
3082 return r;
3083 }
3084 return NULL;
3085}
Denis Vlasenkobb929512009-04-16 10:59:40 +00003086/* Return 0: not a keyword, 1: keyword
3087 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003088static int reserved_word(o_string *word, struct parse_context *ctx)
3089{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003090# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003091 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003092 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003093 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003094# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003095 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003096
Denys Vlasenko38292b62010-09-05 14:49:40 +02003097 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003098 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003099 r = match_reserved_word(word);
3100 if (!r)
3101 return 0;
3102
3103 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003104# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003105 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3106 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003107 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003108 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003109# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003110 if (r->flag == 0) { /* '!' */
3111 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003112 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00003113 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00003114 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003115 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003116 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003117 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003118 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003119 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003120
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003121 old = xmalloc(sizeof(*old));
3122 debug_printf_parse("push stack %p\n", old);
3123 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003124 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003125 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003126 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003127 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003128 ctx->ctx_res_w = RES_SNTX;
3129 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003130 } else {
3131 /* "{...} fi" is ok. "{...} if" is not
3132 * Example:
3133 * if { echo foo; } then { echo bar; } fi */
3134 if (ctx->command->group)
3135 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003136 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00003137
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003138 ctx->ctx_res_w = r->res;
3139 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003140 word->o_assignment = r->assignment_flag;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003141 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
Denis Vlasenkobb929512009-04-16 10:59:40 +00003142
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003143 if (ctx->old_flag & FLAG_END) {
3144 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00003145
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003146 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003147 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003148 old = ctx->stack;
3149 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003150 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003151# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003152 o_addstr(&old->as_string, ctx->as_string.data);
3153 o_free_unsafe(&ctx->as_string);
3154 old->command->group_as_string = xstrdup(old->as_string.data);
3155 debug_printf_parse("pop, remembering as:'%s'\n",
3156 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003157# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003158 *ctx = *old; /* physical copy */
3159 free(old);
3160 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003161 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003162}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003163#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003164
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003165/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003166 * Normal return is 0. Syntax errors return 1.
3167 * Note: on return, word is reset, but not o_free'd!
3168 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003169static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003170{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003171 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003172
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003173 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003174 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003175 debug_printf_parse("done_word return 0: true null, ignored\n");
3176 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003177 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003178
Eric Andersen25f27032001-04-26 23:22:31 +00003179 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003180 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3181 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003182 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3183 * "2.7 Redirection
3184 * ...the word that follows the redirection operator
3185 * shall be subjected to tilde expansion, parameter expansion,
3186 * command substitution, arithmetic expansion, and quote
3187 * removal. Pathname expansion shall not be performed
3188 * on the word by a non-interactive shell; an interactive
3189 * shell may perform it, but shall do so only when
3190 * the expansion would result in one word."
3191 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003192 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003193 /* Cater for >\file case:
3194 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3195 * Same with heredocs:
3196 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3197 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003198 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3199 unbackslash(ctx->pending_redirect->rd_filename);
3200 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003201 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003202 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3203 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003204 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003205 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003206 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003207 } else {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003208#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003209# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003210 if (ctx->ctx_dsemicolon
3211 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3212 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003213 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003214 /* ctx->ctx_res_w = RES_MATCH; */
3215 ctx->ctx_dsemicolon = 0;
3216 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003217# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003218 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003219# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003220 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3221 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003222# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003223# if ENABLE_HUSH_CASE
3224 && ctx->ctx_res_w != RES_CASE
3225# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003226 ) {
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003227 int reserved = reserved_word(word, ctx);
3228 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3229 if (reserved) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003230 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003231 debug_printf_parse("done_word return %d\n",
3232 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003233 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003234 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003235# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003236 if (strcmp(word->data, "[[") == 0) {
3237 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3238 }
3239 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003240# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003241 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003242#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003243 if (command->group) {
3244 /* "{ echo foo; } echo bar" - bad */
3245 syntax_error_at(word->data);
3246 debug_printf_parse("done_word return 1: syntax error, "
3247 "groups and arglists don't mix\n");
3248 return 1;
3249 }
Denys Vlasenko29f9b722011-05-14 11:27:36 +02003250
3251 /* If this word wasn't an assignment, next ones definitely
3252 * can't be assignments. Even if they look like ones. */
3253 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3254 && word->o_assignment != WORD_IS_KEYWORD
3255 ) {
3256 word->o_assignment = NOT_ASSIGNMENT;
3257 } else {
3258 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3259 command->assignment_cnt++;
3260 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3261 }
3262 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3263 word->o_assignment = MAYBE_ASSIGNMENT;
3264 }
3265 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3266
Denys Vlasenko38292b62010-09-05 14:49:40 +02003267 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003268 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3269 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003270 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003271 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003272 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003273 char *p = word->data;
3274 while (p[0] == SPECIAL_VAR_SYMBOL
3275 && (p[1] & 0x7f) == '@'
3276 && p[2] == SPECIAL_VAR_SYMBOL
3277 ) {
3278 p += 3;
3279 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003280 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003281 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003282 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003283 }
Eric Andersen25f27032001-04-26 23:22:31 +00003284
Denis Vlasenko06810332007-05-21 23:30:54 +00003285#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003286 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003287 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003288 || !is_well_formed_var_name(command->argv[0], '\0')
3289 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003290 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003291 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003292 return 1;
3293 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003294 /* Force FOR to have just one word (variable name) */
3295 /* NB: basically, this makes hush see "for v in ..."
3296 * syntax as if it is "for v; in ...". FOR and IN become
3297 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003298 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003299 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003300#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003301#if ENABLE_HUSH_CASE
3302 /* Force CASE to have just one word */
3303 if (ctx->ctx_res_w == RES_CASE) {
3304 done_pipe(ctx, PIPE_SEQ);
3305 }
3306#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003307
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003308 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003309
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003310 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003311 return 0;
3312}
3313
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003314
3315/* Peek ahead in the input to find out if we have a "&n" construct,
3316 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003317 * Return:
3318 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3319 * REDIRFD_SYNTAX_ERR if syntax error,
3320 * REDIRFD_TO_FILE if no & was seen,
3321 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003322 */
3323#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003324#define parse_redir_right_fd(as_string, input) \
3325 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003326#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003327static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003328{
3329 int ch, d, ok;
3330
3331 ch = i_peek(input);
3332 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003333 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003334
3335 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003336 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003337 ch = i_peek(input);
3338 if (ch == '-') {
3339 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003340 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003341 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003342 }
3343 d = 0;
3344 ok = 0;
3345 while (ch != EOF && isdigit(ch)) {
3346 d = d*10 + (ch-'0');
3347 ok = 1;
3348 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003349 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003350 ch = i_peek(input);
3351 }
3352 if (ok) return d;
3353
3354//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3355
3356 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003357 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003358}
3359
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003360/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003361 */
3362static int parse_redirect(struct parse_context *ctx,
3363 int fd,
3364 redir_type style,
3365 struct in_str *input)
3366{
3367 struct command *command = ctx->command;
3368 struct redir_struct *redir;
3369 struct redir_struct **redirp;
3370 int dup_num;
3371
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003372 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003373 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003374 /* Check for a '>&1' type redirect */
3375 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3376 if (dup_num == REDIRFD_SYNTAX_ERR)
3377 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003378 } else {
3379 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003380 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003381 if (dup_num) { /* <<-... */
3382 ch = i_getch(input);
3383 nommu_addchr(&ctx->as_string, ch);
3384 ch = i_peek(input);
3385 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003386 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003387
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003388 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003389 int ch = i_peek(input);
3390 if (ch == '|') {
3391 /* >|FILE redirect ("clobbering" >).
3392 * Since we do not support "set -o noclobber" yet,
3393 * >| and > are the same for now. Just eat |.
3394 */
3395 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003396 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003397 }
3398 }
3399
3400 /* Create a new redir_struct and append it to the linked list */
3401 redirp = &command->redirects;
3402 while ((redir = *redirp) != NULL) {
3403 redirp = &(redir->next);
3404 }
3405 *redirp = redir = xzalloc(sizeof(*redir));
3406 /* redir->next = NULL; */
3407 /* redir->rd_filename = NULL; */
3408 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003409 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003410
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003411 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3412 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003413
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003414 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003415 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003416 /* Erik had a check here that the file descriptor in question
3417 * is legit; I postpone that to "run time"
3418 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003419 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3420 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003421 } else {
3422 /* Set ctx->pending_redirect, so we know what to do at the
3423 * end of the next parsed word. */
3424 ctx->pending_redirect = redir;
3425 }
3426 return 0;
3427}
3428
Eric Andersen25f27032001-04-26 23:22:31 +00003429/* If a redirect is immediately preceded by a number, that number is
3430 * supposed to tell which file descriptor to redirect. This routine
3431 * looks for such preceding numbers. In an ideal world this routine
3432 * needs to handle all the following classes of redirects...
3433 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3434 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3435 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3436 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003437 *
3438 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3439 * "2.7 Redirection
3440 * ... If n is quoted, the number shall not be recognized as part of
3441 * the redirection expression. For example:
3442 * echo \2>a
3443 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003444 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003445 *
3446 * A -1 return means no valid number was found,
3447 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003448 */
3449static int redirect_opt_num(o_string *o)
3450{
3451 int num;
3452
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003453 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003454 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003455 num = bb_strtou(o->data, NULL, 10);
3456 if (errno || num < 0)
3457 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003458 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003459 return num;
3460}
3461
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003462#if BB_MMU
3463#define fetch_till_str(as_string, input, word, skip_tabs) \
3464 fetch_till_str(input, word, skip_tabs)
3465#endif
3466static char *fetch_till_str(o_string *as_string,
3467 struct in_str *input,
3468 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003469 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003470{
3471 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003472 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003473 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003474 int ch;
3475
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003476 goto jump_in;
Denys Vlasenkob8709032011-05-08 21:20:01 +02003477
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003478 while (1) {
3479 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003480 if (ch != EOF)
3481 nommu_addchr(as_string, ch);
3482 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003483 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3484 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003485 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3486 heredoc.data[past_EOL] = '\0';
3487 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3488 return heredoc.data;
3489 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003490 while (ch == '\n') {
3491 o_addchr(&heredoc, ch);
3492 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003493 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003494 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003495 do {
3496 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003497 if (ch != EOF)
3498 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003499 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003500 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003501 }
3502 if (ch == EOF) {
3503 o_free_unsafe(&heredoc);
3504 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003505 }
3506 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003507 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003508 if (prev == '\\' && ch == '\\')
3509 /* Correctly handle foo\\<eol> (not a line cont.) */
3510 prev = 0; /* not \ */
3511 else
3512 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003513 }
3514}
3515
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003516/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3517 * and load them all. There should be exactly heredoc_cnt of them.
3518 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003519static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3520{
3521 struct pipe *pi = ctx->list_head;
3522
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003523 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003524 int i;
3525 struct command *cmd = pi->cmds;
3526
3527 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3528 pi->num_cmds,
3529 cmd->argv ? cmd->argv[0] : "NONE");
3530 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003531 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003532
3533 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3534 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003535 while (redir) {
3536 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003537 char *p;
3538
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003539 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003540 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003541 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003542 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003543 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003544 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003545 return 1;
3546 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003547 free(redir->rd_filename);
3548 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003549 heredoc_cnt--;
3550 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003551 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003552 }
3553 cmd++;
3554 }
3555 pi = pi->next;
3556 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003557#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003558 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003559 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003560 bb_error_msg_and_die("heredoc BUG 2");
3561#endif
3562 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003563}
3564
3565
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003566static int run_list(struct pipe *pi);
3567#if BB_MMU
3568#define parse_stream(pstring, input, end_trigger) \
3569 parse_stream(input, end_trigger)
3570#endif
3571static struct pipe *parse_stream(char **pstring,
3572 struct in_str *input,
3573 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003574
Eric Andersen25f27032001-04-26 23:22:31 +00003575
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003576#if !ENABLE_HUSH_FUNCTIONS
3577#define parse_group(dest, ctx, input, ch) \
3578 parse_group(ctx, input, ch)
3579#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003580static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003581 struct in_str *input, int ch)
3582{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003583 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003584 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003585 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003586 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003587 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003588 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003589
3590 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003591#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003592 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003593 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003594 if (done_word(dest, ctx))
3595 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003596 if (!command->argv)
3597 goto skip; /* (... */
3598 if (command->argv[1]) { /* word word ... (... */
3599 syntax_error_unexpected_ch('(');
3600 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003601 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003602 /* it is "word(..." or "word (..." */
3603 do
3604 ch = i_getch(input);
3605 while (ch == ' ' || ch == '\t');
3606 if (ch != ')') {
3607 syntax_error_unexpected_ch(ch);
3608 return 1;
3609 }
3610 nommu_addchr(&ctx->as_string, ch);
3611 do
3612 ch = i_getch(input);
3613 while (ch == ' ' || ch == '\t' || ch == '\n');
3614 if (ch != '{') {
3615 syntax_error_unexpected_ch(ch);
3616 return 1;
3617 }
3618 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003619 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003620 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003621 }
3622#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003623
3624#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003625 if (command->argv /* word [word]{... */
3626 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003627 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003628 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003629 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003630 debug_printf_parse("parse_group return 1: "
3631 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003632 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003633 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003634#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003635
3636#if ENABLE_HUSH_FUNCTIONS
3637 skip:
3638#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003639 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003640 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003641 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003642 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003643 } else {
3644 /* bash does not allow "{echo...", requires whitespace */
3645 ch = i_getch(input);
3646 if (ch != ' ' && ch != '\t' && ch != '\n') {
3647 syntax_error_unexpected_ch(ch);
3648 return 1;
3649 }
3650 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003651 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003652
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003653 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003654#if BB_MMU
3655# define as_string NULL
3656#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003657 char *as_string = NULL;
3658#endif
3659 pipe_list = parse_stream(&as_string, input, endch);
3660#if !BB_MMU
3661 if (as_string)
3662 o_addstr(&ctx->as_string, as_string);
3663#endif
3664 /* empty ()/{} or parse error? */
3665 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003666 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003667 if (!BB_MMU)
3668 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003669 debug_printf_parse("parse_group return 1: "
3670 "parse_stream returned %p\n", pipe_list);
3671 return 1;
3672 }
3673 command->group = pipe_list;
3674#if !BB_MMU
3675 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3676 command->group_as_string = as_string;
3677 debug_printf_parse("end of group, remembering as:'%s'\n",
3678 command->group_as_string);
3679#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003680#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003681 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003682 debug_printf_parse("parse_group return 0\n");
3683 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003684 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003685}
3686
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003687#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003688/* Subroutines for copying $(...) and `...` things */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003689static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003690/* '...' */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003691static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003692{
3693 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003694 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003695 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003696 syntax_error_unterm_ch('\'');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003697 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003698 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003699 if (ch == '\'')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003700 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003701 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003702 }
3703}
3704/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003705static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003706{
3707 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003708 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003709 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003710 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003711 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003712 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003713 if (ch == '"')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003714 return 1;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003715 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003716 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003717 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003718 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003719 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003720 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003721 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3722 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003723 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003724 continue;
3725 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003726 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003727 }
3728}
3729/* Process `cmd` - copy contents until "`" is seen. Complicated by
3730 * \` quoting.
3731 * "Within the backquoted style of command substitution, backslash
3732 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3733 * The search for the matching backquote shall be satisfied by the first
3734 * backquote found without a preceding backslash; during this search,
3735 * if a non-escaped backquote is encountered within a shell comment,
3736 * a here-document, an embedded command substitution of the $(command)
3737 * form, or a quoted string, undefined results occur. A single-quoted
3738 * or double-quoted string that begins, but does not end, within the
3739 * "`...`" sequence produces undefined results."
3740 * Example Output
3741 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3742 */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003743static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003744{
3745 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003746 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003747 if (ch == '`')
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003748 return 1;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003749 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003750 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3751 ch = i_getch(input);
3752 if (ch != '`'
3753 && ch != '$'
3754 && ch != '\\'
3755 && (!in_dquote || ch != '"')
3756 ) {
3757 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003758 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003759 }
3760 if (ch == EOF) {
3761 syntax_error_unterm_ch('`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003762 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003763 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003764 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003765 }
3766}
3767/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3768 * quoting and nested ()s.
3769 * "With the $(command) style of command substitution, all characters
3770 * following the open parenthesis to the matching closing parenthesis
3771 * constitute the command. Any valid shell script can be used for command,
3772 * except a script consisting solely of redirections which produces
3773 * unspecified results."
3774 * Example Output
3775 * echo $(echo '(TEST)' BEST) (TEST) BEST
3776 * echo $(echo 'TEST)' BEST) TEST) BEST
3777 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003778 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003779 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003780 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003781 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3782 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003783 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003784#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003785static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003786{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003787 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003788 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003789# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003790 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003791# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003792 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3793
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003794 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003795 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003796 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003797 syntax_error_unterm_ch(end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003798 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003799 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003800 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003801 if (!dbl)
3802 break;
3803 /* we look for closing )) of $((EXPR)) */
3804 if (i_peek(input) == end_ch) {
3805 i_getch(input); /* eat second ')' */
3806 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003807 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003808 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003809 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003810 if (ch == '(' || ch == '{') {
3811 ch = (ch == '(' ? ')' : '}');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003812 if (!add_till_closing_bracket(dest, input, ch))
3813 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003814 o_addchr(dest, ch);
3815 continue;
3816 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003817 if (ch == '\'') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003818 if (!add_till_single_quote(dest, input))
3819 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003820 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003821 continue;
3822 }
3823 if (ch == '"') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003824 if (!add_till_double_quote(dest, input))
3825 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003826 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003827 continue;
3828 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003829 if (ch == '`') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003830 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3831 return 0;
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003832 o_addchr(dest, ch);
3833 continue;
3834 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003835 if (ch == '\\') {
3836 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003837 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003838 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003839 syntax_error_unterm_ch(')');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003840 return 0;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003841 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003842 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003843 continue;
3844 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003845 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003846 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003847}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003848#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003849
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003850/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003851#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003852#define parse_dollar(as_string, dest, input, quote_mask) \
3853 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003854#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003855#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003856static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003857 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003858 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003859{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003860 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003861
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003862 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003863 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003864 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003865 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003866 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003867 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003868 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003869 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003870 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003871 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003872 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003873 if (!isalnum(ch) && ch != '_')
3874 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003875 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003876 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003877 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003878 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003879 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003880 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003881 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003882 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003883 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003884 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003885 o_addchr(dest, ch | quote_mask);
3886 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003887 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003888 case '$': /* pid */
3889 case '!': /* last bg pid */
3890 case '?': /* last exit code */
3891 case '#': /* number of args */
3892 case '*': /* args */
3893 case '@': /* args */
3894 goto make_one_char_var;
3895 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003896 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3897
Denys Vlasenko74369502010-05-21 19:52:01 +02003898 ch = i_getch(input); /* eat '{' */
3899 nommu_addchr(as_string, ch);
3900
3901 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003902 /* It should be ${?}, or ${#var},
3903 * or even ${?+subst} - operator acting on a special variable,
3904 * or the beginning of variable name.
3905 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003906 if (ch == EOF
3907 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3908 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003909 bad_dollar_syntax:
3910 syntax_error_unterm_str("${name}");
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003911 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3912 return 0;
Denys Vlasenko74369502010-05-21 19:52:01 +02003913 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003914 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003915 ch |= quote_mask;
3916
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003917 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003918 * However, this regresses some of our testsuite cases
3919 * which check invalid constructs like ${%}.
3920 * Oh well... let's check that the var name part is fine... */
3921
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003922 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003923 unsigned pos;
3924
Denys Vlasenko74369502010-05-21 19:52:01 +02003925 o_addchr(dest, ch);
3926 debug_printf_parse(": '%c'\n", ch);
3927
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003928 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003929 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003930 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003931 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003932
Denys Vlasenko74369502010-05-21 19:52:01 +02003933 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003934 unsigned end_ch;
3935 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003936 /* handle parameter expansions
3937 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3938 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003939 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003940 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003941
3942 /* Eat everything until closing '}' (or ':') */
3943 end_ch = '}';
3944 if (ENABLE_HUSH_BASH_COMPAT
3945 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003946 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003947 ) {
3948 /* It's ${var:N[:M]} thing */
3949 end_ch = '}' * 0x100 + ':';
3950 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003951 if (ENABLE_HUSH_BASH_COMPAT
3952 && ch == '/'
3953 ) {
3954 /* It's ${var/[/]pattern[/repl]} thing */
3955 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3956 i_getch(input);
3957 nommu_addchr(as_string, '/');
3958 ch = '\\';
3959 }
3960 end_ch = '}' * 0x100 + '/';
3961 }
3962 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003963 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003964 if (!BB_MMU)
3965 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003966#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003967 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01003968 if (last_ch == 0) /* error? */
3969 return 0;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003970#else
3971#error Simple code to only allow ${var} is not implemented
3972#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003973 if (as_string) {
3974 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003975 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003976 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003977
3978 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3979 /* close the first block: */
3980 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003981 /* while parsing N from ${var:N[:M]}
3982 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003983 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003984 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003985 end_ch = '}';
3986 goto again;
3987 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003988 /* got '}' */
3989 if (end_ch == '}' * 0x100 + ':') {
3990 /* it's ${var:N} - emulate :999999999 */
3991 o_addstr(dest, "999999999");
3992 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003993 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003994 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003995 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003996 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003997 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3998 break;
3999 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004000#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004001 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004002 unsigned pos;
4003
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004004 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004005 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004006# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004007 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004008 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004009 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004010 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4011 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004012 if (!BB_MMU)
4013 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004014 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4015 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004016 if (as_string) {
4017 o_addstr(as_string, dest->data + pos);
4018 o_addchr(as_string, ')');
4019 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004020 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004021 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004022 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004023 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004024# endif
4025# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004026 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4027 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004028 if (!BB_MMU)
4029 pos = dest->length;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004030 if (!add_till_closing_bracket(dest, input, ')'))
4031 return 0; /* error */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004032 if (as_string) {
4033 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004034 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004035 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004036 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004037# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004038 break;
4039 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004040#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004041 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004042 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004043 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004044 ch = i_peek(input);
4045 if (isalnum(ch)) { /* it's $_name or $_123 */
4046 ch = '_';
4047 goto make_var;
4048 }
4049 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02004050 /* TODO: $_ and $-: */
4051 /* $_ Shell or shell script name; or last argument of last command
4052 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4053 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004054 /* $- Option flags set by set builtin or shell options (-i etc) */
4055 default:
4056 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004057 }
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004058 debug_printf_parse("parse_dollar return 1 (ok)\n");
4059 return 1;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004060#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00004061}
4062
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004063#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004064# if ENABLE_HUSH_BASH_COMPAT
4065#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4066 encode_string(dest, input, dquote_end, process_bkslash)
4067# else
4068/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4069#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4070 encode_string(dest, input, dquote_end)
4071# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004072#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004073
4074#else /* !MMU */
4075
4076# if ENABLE_HUSH_BASH_COMPAT
4077/* all parameters are needed, no macro tricks */
4078# else
4079#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4080 encode_string(as_string, dest, input, dquote_end)
4081# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004082#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004083static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004084 o_string *dest,
4085 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02004086 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004087 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004088{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004089#if !ENABLE_HUSH_BASH_COMPAT
4090 const int process_bkslash = 1;
4091#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004092 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004093 int next;
4094
4095 again:
4096 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004097 if (ch != EOF)
4098 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004099 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004100 debug_printf_parse("encode_string return 1 (ok)\n");
4101 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004102 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004103 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004104 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004105 syntax_error_unterm_ch('"');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004106 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004107 }
4108 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004109 if (ch != '\n') {
4110 next = i_peek(input);
4111 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004112 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004113 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004114 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004115 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004116 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004117 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004118 }
4119 /* bash:
4120 * "The backslash retains its special meaning [in "..."]
4121 * only when followed by one of the following characters:
4122 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004123 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004124 * NB: in (unquoted) heredoc, above does not apply to ",
4125 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004126 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004127 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004128 ch = i_getch(input); /* eat next */
4129 if (ch == '\n')
4130 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004131 } /* else: ch remains == '\\', and we double it below: */
4132 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02004133 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004134 goto again;
4135 }
4136 if (ch == '$') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004137 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4138 debug_printf_parse("encode_string return 0: "
4139 "parse_dollar returned 0 (error)\n");
4140 return 0;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004141 }
4142 goto again;
4143 }
4144#if ENABLE_HUSH_TICK
4145 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004146 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004147 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4148 o_addchr(dest, 0x80 | '`');
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004149 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4150 return 0; /* error */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004151 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4152 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004153 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004154 }
4155#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004156 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004157 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02004158#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004159}
4160
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004161/*
4162 * Scan input until EOF or end_trigger char.
4163 * Return a list of pipes to execute, or NULL on EOF
4164 * or if end_trigger character is met.
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004165 * On syntax error, exit if shell is not interactive,
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004166 * reset parsing machinery and start parsing anew,
4167 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004168 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004169static struct pipe *parse_stream(char **pstring,
4170 struct in_str *input,
4171 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004172{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004173 struct parse_context ctx;
4174 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004175 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004176
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004177 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004178 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004179 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004180 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004181 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004182 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004183
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004184 /* If very first arg is "" or '', dest.data may end up NULL.
4185 * Preventing this: */
4186 o_addchr(&dest, '\0');
4187 dest.length = 0;
4188
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004189 /* We used to separate words on $IFS here. This was wrong.
4190 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004191 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004192 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004193
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004194 if (MAYBE_ASSIGNMENT != 0)
4195 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004196 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004197 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004198 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004199 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004200 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004201 int ch;
4202 int next;
4203 int redir_fd;
4204 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004205
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004206 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004207 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004208 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004209 if (ch == EOF) {
4210 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004211
4212 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004213 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004214 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004215 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004216 /* end_trigger == '}' case errors out earlier,
4217 * checking only ')' */
4218 if (end_trigger == ')') {
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004219 syntax_error_unterm_ch('(');
4220 goto parse_error;
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004221 }
4222
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004223 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004224 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004225 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004226 o_free(&dest);
4227 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004228 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004229 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004230 /* (this makes bare "&" cmd a no-op.
4231 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004232 if (pi->num_cmds == 0
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004233 IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004234 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004235 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004236 pi = NULL;
4237 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004238#if !BB_MMU
4239 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4240 if (pstring)
4241 *pstring = ctx.as_string.data;
4242 else
4243 o_free_unsafe(&ctx.as_string);
4244#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004245 debug_leave();
4246 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004247 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004248 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004249 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004250
4251 next = '\0';
4252 if (ch != '\n')
4253 next = i_peek(input);
4254
4255 is_special = "{}<>;&|()#'" /* special outside of "str" */
4256 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4257 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004258 if (ctx.command->argv /* word [word]{... - non-special */
4259 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004260 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004261 || (next != ';' /* }; - special */
4262 && next != ')' /* }) - special */
4263 && next != '&' /* }& and }&& ... - special */
4264 && next != '|' /* }|| ... - special */
4265 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004266 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004267 ) {
4268 /* They are not special, skip "{}" */
4269 is_special += 2;
4270 }
4271 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004272 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004273
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004274 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004275 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004276 o_addQchr(&dest, ch);
4277 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4278 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004279 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004280 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004281 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004282 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004283 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004284 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004285 continue;
4286 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004287
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004288 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004289 if (done_word(&dest, &ctx)) {
4290 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004291 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004292 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004293 /* Is this a case when newline is simply ignored?
4294 * Some examples:
4295 * "cmd | <newline> cmd ..."
4296 * "case ... in <newline> word) ..."
4297 */
4298 if (IS_NULL_CMD(ctx.command)
4299 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004300 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004301 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004302 * Without check #1, interactive shell
4303 * ignores even bare <newline>,
4304 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004305 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004306 * ps2> _ <=== wrong, should be ps1
4307 * Without check #2, "cmd & <newline>"
4308 * is similarly mistreated.
4309 * (BTW, this makes "cmd & cmd"
4310 * and "cmd && cmd" non-orthogonal.
4311 * Really, ask yourself, why
4312 * "cmd && <newline>" doesn't start
4313 * cmd but waits for more input?
4314 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004315 */
4316 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004317 if (pi->num_cmds != 0 /* check #1 */
4318 && pi->followup != PIPE_BG /* check #2 */
4319 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004320 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004321 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004322 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004323 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004324 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004325 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4326 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004327 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004328 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004329 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004330 heredoc_cnt = 0;
4331 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004332 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004333 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004334 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004335 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004336 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004337 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004338 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004339
4340 /* "cmd}" or "cmd }..." without semicolon or &:
4341 * } is an ordinary char in this case, even inside { cmd; }
4342 * Pathological example: { ""}; } should exec "}" cmd
4343 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004344 if (ch == '}') {
4345 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4346 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004347 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004348 ) {
4349 goto ordinary_char;
4350 }
4351 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4352 goto skip_end_trigger;
4353 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004354 }
4355
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004356 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004357 && (ch != ';' || heredoc_cnt == 0)
4358#if ENABLE_HUSH_CASE
4359 && (ch != ')'
4360 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004361 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004362 )
4363#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004364 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004365 if (heredoc_cnt) {
4366 /* This is technically valid:
4367 * { cat <<HERE; }; echo Ok
4368 * heredoc
4369 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004370 * HERE
4371 * but we don't support this.
4372 * We require heredoc to be in enclosing {}/(),
4373 * if any.
4374 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004375 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004376 goto parse_error;
4377 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004378 if (done_word(&dest, &ctx)) {
4379 goto parse_error;
4380 }
4381 done_pipe(&ctx, PIPE_SEQ);
4382 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004383 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenko240c2552009-04-03 03:45:05 +00004384 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004385 if (!HAS_KEYWORDS
Denys Vlasenko60cb48c2013-01-14 15:57:44 +01004386 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004387 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004388 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004389#if !BB_MMU
4390 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4391 if (pstring)
4392 *pstring = ctx.as_string.data;
4393 else
4394 o_free_unsafe(&ctx.as_string);
4395#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004396 debug_leave();
4397 debug_printf_parse("parse_stream return %p: "
4398 "end_trigger char found\n",
4399 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004400 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004401 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004402 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004403 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004404 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004405 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004406
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004407 /* Catch <, > before deciding whether this word is
4408 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4409 switch (ch) {
4410 case '>':
4411 redir_fd = redirect_opt_num(&dest);
4412 if (done_word(&dest, &ctx)) {
4413 goto parse_error;
4414 }
4415 redir_style = REDIRECT_OVERWRITE;
4416 if (next == '>') {
4417 redir_style = REDIRECT_APPEND;
4418 ch = i_getch(input);
4419 nommu_addchr(&ctx.as_string, ch);
4420 }
4421#if 0
4422 else if (next == '(') {
4423 syntax_error(">(process) not supported");
4424 goto parse_error;
4425 }
4426#endif
4427 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4428 goto parse_error;
4429 continue; /* back to top of while (1) */
4430 case '<':
4431 redir_fd = redirect_opt_num(&dest);
4432 if (done_word(&dest, &ctx)) {
4433 goto parse_error;
4434 }
4435 redir_style = REDIRECT_INPUT;
4436 if (next == '<') {
4437 redir_style = REDIRECT_HEREDOC;
4438 heredoc_cnt++;
4439 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4440 ch = i_getch(input);
4441 nommu_addchr(&ctx.as_string, ch);
4442 } else if (next == '>') {
4443 redir_style = REDIRECT_IO;
4444 ch = i_getch(input);
4445 nommu_addchr(&ctx.as_string, ch);
4446 }
4447#if 0
4448 else if (next == '(') {
4449 syntax_error("<(process) not supported");
4450 goto parse_error;
4451 }
4452#endif
4453 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4454 goto parse_error;
4455 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004456 case '#':
4457 if (dest.length == 0 && !dest.has_quoted_part) {
4458 /* skip "#comment" */
4459 while (1) {
4460 ch = i_peek(input);
4461 if (ch == EOF || ch == '\n')
4462 break;
4463 i_getch(input);
4464 /* note: we do not add it to &ctx.as_string */
4465 }
4466 nommu_addchr(&ctx.as_string, '\n');
4467 continue; /* back to top of while (1) */
4468 }
4469 break;
4470 case '\\':
4471 if (next == '\n') {
4472 /* It's "\<newline>" */
4473#if !BB_MMU
4474 /* Remove trailing '\' from ctx.as_string */
4475 ctx.as_string.data[--ctx.as_string.length] = '\0';
4476#endif
4477 ch = i_getch(input); /* eat it */
4478 continue; /* back to top of while (1) */
4479 }
4480 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004481 }
4482
4483 if (dest.o_assignment == MAYBE_ASSIGNMENT
4484 /* check that we are not in word in "a=1 2>word b=1": */
4485 && !ctx.pending_redirect
4486 ) {
4487 /* ch is a special char and thus this word
4488 * cannot be an assignment */
4489 dest.o_assignment = NOT_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004490 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004491 }
4492
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004493 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4494
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004495 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004496 case '#': /* non-comment #: "echo a#b" etc */
4497 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004498 break;
4499 case '\\':
4500 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004501 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004502 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004503 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004504 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004505 /* note: ch != '\n' (that case does not reach this place) */
4506 o_addchr(&dest, '\\');
4507 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4508 o_addchr(&dest, ch);
4509 nommu_addchr(&ctx.as_string, ch);
4510 /* Example: echo Hello \2>file
4511 * we need to know that word 2 is quoted */
4512 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004513 break;
4514 case '$':
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004515 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004516 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004517 "parse_dollar returned 0 (error)\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004518 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004519 }
Eric Andersen25f27032001-04-26 23:22:31 +00004520 break;
4521 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004522 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004523 if (next == '\'' && !ctx.pending_redirect) {
4524 insert_empty_quoted_str_marker:
4525 nommu_addchr(&ctx.as_string, next);
4526 i_getch(input); /* eat second ' */
4527 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4528 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4529 } else {
4530 while (1) {
4531 ch = i_getch(input);
4532 if (ch == EOF) {
4533 syntax_error_unterm_ch('\'');
4534 goto parse_error;
4535 }
4536 nommu_addchr(&ctx.as_string, ch);
4537 if (ch == '\'')
4538 break;
4539 o_addqchr(&dest, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004540 }
Eric Andersen25f27032001-04-26 23:22:31 +00004541 }
Eric Andersen25f27032001-04-26 23:22:31 +00004542 break;
4543 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004544 dest.has_quoted_part = 1;
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004545 if (next == '"' && !ctx.pending_redirect)
4546 goto insert_empty_quoted_str_marker;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004547 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004548 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004549 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004550 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004551 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004552 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004553#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004554 case '`': {
Denys Vlasenko60a94142011-05-13 20:57:01 +02004555 USE_FOR_NOMMU(unsigned pos;)
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004556
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004557 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4558 o_addchr(&dest, '`');
Denys Vlasenko60a94142011-05-13 20:57:01 +02004559 USE_FOR_NOMMU(pos = dest.length;)
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004560 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4561 goto parse_error;
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004562# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004563 o_addstr(&ctx.as_string, dest.data + pos);
4564 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004565# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004566 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4567 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004568 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004569 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004570#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004571 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004572#if ENABLE_HUSH_CASE
4573 case_semi:
4574#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004575 if (done_word(&dest, &ctx)) {
4576 goto parse_error;
4577 }
4578 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004579#if ENABLE_HUSH_CASE
4580 /* Eat multiple semicolons, detect
4581 * whether it means something special */
4582 while (1) {
4583 ch = i_peek(input);
4584 if (ch != ';')
4585 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004586 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004587 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004588 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004589 ctx.ctx_dsemicolon = 1;
4590 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004591 break;
4592 }
4593 }
4594#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004595 new_cmd:
4596 /* We just finished a cmd. New one may start
4597 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004598 dest.o_assignment = MAYBE_ASSIGNMENT;
Denys Vlasenko29f9b722011-05-14 11:27:36 +02004599 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
Eric Andersen25f27032001-04-26 23:22:31 +00004600 break;
4601 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004602 if (done_word(&dest, &ctx)) {
4603 goto parse_error;
4604 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004605 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004606 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004607 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004608 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004609 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004610 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004611 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004612 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004613 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004614 if (done_word(&dest, &ctx)) {
4615 goto parse_error;
4616 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004617#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004618 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004619 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004620#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004621 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004622 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004623 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004624 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004625 } else {
4626 /* we could pick up a file descriptor choice here
4627 * with redirect_opt_num(), but bash doesn't do it.
4628 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004629 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004630#if !BB_MMU
4631 o_reset_to_empty_unquoted(&ctx.as_string);
4632#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004633 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004634 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004635 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004636#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004637 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004638 if (ctx.ctx_res_w == RES_MATCH
4639 && ctx.command->argv == NULL /* not (word|(... */
4640 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004641 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004642 ) {
4643 continue;
4644 }
4645#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004646 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004647 if (parse_group(&dest, &ctx, input, ch) != 0) {
4648 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004649 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004650 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004651 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004652#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004653 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004654 goto case_semi;
4655#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004656 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004657 /* proper use of this character is caught by end_trigger:
4658 * if we see {, we call parse_group(..., end_trigger='}')
4659 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004660 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004661 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004662 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004663 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004664 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004665 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004666 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004667
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004668 parse_error:
4669 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004670 struct parse_context *pctx;
4671 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004672
4673 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004674 * Sample for finding leaks on syntax error recovery path.
4675 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004676 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004677 * Samples to catch leaks at execution:
4678 * while if (true | {true;}); then echo ok; fi; do break; done
4679 * 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 +00004680 */
4681 pctx = &ctx;
4682 do {
4683 /* Update pipe/command counts,
4684 * otherwise freeing may miss some */
4685 done_pipe(pctx, PIPE_SEQ);
4686 debug_printf_clean("freeing list %p from ctx %p\n",
4687 pctx->list_head, pctx);
4688 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004689 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004690 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004691#if !BB_MMU
4692 o_free_unsafe(&pctx->as_string);
4693#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004694 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004695 if (pctx != &ctx) {
4696 free(pctx);
4697 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004698 IF_HAS_KEYWORDS(pctx = p2;)
4699 } while (HAS_KEYWORDS && pctx);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004700
Denys Vlasenkoa439fa92011-03-30 19:11:46 +02004701 o_free(&dest);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004702 G.last_exitcode = 1;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004703#if !BB_MMU
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004704 if (pstring)
4705 *pstring = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004706#endif
Denys Vlasenkocecbc982011-03-30 18:54:52 +02004707 debug_leave();
4708 return ERR_PTR;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004709 }
Eric Andersen25f27032001-04-26 23:22:31 +00004710}
4711
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004712
4713/*** Execution routines ***/
4714
4715/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004716#if !ENABLE_HUSH_BASH_COMPAT
4717/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4718#define expand_string_to_string(str, do_unbackslash) \
4719 expand_string_to_string(str)
4720#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004721static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004722#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004723static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004724#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004725
4726/* expand_strvec_to_strvec() takes a list of strings, expands
4727 * all variable references within and returns a pointer to
4728 * a list of expanded strings, possibly with larger number
4729 * of strings. (Think VAR="a b"; echo $VAR).
4730 * This new list is allocated as a single malloc block.
4731 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004732 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004733 * Caller can deallocate entire list by single free(list). */
4734
Denys Vlasenko238081f2010-10-03 14:26:26 +02004735/* A horde of its helpers come first: */
4736
4737static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4738{
4739 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004740 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004741
Denys Vlasenko9e800222010-10-03 14:28:04 +02004742#if ENABLE_HUSH_BRACE_EXPANSION
4743 if (c == '{' || c == '}') {
4744 /* { -> \{, } -> \} */
4745 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004746 /* And now we want to add { or } and continue:
4747 * o_addchr(o, c);
4748 * continue;
4749 * luckily, just falling throught achieves this.
4750 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004751 }
4752#endif
4753 o_addchr(o, c);
4754 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004755 /* \z -> \\\z; \<eol> -> \\<eol> */
4756 o_addchr(o, '\\');
4757 if (len) {
4758 len--;
4759 o_addchr(o, '\\');
4760 o_addchr(o, *str++);
4761 }
4762 }
4763 }
4764}
4765
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004766/* Store given string, finalizing the word and starting new one whenever
4767 * we encounter IFS char(s). This is used for expanding variable values.
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004768 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4769 * Return in *ended_with_ifs:
4770 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4771 */
4772static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004773{
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004774 int last_is_ifs = 0;
4775
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004776 while (1) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004777 int word_len;
4778
4779 if (!*str) /* EOL - do not finalize word */
4780 break;
4781 word_len = strcspn(str, G.ifs);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004782 if (word_len) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004783 /* We have WORD_LEN leading non-IFS chars */
Denys Vlasenko238081f2010-10-03 14:26:26 +02004784 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004785 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004786 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004787 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004788 * Example: "v='\*'; echo b$v" prints "b\*"
4789 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004790 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004791 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004792 /*/ Why can't we do it easier? */
4793 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4794 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4795 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004796 last_is_ifs = 0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004797 str += word_len;
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004798 if (!*str) /* EOL - do not finalize word */
4799 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004800 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004801
4802 /* We know str here points to at least one IFS char */
4803 last_is_ifs = 1;
4804 str += strspn(str, G.ifs); /* skip IFS chars */
4805 if (!*str) /* EOL - do not finalize word */
4806 break;
4807
4808 /* Start new word... but not always! */
4809 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004810 if (output->has_quoted_part
4811 /* Case "v=' a'; echo $v":
4812 * here nothing precedes the space in $v expansion,
4813 * therefore we should not finish the word
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004814 * (IOW: if there *is* word to finalize, only then do it):
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004815 */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004816 || (n > 0 && output->data[output->length - 1])
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004817 ) {
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02004818 o_addchr(output, '\0');
4819 debug_print_list("expand_on_ifs", output, n);
4820 n = o_save_ptr(output, n);
4821 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004822 }
Denys Vlasenko6e42b892011-08-01 18:16:43 +02004823
4824 if (ended_with_ifs)
4825 *ended_with_ifs = last_is_ifs;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004826 debug_print_list("expand_on_ifs[1]", output, n);
4827 return n;
4828}
4829
4830/* Helper to expand $((...)) and heredoc body. These act as if
4831 * they are in double quotes, with the exception that they are not :).
4832 * Just the rules are similar: "expand only $var and `cmd`"
4833 *
4834 * Returns malloced string.
4835 * As an optimization, we return NULL if expansion is not needed.
4836 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004837#if !ENABLE_HUSH_BASH_COMPAT
4838/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4839#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4840 encode_then_expand_string(str)
4841#endif
4842static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004843{
4844 char *exp_str;
4845 struct in_str input;
4846 o_string dest = NULL_O_STRING;
4847
4848 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004849 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004850#if ENABLE_HUSH_TICK
4851 && !strchr(str, '`')
4852#endif
4853 ) {
4854 return NULL;
4855 }
4856
4857 /* We need to expand. Example:
4858 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4859 */
4860 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004861 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenko3eab24e2011-03-24 05:25:59 +01004862//TODO: error check (encode_string returns 0 on error)?
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004863 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004864 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004865 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4866 o_free_unsafe(&dest);
4867 return exp_str;
4868}
4869
4870#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004871static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004872{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004873 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004874 arith_t res;
4875 char *exp_str;
4876
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004877 math_state.lookupvar = get_local_var_value;
4878 math_state.setvar = set_local_var_from_halves;
4879 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004880 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004881 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004882 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004883 if (errmsg_p)
4884 *errmsg_p = math_state.errmsg;
4885 if (math_state.errmsg)
4886 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004887 return res;
4888}
4889#endif
4890
4891#if ENABLE_HUSH_BASH_COMPAT
4892/* ${var/[/]pattern[/repl]} helpers */
4893static char *strstr_pattern(char *val, const char *pattern, int *size)
4894{
4895 while (1) {
4896 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4897 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4898 if (end) {
4899 *size = end - val;
4900 return val;
4901 }
4902 if (*val == '\0')
4903 return NULL;
4904 /* Optimization: if "*pat" did not match the start of "string",
4905 * we know that "tring", "ring" etc will not match too:
4906 */
4907 if (pattern[0] == '*')
4908 return NULL;
4909 val++;
4910 }
4911}
4912static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4913{
4914 char *result = NULL;
4915 unsigned res_len = 0;
4916 unsigned repl_len = strlen(repl);
4917
4918 while (1) {
4919 int size;
4920 char *s = strstr_pattern(val, pattern, &size);
4921 if (!s)
4922 break;
4923
4924 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4925 memcpy(result + res_len, val, s - val);
4926 res_len += s - val;
4927 strcpy(result + res_len, repl);
4928 res_len += repl_len;
4929 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4930
4931 val = s + size;
4932 if (exp_op == '/')
4933 break;
4934 }
4935 if (val[0] && result) {
4936 result = xrealloc(result, res_len + strlen(val) + 1);
4937 strcpy(result + res_len, val);
4938 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4939 }
4940 debug_printf_varexp("result:'%s'\n", result);
4941 return result;
4942}
4943#endif
4944
4945/* Helper:
4946 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4947 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004948static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004949{
4950 const char *val = NULL;
4951 char *to_be_freed = NULL;
4952 char *p = *pp;
4953 char *var;
4954 char first_char;
4955 char exp_op;
4956 char exp_save = exp_save; /* for compiler */
4957 char *exp_saveptr; /* points to expansion operator */
4958 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004959 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004960
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004961 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004962 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004963 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004964 arg0 = arg[0];
4965 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004966 exp_op = 0;
4967
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004968 if (first_char == '#' /* ${#... */
4969 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4970 ) {
4971 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004972 var++;
4973 exp_op = 'L';
4974 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004975 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004976 if (exp_saveptr /* if 2nd char is one of expansion operators */
4977 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4978 ) {
4979 /* ${?:0}, ${#[:]%0} etc */
4980 exp_saveptr = var + 1;
4981 } else {
4982 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4983 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4984 }
4985 exp_op = exp_save = *exp_saveptr;
4986 if (exp_op) {
4987 exp_word = exp_saveptr + 1;
4988 if (exp_op == ':') {
4989 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004990//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004991 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004992 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004993 ) {
4994 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4995 exp_op = ':';
4996 exp_word--;
4997 }
4998 }
4999 *exp_saveptr = '\0';
5000 } /* else: it's not an expansion op, but bare ${var} */
5001 }
5002
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005003 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005004 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02005005 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005006 int n = xatoi_positive(var);
5007 if (n < G.global_argc)
5008 val = G.global_argv[n];
5009 /* else val remains NULL: $N with too big N */
5010 } else {
5011 switch (var[0]) {
5012 case '$': /* pid */
5013 val = utoa(G.root_pid);
5014 break;
5015 case '!': /* bg pid */
5016 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5017 break;
5018 case '?': /* exitcode */
5019 val = utoa(G.last_exitcode);
5020 break;
5021 case '#': /* argc */
5022 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5023 break;
5024 default:
5025 val = get_local_var_value(var);
5026 }
5027 }
5028
5029 /* Handle any expansions */
5030 if (exp_op == 'L') {
5031 debug_printf_expand("expand: length(%s)=", val);
5032 val = utoa(val ? strlen(val) : 0);
5033 debug_printf_expand("%s\n", val);
5034 } else if (exp_op) {
5035 if (exp_op == '%' || exp_op == '#') {
5036 /* Standard-mandated substring removal ops:
5037 * ${parameter%word} - remove smallest suffix pattern
5038 * ${parameter%%word} - remove largest suffix pattern
5039 * ${parameter#word} - remove smallest prefix pattern
5040 * ${parameter##word} - remove largest prefix pattern
5041 *
5042 * Word is expanded to produce a glob pattern.
5043 * Then var's value is matched to it and matching part removed.
5044 */
5045 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005046 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005047 char *exp_exp_word;
5048 char *loc;
5049 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02005050 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005051 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005052 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005053 if (exp_exp_word)
5054 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02005055 /* HACK ALERT. We depend here on the fact that
5056 * G.global_argv and results of utoa and get_local_var_value
5057 * are actually in writable memory:
5058 * scan_and_match momentarily stores NULs there. */
5059 t = (char*)val;
5060 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005061 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02005062 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005063 free(exp_exp_word);
5064 if (loc) { /* match was found */
5065 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005066 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005067 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02005068 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005069 }
5070 }
5071 }
5072#if ENABLE_HUSH_BASH_COMPAT
5073 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005074 /* It's ${var/[/]pattern[/repl]} thing.
5075 * Note that in encoded form it has TWO parts:
5076 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02005077 * and if // is used, it is encoded as \:
5078 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005079 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005080 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005081 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005082 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02005083 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005084 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005085 * by the usual expansion rules:
5086 * >az; >bz;
5087 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5088 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5089 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5090 * v='a bz'; echo ${v/a*z/\z} prints "z"
5091 * (note that a*z _pattern_ is never globbed!)
5092 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005093 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005094 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005095 if (!pattern)
5096 pattern = xstrdup(exp_word);
5097 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5098 *p++ = SPECIAL_VAR_SYMBOL;
5099 exp_word = p;
5100 p = strchr(p, SPECIAL_VAR_SYMBOL);
5101 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005102 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005103 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5104 /* HACK ALERT. We depend here on the fact that
5105 * G.global_argv and results of utoa and get_local_var_value
5106 * are actually in writable memory:
5107 * replace_pattern momentarily stores NULs there. */
5108 t = (char*)val;
5109 to_be_freed = replace_pattern(t,
5110 pattern,
5111 (repl ? repl : exp_word),
5112 exp_op);
5113 if (to_be_freed) /* at least one replace happened */
5114 val = to_be_freed;
5115 free(pattern);
5116 free(repl);
5117 }
5118 }
5119#endif
5120 else if (exp_op == ':') {
5121#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5122 /* It's ${var:N[:M]} bashism.
5123 * Note that in encoded form it has TWO parts:
5124 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5125 */
5126 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02005127 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005128
Denys Vlasenko063847d2010-09-15 13:33:02 +02005129 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5130 if (errmsg)
5131 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005132 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5133 *p++ = SPECIAL_VAR_SYMBOL;
5134 exp_word = p;
5135 p = strchr(p, SPECIAL_VAR_SYMBOL);
5136 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02005137 len = expand_and_evaluate_arith(exp_word, &errmsg);
5138 if (errmsg)
5139 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005140 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005141 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005142 if (beg < 0) /* bash compat */
5143 beg = 0;
5144 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005145 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02005146 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02005147 val = NULL;
5148 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005149 /* Paranoia. What if user entered 9999999999999
5150 * which fits in arith_t but not int? */
5151 if (len >= INT_MAX)
5152 len = INT_MAX;
5153 val = to_be_freed = xstrndup(val + beg, len);
5154 }
5155 debug_printf_varexp("val:'%s'\n", val);
5156 } else
5157#endif
5158 {
5159 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02005160 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005161 }
5162 } else { /* one of "-=+?" */
5163 /* Standard-mandated substitution ops:
5164 * ${var?word} - indicate error if unset
5165 * If var is unset, word (or a message indicating it is unset
5166 * if word is null) is written to standard error
5167 * and the shell exits with a non-zero exit status.
5168 * Otherwise, the value of var is substituted.
5169 * ${var-word} - use default value
5170 * If var is unset, word is substituted.
5171 * ${var=word} - assign and use default value
5172 * If var is unset, word is assigned to var.
5173 * In all cases, final value of var is substituted.
5174 * ${var+word} - use alternative value
5175 * If var is unset, null is substituted.
5176 * Otherwise, word is substituted.
5177 *
5178 * Word is subjected to tilde expansion, parameter expansion,
5179 * command substitution, and arithmetic expansion.
5180 * If word is not needed, it is not expanded.
5181 *
5182 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5183 * but also treat null var as if it is unset.
5184 */
5185 int use_word = (!val || ((exp_save == ':') && !val[0]));
5186 if (exp_op == '+')
5187 use_word = !use_word;
5188 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5189 (exp_save == ':') ? "true" : "false", use_word);
5190 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005191 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005192 if (to_be_freed)
5193 exp_word = to_be_freed;
5194 if (exp_op == '?') {
5195 /* mimic bash message */
5196 die_if_script("%s: %s",
5197 var,
5198 exp_word[0] ? exp_word : "parameter null or not set"
5199 );
5200//TODO: how interactive bash aborts expansion mid-command?
5201 } else {
5202 val = exp_word;
5203 }
5204
5205 if (exp_op == '=') {
5206 /* ${var=[word]} or ${var:=[word]} */
5207 if (isdigit(var[0]) || var[0] == '#') {
5208 /* mimic bash message */
5209 die_if_script("$%s: cannot assign in this way", var);
5210 val = NULL;
5211 } else {
5212 char *new_var = xasprintf("%s=%s", var, val);
5213 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5214 }
5215 }
5216 }
5217 } /* one of "-=+?" */
5218
5219 *exp_saveptr = exp_save;
5220 } /* if (exp_op) */
5221
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005222 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005223
5224 *pp = p;
5225 *to_be_freed_pp = to_be_freed;
5226 return val;
5227}
5228
5229/* Expand all variable references in given string, adding words to list[]
5230 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5231 * to be filled). This routine is extremely tricky: has to deal with
5232 * variables/parameters with whitespace, $* and $@, and constructs like
5233 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005234static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005235{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005236 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005237 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005238 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005239 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005240 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005241 char *p;
5242
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005243 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5244 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005245 debug_print_list("expand_vars_to_list", output, n);
5246 n = o_save_ptr(output, n);
5247 debug_print_list("expand_vars_to_list[0]", output, n);
5248
5249 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5250 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005251 char *to_be_freed = NULL;
5252 const char *val = NULL;
5253#if ENABLE_HUSH_TICK
5254 o_string subst_result = NULL_O_STRING;
5255#endif
5256#if ENABLE_SH_MATH_SUPPORT
5257 char arith_buf[sizeof(arith_t)*3 + 2];
5258#endif
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005259
5260 if (ended_in_ifs) {
5261 o_addchr(output, '\0');
5262 n = o_save_ptr(output, n);
5263 ended_in_ifs = 0;
5264 }
5265
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005266 o_addblock(output, arg, p - arg);
5267 debug_print_list("expand_vars_to_list[1]", output, n);
5268 arg = ++p;
5269 p = strchr(p, SPECIAL_VAR_SYMBOL);
5270
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005271 /* Fetch special var name (if it is indeed one of them)
5272 * and quote bit, force the bit on if singleword expansion -
5273 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005274 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005275
5276 /* Is this variable quoted and thus expansion can't be null?
5277 * "$@" is special. Even if quoted, it can still
5278 * expand to nothing (not even an empty string),
5279 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005280 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005281 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005282
5283 switch (first_ch & 0x7f) {
5284 /* Highest bit in first_ch indicates that var is double-quoted */
5285 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005286 case '@': {
5287 int i;
5288 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005289 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005290 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005291 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005292 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005293 while (G.global_argv[i]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005294 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005295 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5296 if (G.global_argv[i++][0] && G.global_argv[i]) {
5297 /* this argv[] is not empty and not last:
5298 * put terminating NUL, start new word */
5299 o_addchr(output, '\0');
5300 debug_print_list("expand_vars_to_list[2]", output, n);
5301 n = o_save_ptr(output, n);
5302 debug_print_list("expand_vars_to_list[3]", output, n);
5303 }
5304 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005305 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005306 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005307 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005308 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005309 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005310 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005311 while (1) {
5312 o_addQstr(output, G.global_argv[i]);
5313 if (++i >= G.global_argc)
5314 break;
5315 o_addchr(output, '\0');
5316 debug_print_list("expand_vars_to_list[4]", output, n);
5317 n = o_save_ptr(output, n);
5318 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005319 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005320 while (1) {
5321 o_addQstr(output, G.global_argv[i]);
5322 if (!G.global_argv[++i])
5323 break;
5324 if (G.ifs[0])
5325 o_addchr(output, G.ifs[0]);
5326 }
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005327 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005328 }
5329 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005330 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005331 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5332 /* "Empty variable", used to make "" etc to not disappear */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005333 output->has_quoted_part = 1;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005334 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005335 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005336 break;
5337#if ENABLE_HUSH_TICK
5338 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005339 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005340 arg++;
5341 /* Can't just stuff it into output o_string,
5342 * expanded result may need to be globbed
5343 * and $IFS-splitted */
5344 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5345 G.last_exitcode = process_command_subs(&subst_result, arg);
5346 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5347 val = subst_result.data;
5348 goto store_val;
5349#endif
5350#if ENABLE_SH_MATH_SUPPORT
5351 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5352 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005353
5354 arg++; /* skip '+' */
5355 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5356 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005357 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005358 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5359 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005360 val = arith_buf;
5361 break;
5362 }
5363#endif
5364 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005365 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005366 IF_HUSH_TICK(store_val:)
5367 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005368 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5369 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005370 if (val && val[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005371 n = expand_on_ifs(&ended_in_ifs, output, n, val);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005372 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005373 }
5374 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko4fb53fb2011-08-01 14:06:20 +02005375 output->has_quoted_part = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005376 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5377 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005378 }
5379 break;
5380
5381 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5382
5383 if (val && val[0]) {
5384 o_addQstr(output, val);
5385 }
5386 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005387
5388 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5389 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005390 if (*p != SPECIAL_VAR_SYMBOL)
5391 *p = SPECIAL_VAR_SYMBOL;
5392
5393#if ENABLE_HUSH_TICK
5394 o_free(&subst_result);
5395#endif
5396 arg = ++p;
5397 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5398
5399 if (arg[0]) {
Denys Vlasenko6e42b892011-08-01 18:16:43 +02005400 if (ended_in_ifs) {
5401 o_addchr(output, '\0');
5402 n = o_save_ptr(output, n);
5403 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005404 debug_print_list("expand_vars_to_list[a]", output, n);
5405 /* this part is literal, and it was already pre-quoted
5406 * if needed (much earlier), do not use o_addQstr here! */
5407 o_addstr_with_NUL(output, arg);
5408 debug_print_list("expand_vars_to_list[b]", output, n);
5409 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005410 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005411 ) {
5412 n--;
5413 /* allow to reuse list[n] later without re-growth */
5414 output->has_empty_slot = 1;
5415 } else {
5416 o_addchr(output, '\0');
5417 }
5418
5419 return n;
5420}
5421
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005422static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005423{
5424 int n;
5425 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005426 o_string output = NULL_O_STRING;
5427
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005428 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005429
5430 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005431 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005432 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005433 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005434 }
5435 debug_print_list("expand_variables", &output, n);
5436
5437 /* output.data (malloced in one block) gets returned in "list" */
5438 list = o_finalize_list(&output, n);
5439 debug_print_strings("expand_variables[1]", list);
5440 return list;
5441}
5442
5443static char **expand_strvec_to_strvec(char **argv)
5444{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005445 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005446}
5447
5448#if ENABLE_HUSH_BASH_COMPAT
5449static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5450{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005451 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005452}
5453#endif
5454
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005455/* Used for expansion of right hand of assignments,
5456 * $((...)), heredocs, variable espansion parts.
5457 *
5458 * NB: should NOT do globbing!
5459 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5460 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005461static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005462{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005463#if !ENABLE_HUSH_BASH_COMPAT
5464 const int do_unbackslash = 1;
5465#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005466 char *argv[2], **list;
5467
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005468 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005469 /* This is generally an optimization, but it also
5470 * handles "", which otherwise trips over !list[0] check below.
5471 * (is this ever happens that we actually get str="" here?)
5472 */
5473 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5474 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005475 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005476 return xstrdup(str);
5477 }
5478
5479 argv[0] = (char*)str;
5480 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005481 list = expand_variables(argv, do_unbackslash
5482 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5483 : EXP_FLAG_SINGLEWORD
5484 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005485 if (HUSH_DEBUG)
5486 if (!list[0] || list[1])
5487 bb_error_msg_and_die("BUG in varexp2");
5488 /* actually, just move string 2*sizeof(char*) bytes back */
5489 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005490 if (do_unbackslash)
5491 unbackslash((char*)list);
5492 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005493 return (char*)list;
5494}
5495
5496/* Used for "eval" builtin */
5497static char* expand_strvec_to_string(char **argv)
5498{
5499 char **list;
5500
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005501 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005502 /* Convert all NULs to spaces */
5503 if (list[0]) {
5504 int n = 1;
5505 while (list[n]) {
5506 if (HUSH_DEBUG)
5507 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5508 bb_error_msg_and_die("BUG in varexp3");
5509 /* bash uses ' ' regardless of $IFS contents */
5510 list[n][-1] = ' ';
5511 n++;
5512 }
5513 }
5514 overlapping_strcpy((char*)list, list[0]);
5515 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5516 return (char*)list;
5517}
5518
5519static char **expand_assignments(char **argv, int count)
5520{
5521 int i;
5522 char **p;
5523
5524 G.expanded_assignments = p = NULL;
5525 /* Expand assignments into one string each */
5526 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005527 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005528 }
5529 G.expanded_assignments = NULL;
5530 return p;
5531}
5532
5533
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005534static void switch_off_special_sigs(unsigned mask)
5535{
5536 unsigned sig = 0;
5537 while ((mask >>= 1) != 0) {
5538 sig++;
5539 if (!(mask & 1))
5540 continue;
5541 if (G.traps) {
5542 if (G.traps[sig] && !G.traps[sig][0])
5543 /* trap is '', has to remain SIG_IGN */
5544 continue;
5545 free(G.traps[sig]);
5546 G.traps[sig] = NULL;
5547 }
5548 /* We are here only if no trap or trap was not '' */
Denys Vlasenko0806e402011-05-12 23:06:20 +02005549 install_sighandler(sig, SIG_DFL);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005550 }
5551}
5552
Denys Vlasenkob347df92011-08-09 22:49:15 +02005553#if BB_MMU
5554/* never called */
5555void re_execute_shell(char ***to_free, const char *s,
5556 char *g_argv0, char **g_argv,
5557 char **builtin_argv) NORETURN;
5558
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005559static void reset_traps_to_defaults(void)
5560{
5561 /* This function is always called in a child shell
5562 * after fork (not vfork, NOMMU doesn't use this function).
5563 */
5564 unsigned sig;
5565 unsigned mask;
5566
5567 /* Child shells are not interactive.
5568 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5569 * Testcase: (while :; do :; done) + ^Z should background.
5570 * Same goes for SIGTERM, SIGHUP, SIGINT.
5571 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005572 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5573 if (!G.traps && !mask)
5574 return; /* already no traps and no special sigs */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005575
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005576 /* Switch off special sigs */
5577 switch_off_special_sigs(mask);
5578#if ENABLE_HUSH_JOB
5579 G_fatal_sig_mask = 0;
5580#endif
Denys Vlasenko10c01312011-05-11 11:49:21 +02005581 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02005582 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5583 * remain set in G.special_sig_mask */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005584
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005585 if (!G.traps)
5586 return;
5587
5588 /* Reset all sigs to default except ones with empty traps */
5589 for (sig = 0; sig < NSIG; sig++) {
5590 if (!G.traps[sig])
5591 continue; /* no trap: nothing to do */
5592 if (!G.traps[sig][0])
5593 continue; /* empty trap: has to remain SIG_IGN */
5594 /* sig has non-empty trap, reset it: */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005595 free(G.traps[sig]);
5596 G.traps[sig] = NULL;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02005597 /* There is no signal for trap 0 (EXIT) */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005598 if (sig == 0)
5599 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02005600 install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005601 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005602}
5603
5604#else /* !BB_MMU */
5605
5606static void re_execute_shell(char ***to_free, const char *s,
5607 char *g_argv0, char **g_argv,
5608 char **builtin_argv) NORETURN;
5609static void re_execute_shell(char ***to_free, const char *s,
5610 char *g_argv0, char **g_argv,
5611 char **builtin_argv)
5612{
5613# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5614 /* delims + 2 * (number of bytes in printed hex numbers) */
5615 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5616 char *heredoc_argv[4];
5617 struct variable *cur;
5618# if ENABLE_HUSH_FUNCTIONS
5619 struct function *funcp;
5620# endif
5621 char **argv, **pp;
5622 unsigned cnt;
5623 unsigned long long empty_trap_mask;
5624
5625 if (!g_argv0) { /* heredoc */
5626 argv = heredoc_argv;
5627 argv[0] = (char *) G.argv0_for_re_execing;
5628 argv[1] = (char *) "-<";
5629 argv[2] = (char *) s;
5630 argv[3] = NULL;
5631 pp = &argv[3]; /* used as pointer to empty environment */
5632 goto do_exec;
5633 }
5634
5635 cnt = 0;
5636 pp = builtin_argv;
5637 if (pp) while (*pp++)
5638 cnt++;
5639
5640 empty_trap_mask = 0;
5641 if (G.traps) {
5642 int sig;
5643 for (sig = 1; sig < NSIG; sig++) {
5644 if (G.traps[sig] && !G.traps[sig][0])
5645 empty_trap_mask |= 1LL << sig;
5646 }
5647 }
5648
5649 sprintf(param_buf, NOMMU_HACK_FMT
5650 , (unsigned) G.root_pid
5651 , (unsigned) G.root_ppid
5652 , (unsigned) G.last_bg_pid
5653 , (unsigned) G.last_exitcode
5654 , cnt
5655 , empty_trap_mask
5656 IF_HUSH_LOOPS(, G.depth_of_loop)
5657 );
5658# undef NOMMU_HACK_FMT
5659 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5660 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5661 */
5662 cnt += 6;
5663 for (cur = G.top_var; cur; cur = cur->next) {
5664 if (!cur->flg_export || cur->flg_read_only)
5665 cnt += 2;
5666 }
5667# if ENABLE_HUSH_FUNCTIONS
5668 for (funcp = G.top_func; funcp; funcp = funcp->next)
5669 cnt += 3;
5670# endif
5671 pp = g_argv;
5672 while (*pp++)
5673 cnt++;
5674 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5675 *pp++ = (char *) G.argv0_for_re_execing;
5676 *pp++ = param_buf;
5677 for (cur = G.top_var; cur; cur = cur->next) {
5678 if (strcmp(cur->varstr, hush_version_str) == 0)
5679 continue;
5680 if (cur->flg_read_only) {
5681 *pp++ = (char *) "-R";
5682 *pp++ = cur->varstr;
5683 } else if (!cur->flg_export) {
5684 *pp++ = (char *) "-V";
5685 *pp++ = cur->varstr;
5686 }
5687 }
5688# if ENABLE_HUSH_FUNCTIONS
5689 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5690 *pp++ = (char *) "-F";
5691 *pp++ = funcp->name;
5692 *pp++ = funcp->body_as_string;
5693 }
5694# endif
5695 /* We can pass activated traps here. Say, -Tnn:trap_string
5696 *
5697 * However, POSIX says that subshells reset signals with traps
5698 * to SIG_DFL.
5699 * I tested bash-3.2 and it not only does that with true subshells
5700 * of the form ( list ), but with any forked children shells.
5701 * I set trap "echo W" WINCH; and then tried:
5702 *
5703 * { echo 1; sleep 20; echo 2; } &
5704 * while true; do echo 1; sleep 20; echo 2; break; done &
5705 * true | { echo 1; sleep 20; echo 2; } | cat
5706 *
5707 * In all these cases sending SIGWINCH to the child shell
5708 * did not run the trap. If I add trap "echo V" WINCH;
5709 * _inside_ group (just before echo 1), it works.
5710 *
5711 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005712 */
5713 *pp++ = (char *) "-c";
5714 *pp++ = (char *) s;
5715 if (builtin_argv) {
5716 while (*++builtin_argv)
5717 *pp++ = *builtin_argv;
5718 *pp++ = (char *) "";
5719 }
5720 *pp++ = g_argv0;
5721 while (*g_argv)
5722 *pp++ = *g_argv++;
5723 /* *pp = NULL; - is already there */
5724 pp = environ;
5725
5726 do_exec:
5727 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02005728 /* Don't propagate SIG_IGN to the child */
5729 if (SPECIAL_JOBSTOP_SIGS != 0)
5730 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005731 execve(bb_busybox_exec_path, argv, pp);
5732 /* Fallback. Useful for init=/bin/hush usage etc */
5733 if (argv[0][0] == '/')
5734 execve(argv[0], argv, pp);
5735 xfunc_error_retval = 127;
5736 bb_error_msg_and_die("can't re-execute the shell");
5737}
5738#endif /* !BB_MMU */
5739
5740
5741static int run_and_free_list(struct pipe *pi);
5742
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005743/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005744 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5745 * end_trigger controls how often we stop parsing
5746 * NUL: parse all, execute, return
5747 * ';': parse till ';' or newline, execute, repeat till EOF
5748 */
5749static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005750{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005751 /* Why we need empty flag?
5752 * An obscure corner case "false; ``; echo $?":
5753 * empty command in `` should still set $? to 0.
5754 * But we can't just set $? to 0 at the start,
5755 * this breaks "false; echo `echo $?`" case.
5756 */
5757 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005758 while (1) {
5759 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005760
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005761#if ENABLE_HUSH_INTERACTIVE
5762 if (end_trigger == ';')
5763 inp->promptmode = 0; /* PS1 */
5764#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005765 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenkocecbc982011-03-30 18:54:52 +02005766 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5767 /* If we are in "big" script
5768 * (not in `cmd` or something similar)...
5769 */
5770 if (pipe_list == ERR_PTR && end_trigger == ';') {
5771 /* Discard cached input (rest of line) */
5772 int ch = inp->last_char;
5773 while (ch != EOF && ch != '\n') {
5774 //bb_error_msg("Discarded:'%c'", ch);
5775 ch = i_getch(inp);
5776 }
5777 /* Force prompt */
5778 inp->p = NULL;
5779 /* This stream isn't empty */
5780 empty = 0;
5781 continue;
5782 }
5783 if (!pipe_list && empty)
Denys Vlasenko00243b02009-11-16 02:00:03 +01005784 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005785 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005786 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005787 debug_print_tree(pipe_list, 0);
5788 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5789 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005790 empty = 0;
Denys Vlasenko68d5cb52011-03-24 02:50:03 +01005791#if ENABLE_HUSH_FUNCTIONS
5792 if (G.flag_return_in_progress == 1)
5793 break;
5794#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005795 }
Eric Andersen25f27032001-04-26 23:22:31 +00005796}
5797
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005798static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005799{
5800 struct in_str input;
5801 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005802 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005803}
5804
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005805static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005806{
Eric Andersen25f27032001-04-26 23:22:31 +00005807 struct in_str input;
5808 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005809 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005810}
5811
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005812#if ENABLE_HUSH_TICK
5813static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5814{
5815 pid_t pid;
5816 int channel[2];
5817# if !BB_MMU
5818 char **to_free = NULL;
5819# endif
5820
5821 xpipe(channel);
5822 pid = BB_MMU ? xfork() : xvfork();
5823 if (pid == 0) { /* child */
5824 disable_restore_tty_pgrp_on_exit();
5825 /* Process substitution is not considered to be usual
5826 * 'command execution'.
5827 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5828 */
5829 bb_signals(0
5830 + (1 << SIGTSTP)
5831 + (1 << SIGTTIN)
5832 + (1 << SIGTTOU)
5833 , SIG_IGN);
5834 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5835 close(channel[0]); /* NB: close _first_, then move fd! */
5836 xmove_fd(channel[1], 1);
5837 /* Prevent it from trying to handle ctrl-z etc */
5838 IF_HUSH_JOB(G.run_list_level = 1;)
5839 /* Awful hack for `trap` or $(trap).
5840 *
5841 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5842 * contains an example where "trap" is executed in a subshell:
5843 *
5844 * save_traps=$(trap)
5845 * ...
5846 * eval "$save_traps"
5847 *
5848 * Standard does not say that "trap" in subshell shall print
5849 * parent shell's traps. It only says that its output
5850 * must have suitable form, but then, in the above example
5851 * (which is not supposed to be normative), it implies that.
5852 *
5853 * bash (and probably other shell) does implement it
5854 * (traps are reset to defaults, but "trap" still shows them),
5855 * but as a result, "trap" logic is hopelessly messed up:
5856 *
5857 * # trap
5858 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5859 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5860 * # true | trap <--- trap is in subshell - no output (ditto)
5861 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5862 * trap -- 'echo Ho' SIGWINCH
5863 * # echo `(trap)` <--- in subshell in subshell - output
5864 * trap -- 'echo Ho' SIGWINCH
5865 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5866 * trap -- 'echo Ho' SIGWINCH
5867 *
5868 * The rules when to forget and when to not forget traps
5869 * get really complex and nonsensical.
5870 *
5871 * Our solution: ONLY bare $(trap) or `trap` is special.
5872 */
5873 s = skip_whitespace(s);
5874 if (strncmp(s, "trap", 4) == 0
5875 && skip_whitespace(s + 4)[0] == '\0'
5876 ) {
5877 static const char *const argv[] = { NULL, NULL };
5878 builtin_trap((char**)argv);
5879 exit(0); /* not _exit() - we need to fflush */
5880 }
5881# if BB_MMU
5882 reset_traps_to_defaults();
5883 parse_and_run_string(s);
5884 _exit(G.last_exitcode);
5885# else
5886 /* We re-execute after vfork on NOMMU. This makes this script safe:
5887 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5888 * huge=`cat BIG` # was blocking here forever
5889 * echo OK
5890 */
5891 re_execute_shell(&to_free,
5892 s,
5893 G.global_argv[0],
5894 G.global_argv + 1,
5895 NULL);
5896# endif
5897 }
5898
5899 /* parent */
5900 *pid_p = pid;
5901# if ENABLE_HUSH_FAST
5902 G.count_SIGCHLD++;
5903//bb_error_msg("[%d] fork in generate_stream_from_string:"
5904// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5905// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5906# endif
5907 enable_restore_tty_pgrp_on_exit();
5908# if !BB_MMU
5909 free(to_free);
5910# endif
5911 close(channel[1]);
5912 close_on_exec_on(channel[0]);
5913 return xfdopen_for_read(channel[0]);
5914}
5915
5916/* Return code is exit status of the process that is run. */
5917static int process_command_subs(o_string *dest, const char *s)
5918{
5919 FILE *fp;
5920 struct in_str pipe_str;
5921 pid_t pid;
5922 int status, ch, eol_cnt;
5923
5924 fp = generate_stream_from_string(s, &pid);
5925
5926 /* Now send results of command back into original context */
5927 setup_file_in_str(&pipe_str, fp);
5928 eol_cnt = 0;
5929 while ((ch = i_getch(&pipe_str)) != EOF) {
5930 if (ch == '\n') {
5931 eol_cnt++;
5932 continue;
5933 }
5934 while (eol_cnt) {
5935 o_addchr(dest, '\n');
5936 eol_cnt--;
5937 }
5938 o_addQchr(dest, ch);
5939 }
5940
5941 debug_printf("done reading from `cmd` pipe, closing it\n");
5942 fclose(fp);
5943 /* We need to extract exitcode. Test case
5944 * "true; echo `sleep 1; false` $?"
5945 * should print 1 */
5946 safe_waitpid(pid, &status, 0);
5947 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5948 return WEXITSTATUS(status);
5949}
5950#endif /* ENABLE_HUSH_TICK */
5951
5952
5953static void setup_heredoc(struct redir_struct *redir)
5954{
5955 struct fd_pair pair;
5956 pid_t pid;
5957 int len, written;
5958 /* the _body_ of heredoc (misleading field name) */
5959 const char *heredoc = redir->rd_filename;
5960 char *expanded;
5961#if !BB_MMU
5962 char **to_free;
5963#endif
5964
5965 expanded = NULL;
5966 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005967 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005968 if (expanded)
5969 heredoc = expanded;
5970 }
5971 len = strlen(heredoc);
5972
5973 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5974 xpiped_pair(pair);
5975 xmove_fd(pair.rd, redir->rd_fd);
5976
5977 /* Try writing without forking. Newer kernels have
5978 * dynamically growing pipes. Must use non-blocking write! */
5979 ndelay_on(pair.wr);
5980 while (1) {
5981 written = write(pair.wr, heredoc, len);
5982 if (written <= 0)
5983 break;
5984 len -= written;
5985 if (len == 0) {
5986 close(pair.wr);
5987 free(expanded);
5988 return;
5989 }
5990 heredoc += written;
5991 }
5992 ndelay_off(pair.wr);
5993
5994 /* Okay, pipe buffer was not big enough */
5995 /* Note: we must not create a stray child (bastard? :)
5996 * for the unsuspecting parent process. Child creates a grandchild
5997 * and exits before parent execs the process which consumes heredoc
5998 * (that exec happens after we return from this function) */
5999#if !BB_MMU
6000 to_free = NULL;
6001#endif
6002 pid = xvfork();
6003 if (pid == 0) {
6004 /* child */
6005 disable_restore_tty_pgrp_on_exit();
6006 pid = BB_MMU ? xfork() : xvfork();
6007 if (pid != 0)
6008 _exit(0);
6009 /* grandchild */
6010 close(redir->rd_fd); /* read side of the pipe */
6011#if BB_MMU
6012 full_write(pair.wr, heredoc, len); /* may loop or block */
6013 _exit(0);
6014#else
6015 /* Delegate blocking writes to another process */
6016 xmove_fd(pair.wr, STDOUT_FILENO);
6017 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6018#endif
6019 }
6020 /* parent */
6021#if ENABLE_HUSH_FAST
6022 G.count_SIGCHLD++;
6023//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6024#endif
6025 enable_restore_tty_pgrp_on_exit();
6026#if !BB_MMU
6027 free(to_free);
6028#endif
6029 close(pair.wr);
6030 free(expanded);
6031 wait(NULL); /* wait till child has died */
6032}
6033
6034/* squirrel != NULL means we squirrel away copies of stdin, stdout,
6035 * and stderr if they are redirected. */
6036static int setup_redirects(struct command *prog, int squirrel[])
6037{
6038 int openfd, mode;
6039 struct redir_struct *redir;
6040
6041 for (redir = prog->redirects; redir; redir = redir->next) {
6042 if (redir->rd_type == REDIRECT_HEREDOC2) {
6043 /* rd_fd<<HERE case */
6044 if (squirrel && redir->rd_fd < 3
6045 && squirrel[redir->rd_fd] < 0
6046 ) {
6047 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6048 }
6049 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6050 * of the heredoc */
6051 debug_printf_parse("set heredoc '%s'\n",
6052 redir->rd_filename);
6053 setup_heredoc(redir);
6054 continue;
6055 }
6056
6057 if (redir->rd_dup == REDIRFD_TO_FILE) {
6058 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6059 char *p;
6060 if (redir->rd_filename == NULL) {
6061 /* Something went wrong in the parse.
6062 * Pretend it didn't happen */
6063 bb_error_msg("bug in redirect parse");
6064 continue;
6065 }
6066 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006067 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006068 openfd = open_or_warn(p, mode);
6069 free(p);
6070 if (openfd < 0) {
6071 /* this could get lost if stderr has been redirected, but
6072 * bash and ash both lose it as well (though zsh doesn't!) */
6073//what the above comment tries to say?
6074 return 1;
6075 }
6076 } else {
6077 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6078 openfd = redir->rd_dup;
6079 }
6080
6081 if (openfd != redir->rd_fd) {
6082 if (squirrel && redir->rd_fd < 3
6083 && squirrel[redir->rd_fd] < 0
6084 ) {
6085 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6086 }
6087 if (openfd == REDIRFD_CLOSE) {
6088 /* "n>-" means "close me" */
6089 close(redir->rd_fd);
6090 } else {
6091 xdup2(openfd, redir->rd_fd);
6092 if (redir->rd_dup == REDIRFD_TO_FILE)
6093 close(openfd);
6094 }
6095 }
6096 }
6097 return 0;
6098}
6099
6100static void restore_redirects(int squirrel[])
6101{
6102 int i, fd;
6103 for (i = 0; i < 3; i++) {
6104 fd = squirrel[i];
6105 if (fd != -1) {
6106 /* We simply die on error */
6107 xmove_fd(fd, i);
6108 }
6109 }
6110}
6111
6112static char *find_in_path(const char *arg)
6113{
6114 char *ret = NULL;
6115 const char *PATH = get_local_var_value("PATH");
6116
6117 if (!PATH)
6118 return NULL;
6119
6120 while (1) {
6121 const char *end = strchrnul(PATH, ':');
6122 int sz = end - PATH; /* must be int! */
6123
6124 free(ret);
6125 if (sz != 0) {
6126 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6127 } else {
6128 /* We have xxx::yyyy in $PATH,
6129 * it means "use current dir" */
6130 ret = xstrdup(arg);
6131 }
6132 if (access(ret, F_OK) == 0)
6133 break;
6134
6135 if (*end == '\0') {
6136 free(ret);
6137 return NULL;
6138 }
6139 PATH = end + 1;
6140 }
6141
6142 return ret;
6143}
6144
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006145static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006146 const struct built_in_command *x,
6147 const struct built_in_command *end)
6148{
6149 while (x != end) {
6150 if (strcmp(name, x->b_cmd) != 0) {
6151 x++;
6152 continue;
6153 }
6154 debug_printf_exec("found builtin '%s'\n", name);
6155 return x;
6156 }
6157 return NULL;
6158}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006159static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006160{
6161 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6162}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006163static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006164{
6165 const struct built_in_command *x = find_builtin1(name);
6166 if (x)
6167 return x;
6168 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6169}
6170
6171#if ENABLE_HUSH_FUNCTIONS
6172static struct function **find_function_slot(const char *name)
6173{
6174 struct function **funcpp = &G.top_func;
6175 while (*funcpp) {
6176 if (strcmp(name, (*funcpp)->name) == 0) {
6177 break;
6178 }
6179 funcpp = &(*funcpp)->next;
6180 }
6181 return funcpp;
6182}
6183
6184static const struct function *find_function(const char *name)
6185{
6186 const struct function *funcp = *find_function_slot(name);
6187 if (funcp)
6188 debug_printf_exec("found function '%s'\n", name);
6189 return funcp;
6190}
6191
6192/* Note: takes ownership on name ptr */
6193static struct function *new_function(char *name)
6194{
6195 struct function **funcpp = find_function_slot(name);
6196 struct function *funcp = *funcpp;
6197
6198 if (funcp != NULL) {
6199 struct command *cmd = funcp->parent_cmd;
6200 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6201 if (!cmd) {
6202 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6203 free(funcp->name);
6204 /* Note: if !funcp->body, do not free body_as_string!
6205 * This is a special case of "-F name body" function:
6206 * body_as_string was not malloced! */
6207 if (funcp->body) {
6208 free_pipe_list(funcp->body);
6209# if !BB_MMU
6210 free(funcp->body_as_string);
6211# endif
6212 }
6213 } else {
6214 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6215 cmd->argv[0] = funcp->name;
6216 cmd->group = funcp->body;
6217# if !BB_MMU
6218 cmd->group_as_string = funcp->body_as_string;
6219# endif
6220 }
6221 } else {
6222 debug_printf_exec("remembering new function '%s'\n", name);
6223 funcp = *funcpp = xzalloc(sizeof(*funcp));
6224 /*funcp->next = NULL;*/
6225 }
6226
6227 funcp->name = name;
6228 return funcp;
6229}
6230
6231static void unset_func(const char *name)
6232{
6233 struct function **funcpp = find_function_slot(name);
6234 struct function *funcp = *funcpp;
6235
6236 if (funcp != NULL) {
6237 debug_printf_exec("freeing function '%s'\n", funcp->name);
6238 *funcpp = funcp->next;
6239 /* funcp is unlinked now, deleting it.
6240 * Note: if !funcp->body, the function was created by
6241 * "-F name body", do not free ->body_as_string
6242 * and ->name as they were not malloced. */
6243 if (funcp->body) {
6244 free_pipe_list(funcp->body);
6245 free(funcp->name);
6246# if !BB_MMU
6247 free(funcp->body_as_string);
6248# endif
6249 }
6250 free(funcp);
6251 }
6252}
6253
6254# if BB_MMU
6255#define exec_function(to_free, funcp, argv) \
6256 exec_function(funcp, argv)
6257# endif
6258static void exec_function(char ***to_free,
6259 const struct function *funcp,
6260 char **argv) NORETURN;
6261static void exec_function(char ***to_free,
6262 const struct function *funcp,
6263 char **argv)
6264{
6265# if BB_MMU
6266 int n = 1;
6267
6268 argv[0] = G.global_argv[0];
6269 G.global_argv = argv;
6270 while (*++argv)
6271 n++;
6272 G.global_argc = n;
6273 /* On MMU, funcp->body is always non-NULL */
6274 n = run_list(funcp->body);
6275 fflush_all();
6276 _exit(n);
6277# else
6278 re_execute_shell(to_free,
6279 funcp->body_as_string,
6280 G.global_argv[0],
6281 argv + 1,
6282 NULL);
6283# endif
6284}
6285
6286static int run_function(const struct function *funcp, char **argv)
6287{
6288 int rc;
6289 save_arg_t sv;
6290 smallint sv_flg;
6291
6292 save_and_replace_G_args(&sv, argv);
6293
6294 /* "we are in function, ok to use return" */
6295 sv_flg = G.flag_return_in_progress;
6296 G.flag_return_in_progress = -1;
6297# if ENABLE_HUSH_LOCAL
6298 G.func_nest_level++;
6299# endif
6300
6301 /* On MMU, funcp->body is always non-NULL */
6302# if !BB_MMU
6303 if (!funcp->body) {
6304 /* Function defined by -F */
6305 parse_and_run_string(funcp->body_as_string);
6306 rc = G.last_exitcode;
6307 } else
6308# endif
6309 {
6310 rc = run_list(funcp->body);
6311 }
6312
6313# if ENABLE_HUSH_LOCAL
6314 {
6315 struct variable *var;
6316 struct variable **var_pp;
6317
6318 var_pp = &G.top_var;
6319 while ((var = *var_pp) != NULL) {
6320 if (var->func_nest_level < G.func_nest_level) {
6321 var_pp = &var->next;
6322 continue;
6323 }
6324 /* Unexport */
6325 if (var->flg_export)
6326 bb_unsetenv(var->varstr);
6327 /* Remove from global list */
6328 *var_pp = var->next;
6329 /* Free */
6330 if (!var->max_len)
6331 free(var->varstr);
6332 free(var);
6333 }
6334 G.func_nest_level--;
6335 }
6336# endif
6337 G.flag_return_in_progress = sv_flg;
6338
6339 restore_G_args(&sv, argv);
6340
6341 return rc;
6342}
6343#endif /* ENABLE_HUSH_FUNCTIONS */
6344
6345
6346#if BB_MMU
6347#define exec_builtin(to_free, x, argv) \
6348 exec_builtin(x, argv)
6349#else
6350#define exec_builtin(to_free, x, argv) \
6351 exec_builtin(to_free, argv)
6352#endif
6353static void exec_builtin(char ***to_free,
6354 const struct built_in_command *x,
6355 char **argv) NORETURN;
6356static void exec_builtin(char ***to_free,
6357 const struct built_in_command *x,
6358 char **argv)
6359{
6360#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006361 int rcode;
6362 fflush_all();
6363 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006364 fflush_all();
6365 _exit(rcode);
6366#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006367 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006368 /* On NOMMU, we must never block!
6369 * Example: { sleep 99 | read line; } & echo Ok
6370 */
6371 re_execute_shell(to_free,
6372 argv[0],
6373 G.global_argv[0],
6374 G.global_argv + 1,
6375 argv);
6376#endif
6377}
6378
6379
6380static void execvp_or_die(char **argv) NORETURN;
6381static void execvp_or_die(char **argv)
6382{
6383 debug_printf_exec("execing '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006384 /* Don't propagate SIG_IGN to the child */
6385 if (SPECIAL_JOBSTOP_SIGS != 0)
6386 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006387 execvp(argv[0], argv);
6388 bb_perror_msg("can't execute '%s'", argv[0]);
6389 _exit(127); /* bash compat */
6390}
6391
6392#if ENABLE_HUSH_MODE_X
6393static void dump_cmd_in_x_mode(char **argv)
6394{
6395 if (G_x_mode && argv) {
6396 /* We want to output the line in one write op */
6397 char *buf, *p;
6398 int len;
6399 int n;
6400
6401 len = 3;
6402 n = 0;
6403 while (argv[n])
6404 len += strlen(argv[n++]) + 1;
6405 buf = xmalloc(len);
6406 buf[0] = '+';
6407 p = buf + 1;
6408 n = 0;
6409 while (argv[n])
6410 p += sprintf(p, " %s", argv[n++]);
6411 *p++ = '\n';
6412 *p = '\0';
6413 fputs(buf, stderr);
6414 free(buf);
6415 }
6416}
6417#else
6418# define dump_cmd_in_x_mode(argv) ((void)0)
6419#endif
6420
6421#if BB_MMU
6422#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6423 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6424#define pseudo_exec(nommu_save, command, argv_expanded) \
6425 pseudo_exec(command, argv_expanded)
6426#endif
6427
6428/* Called after [v]fork() in run_pipe, or from builtin_exec.
6429 * Never returns.
6430 * Don't exit() here. If you don't exec, use _exit instead.
6431 * The at_exit handlers apparently confuse the calling process,
6432 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6433static void pseudo_exec_argv(nommu_save_t *nommu_save,
6434 char **argv, int assignment_cnt,
6435 char **argv_expanded) NORETURN;
6436static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6437 char **argv, int assignment_cnt,
6438 char **argv_expanded)
6439{
6440 char **new_env;
6441
6442 new_env = expand_assignments(argv, assignment_cnt);
6443 dump_cmd_in_x_mode(new_env);
6444
6445 if (!argv[assignment_cnt]) {
6446 /* Case when we are here: ... | var=val | ...
6447 * (note that we do not exit early, i.e., do not optimize out
6448 * expand_assignments(): think about ... | var=`sleep 1` | ...
6449 */
6450 free_strings(new_env);
6451 _exit(EXIT_SUCCESS);
6452 }
6453
6454#if BB_MMU
6455 set_vars_and_save_old(new_env);
6456 free(new_env); /* optional */
6457 /* we can also destroy set_vars_and_save_old's return value,
6458 * to save memory */
6459#else
6460 nommu_save->new_env = new_env;
6461 nommu_save->old_vars = set_vars_and_save_old(new_env);
6462#endif
6463
6464 if (argv_expanded) {
6465 argv = argv_expanded;
6466 } else {
6467 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6468#if !BB_MMU
6469 nommu_save->argv = argv;
6470#endif
6471 }
6472 dump_cmd_in_x_mode(argv);
6473
6474#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6475 if (strchr(argv[0], '/') != NULL)
6476 goto skip;
6477#endif
6478
6479 /* Check if the command matches any of the builtins.
6480 * Depending on context, this might be redundant. But it's
6481 * easier to waste a few CPU cycles than it is to figure out
6482 * if this is one of those cases.
6483 */
6484 {
6485 /* On NOMMU, it is more expensive to re-execute shell
6486 * just in order to run echo or test builtin.
6487 * It's better to skip it here and run corresponding
6488 * non-builtin later. */
6489 const struct built_in_command *x;
6490 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6491 if (x) {
6492 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6493 }
6494 }
6495#if ENABLE_HUSH_FUNCTIONS
6496 /* Check if the command matches any functions */
6497 {
6498 const struct function *funcp = find_function(argv[0]);
6499 if (funcp) {
6500 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6501 }
6502 }
6503#endif
6504
6505#if ENABLE_FEATURE_SH_STANDALONE
6506 /* Check if the command matches any busybox applets */
6507 {
6508 int a = find_applet_by_name(argv[0]);
6509 if (a >= 0) {
6510# if BB_MMU /* see above why on NOMMU it is not allowed */
6511 if (APPLET_IS_NOEXEC(a)) {
6512 debug_printf_exec("running applet '%s'\n", argv[0]);
6513 run_applet_no_and_exit(a, argv);
6514 }
6515# endif
6516 /* Re-exec ourselves */
6517 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denys Vlasenko75e77de2011-05-12 13:12:47 +02006518 /* Don't propagate SIG_IGN to the child */
6519 if (SPECIAL_JOBSTOP_SIGS != 0)
6520 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006521 execv(bb_busybox_exec_path, argv);
6522 /* If they called chroot or otherwise made the binary no longer
6523 * executable, fall through */
6524 }
6525 }
6526#endif
6527
6528#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6529 skip:
6530#endif
6531 execvp_or_die(argv);
6532}
6533
6534/* Called after [v]fork() in run_pipe
6535 */
6536static void pseudo_exec(nommu_save_t *nommu_save,
6537 struct command *command,
6538 char **argv_expanded) NORETURN;
6539static void pseudo_exec(nommu_save_t *nommu_save,
6540 struct command *command,
6541 char **argv_expanded)
6542{
6543 if (command->argv) {
6544 pseudo_exec_argv(nommu_save, command->argv,
6545 command->assignment_cnt, argv_expanded);
6546 }
6547
6548 if (command->group) {
6549 /* Cases when we are here:
6550 * ( list )
6551 * { list } &
6552 * ... | ( list ) | ...
6553 * ... | { list } | ...
6554 */
6555#if BB_MMU
6556 int rcode;
6557 debug_printf_exec("pseudo_exec: run_list\n");
6558 reset_traps_to_defaults();
6559 rcode = run_list(command->group);
6560 /* OK to leak memory by not calling free_pipe_list,
6561 * since this process is about to exit */
6562 _exit(rcode);
6563#else
6564 re_execute_shell(&nommu_save->argv_from_re_execing,
6565 command->group_as_string,
6566 G.global_argv[0],
6567 G.global_argv + 1,
6568 NULL);
6569#endif
6570 }
6571
6572 /* Case when we are here: ... | >file */
6573 debug_printf_exec("pseudo_exec'ed null command\n");
6574 _exit(EXIT_SUCCESS);
6575}
6576
6577#if ENABLE_HUSH_JOB
6578static const char *get_cmdtext(struct pipe *pi)
6579{
6580 char **argv;
6581 char *p;
6582 int len;
6583
6584 /* This is subtle. ->cmdtext is created only on first backgrounding.
6585 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6586 * On subsequent bg argv is trashed, but we won't use it */
6587 if (pi->cmdtext)
6588 return pi->cmdtext;
6589 argv = pi->cmds[0].argv;
6590 if (!argv || !argv[0]) {
6591 pi->cmdtext = xzalloc(1);
6592 return pi->cmdtext;
6593 }
6594
6595 len = 0;
6596 do {
6597 len += strlen(*argv) + 1;
6598 } while (*++argv);
6599 p = xmalloc(len);
6600 pi->cmdtext = p;
6601 argv = pi->cmds[0].argv;
6602 do {
6603 len = strlen(*argv);
6604 memcpy(p, *argv, len);
6605 p += len;
6606 *p++ = ' ';
6607 } while (*++argv);
6608 p[-1] = '\0';
6609 return pi->cmdtext;
6610}
6611
6612static void insert_bg_job(struct pipe *pi)
6613{
6614 struct pipe *job, **jobp;
6615 int i;
6616
6617 /* Linear search for the ID of the job to use */
6618 pi->jobid = 1;
6619 for (job = G.job_list; job; job = job->next)
6620 if (job->jobid >= pi->jobid)
6621 pi->jobid = job->jobid + 1;
6622
6623 /* Add job to the list of running jobs */
6624 jobp = &G.job_list;
6625 while ((job = *jobp) != NULL)
6626 jobp = &job->next;
6627 job = *jobp = xmalloc(sizeof(*job));
6628
6629 *job = *pi; /* physical copy */
6630 job->next = NULL;
6631 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6632 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6633 for (i = 0; i < pi->num_cmds; i++) {
6634 job->cmds[i].pid = pi->cmds[i].pid;
6635 /* all other fields are not used and stay zero */
6636 }
6637 job->cmdtext = xstrdup(get_cmdtext(pi));
6638
6639 if (G_interactive_fd)
6640 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6641 G.last_jobid = job->jobid;
6642}
6643
6644static void remove_bg_job(struct pipe *pi)
6645{
6646 struct pipe *prev_pipe;
6647
6648 if (pi == G.job_list) {
6649 G.job_list = pi->next;
6650 } else {
6651 prev_pipe = G.job_list;
6652 while (prev_pipe->next != pi)
6653 prev_pipe = prev_pipe->next;
6654 prev_pipe->next = pi->next;
6655 }
6656 if (G.job_list)
6657 G.last_jobid = G.job_list->jobid;
6658 else
6659 G.last_jobid = 0;
6660}
6661
6662/* Remove a backgrounded job */
6663static void delete_finished_bg_job(struct pipe *pi)
6664{
6665 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006666 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006667}
6668#endif /* JOB */
6669
6670/* Check to see if any processes have exited -- if they
6671 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006672static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006673{
6674 int attributes;
6675 int status;
6676#if ENABLE_HUSH_JOB
6677 struct pipe *pi;
6678#endif
6679 pid_t childpid;
6680 int rcode = 0;
6681
6682 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6683
6684 attributes = WUNTRACED;
6685 if (fg_pipe == NULL)
6686 attributes |= WNOHANG;
6687
6688 errno = 0;
6689#if ENABLE_HUSH_FAST
6690 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6691//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6692//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6693 /* There was neither fork nor SIGCHLD since last waitpid */
6694 /* Avoid doing waitpid syscall if possible */
6695 if (!G.we_have_children) {
6696 errno = ECHILD;
6697 return -1;
6698 }
6699 if (fg_pipe == NULL) { /* is WNOHANG set? */
6700 /* We have children, but they did not exit
6701 * or stop yet (we saw no SIGCHLD) */
6702 return 0;
6703 }
6704 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6705 }
6706#endif
6707
6708/* Do we do this right?
6709 * bash-3.00# sleep 20 | false
6710 * <ctrl-Z pressed>
6711 * [3]+ Stopped sleep 20 | false
6712 * bash-3.00# echo $?
6713 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6714 * [hush 1.14.0: yes we do it right]
6715 */
6716 wait_more:
6717 while (1) {
6718 int i;
6719 int dead;
6720
6721#if ENABLE_HUSH_FAST
6722 i = G.count_SIGCHLD;
6723#endif
6724 childpid = waitpid(-1, &status, attributes);
6725 if (childpid <= 0) {
6726 if (childpid && errno != ECHILD)
6727 bb_perror_msg("waitpid");
6728#if ENABLE_HUSH_FAST
6729 else { /* Until next SIGCHLD, waitpid's are useless */
6730 G.we_have_children = (childpid == 0);
6731 G.handled_SIGCHLD = i;
6732//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6733 }
6734#endif
6735 break;
6736 }
6737 dead = WIFEXITED(status) || WIFSIGNALED(status);
6738
6739#if DEBUG_JOBS
6740 if (WIFSTOPPED(status))
6741 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6742 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6743 if (WIFSIGNALED(status))
6744 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6745 childpid, WTERMSIG(status), WEXITSTATUS(status));
6746 if (WIFEXITED(status))
6747 debug_printf_jobs("pid %d exited, exitcode %d\n",
6748 childpid, WEXITSTATUS(status));
6749#endif
6750 /* Were we asked to wait for fg pipe? */
6751 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006752 i = fg_pipe->num_cmds;
6753 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006754 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6755 if (fg_pipe->cmds[i].pid != childpid)
6756 continue;
6757 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006758 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006759 fg_pipe->cmds[i].pid = 0;
6760 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006761 ex = WEXITSTATUS(status);
6762 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006763 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006764 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6765 */
6766 if (WIFSIGNALED(status)) {
6767 int sig = WTERMSIG(status);
6768 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006769 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6770 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6771 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006772 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6773 * Maybe we need to use sig | 128? */
6774 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006775 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006776 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006777 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006778 fg_pipe->stopped_cmds++;
6779 }
6780 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6781 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006782 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006783 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006784 i = fg_pipe->num_cmds;
6785 while (--i >= 0) {
6786 rcode = fg_pipe->cmds[i].cmd_exitcode;
6787 /* usually last process gives overall exitstatus,
6788 * but with "set -o pipefail", last *failed* process does */
6789 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6790 break;
6791 }
6792 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006793/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6794 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6795 * and "killall -STOP cat" */
6796 if (G_interactive_fd) {
6797#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006798 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006799 insert_bg_job(fg_pipe);
6800#endif
6801 return rcode;
6802 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006803 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006804 return rcode;
6805 }
6806 /* There are still running processes in the fg pipe */
6807 goto wait_more; /* do waitpid again */
6808 }
6809 /* it wasnt fg_pipe, look for process in bg pipes */
6810 }
6811
6812#if ENABLE_HUSH_JOB
6813 /* We asked to wait for bg or orphaned children */
6814 /* No need to remember exitcode in this case */
6815 for (pi = G.job_list; pi; pi = pi->next) {
6816 for (i = 0; i < pi->num_cmds; i++) {
6817 if (pi->cmds[i].pid == childpid)
6818 goto found_pi_and_prognum;
6819 }
6820 }
6821 /* Happens when shell is used as init process (init=/bin/sh) */
6822 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6823 continue; /* do waitpid again */
6824
6825 found_pi_and_prognum:
6826 if (dead) {
6827 /* child exited */
6828 pi->cmds[i].pid = 0;
6829 pi->alive_cmds--;
6830 if (!pi->alive_cmds) {
6831 if (G_interactive_fd)
6832 printf(JOB_STATUS_FORMAT, pi->jobid,
6833 "Done", pi->cmdtext);
6834 delete_finished_bg_job(pi);
6835 }
6836 } else {
6837 /* child stopped */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006838 pi->stopped_cmds++;
6839 }
6840#endif
6841 } /* while (waitpid succeeds)... */
6842
6843 return rcode;
6844}
6845
6846#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006847static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006848{
6849 pid_t p;
6850 int rcode = checkjobs(fg_pipe);
6851 if (G_saved_tty_pgrp) {
6852 /* Job finished, move the shell to the foreground */
6853 p = getpgrp(); /* our process group id */
6854 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6855 tcsetpgrp(G_interactive_fd, p);
6856 }
6857 return rcode;
6858}
6859#endif
6860
6861/* Start all the jobs, but don't wait for anything to finish.
6862 * See checkjobs().
6863 *
6864 * Return code is normally -1, when the caller has to wait for children
6865 * to finish to determine the exit status of the pipe. If the pipe
6866 * is a simple builtin command, however, the action is done by the
6867 * time run_pipe returns, and the exit code is provided as the
6868 * return value.
6869 *
6870 * Returns -1 only if started some children. IOW: we have to
6871 * mask out retvals of builtins etc with 0xff!
6872 *
6873 * The only case when we do not need to [v]fork is when the pipe
6874 * is single, non-backgrounded, non-subshell command. Examples:
6875 * cmd ; ... { list } ; ...
6876 * cmd && ... { list } && ...
6877 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006878 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006879 * or (if SH_STANDALONE) an applet, and we can run the { list }
6880 * with run_list. If it isn't one of these, we fork and exec cmd.
6881 *
6882 * Cases when we must fork:
6883 * non-single: cmd | cmd
6884 * backgrounded: cmd & { list } &
6885 * subshell: ( list ) [&]
6886 */
6887#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006888#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006889 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6890#endif
6891static int redirect_and_varexp_helper(char ***new_env_p,
6892 struct variable **old_vars_p,
6893 struct command *command,
6894 int squirrel[3],
6895 char **argv_expanded)
6896{
6897 /* setup_redirects acts on file descriptors, not FILEs.
6898 * This is perfect for work that comes after exec().
6899 * Is it really safe for inline use? Experimentally,
6900 * things seem to work. */
6901 int rcode = setup_redirects(command, squirrel);
6902 if (rcode == 0) {
6903 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6904 *new_env_p = new_env;
6905 dump_cmd_in_x_mode(new_env);
6906 dump_cmd_in_x_mode(argv_expanded);
6907 if (old_vars_p)
6908 *old_vars_p = set_vars_and_save_old(new_env);
6909 }
6910 return rcode;
6911}
6912static NOINLINE int run_pipe(struct pipe *pi)
6913{
6914 static const char *const null_ptr = NULL;
6915
6916 int cmd_no;
6917 int next_infd;
6918 struct command *command;
6919 char **argv_expanded;
6920 char **argv;
6921 /* it is not always needed, but we aim to smaller code */
6922 int squirrel[] = { -1, -1, -1 };
6923 int rcode;
6924
6925 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6926 debug_enter();
6927
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006928 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6929 * Result should be 3 lines: q w e, qwe, q w e
6930 */
6931 G.ifs = get_local_var_value("IFS");
6932 if (!G.ifs)
6933 G.ifs = defifs;
6934
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006935 IF_HUSH_JOB(pi->pgrp = -1;)
6936 pi->stopped_cmds = 0;
6937 command = &pi->cmds[0];
6938 argv_expanded = NULL;
6939
6940 if (pi->num_cmds != 1
6941 || pi->followup == PIPE_BG
6942 || command->cmd_type == CMD_SUBSHELL
6943 ) {
6944 goto must_fork;
6945 }
6946
6947 pi->alive_cmds = 1;
6948
6949 debug_printf_exec(": group:%p argv:'%s'\n",
6950 command->group, command->argv ? command->argv[0] : "NONE");
6951
6952 if (command->group) {
6953#if ENABLE_HUSH_FUNCTIONS
6954 if (command->cmd_type == CMD_FUNCDEF) {
6955 /* "executing" func () { list } */
6956 struct function *funcp;
6957
6958 funcp = new_function(command->argv[0]);
6959 /* funcp->name is already set to argv[0] */
6960 funcp->body = command->group;
6961# if !BB_MMU
6962 funcp->body_as_string = command->group_as_string;
6963 command->group_as_string = NULL;
6964# endif
6965 command->group = NULL;
6966 command->argv[0] = NULL;
6967 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6968 funcp->parent_cmd = command;
6969 command->child_func = funcp;
6970
6971 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6972 debug_leave();
6973 return EXIT_SUCCESS;
6974 }
6975#endif
6976 /* { list } */
6977 debug_printf("non-subshell group\n");
6978 rcode = 1; /* exitcode if redir failed */
6979 if (setup_redirects(command, squirrel) == 0) {
6980 debug_printf_exec(": run_list\n");
6981 rcode = run_list(command->group) & 0xff;
6982 }
6983 restore_redirects(squirrel);
6984 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6985 debug_leave();
6986 debug_printf_exec("run_pipe: return %d\n", rcode);
6987 return rcode;
6988 }
6989
6990 argv = command->argv ? command->argv : (char **) &null_ptr;
6991 {
6992 const struct built_in_command *x;
6993#if ENABLE_HUSH_FUNCTIONS
6994 const struct function *funcp;
6995#else
6996 enum { funcp = 0 };
6997#endif
6998 char **new_env = NULL;
6999 struct variable *old_vars = NULL;
7000
7001 if (argv[command->assignment_cnt] == NULL) {
7002 /* Assignments, but no command */
7003 /* Ensure redirects take effect (that is, create files).
7004 * Try "a=t >file" */
7005#if 0 /* A few cases in testsuite fail with this code. FIXME */
7006 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7007 /* Set shell variables */
7008 if (new_env) {
7009 argv = new_env;
7010 while (*argv) {
7011 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7012 /* Do we need to flag set_local_var() errors?
7013 * "assignment to readonly var" and "putenv error"
7014 */
7015 argv++;
7016 }
7017 }
7018 /* Redirect error sets $? to 1. Otherwise,
7019 * if evaluating assignment value set $?, retain it.
7020 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7021 if (rcode == 0)
7022 rcode = G.last_exitcode;
7023 /* Exit, _skipping_ variable restoring code: */
7024 goto clean_up_and_ret0;
7025
7026#else /* Older, bigger, but more correct code */
7027
7028 rcode = setup_redirects(command, squirrel);
7029 restore_redirects(squirrel);
7030 /* Set shell variables */
7031 if (G_x_mode)
7032 bb_putchar_stderr('+');
7033 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007034 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007035 if (G_x_mode)
7036 fprintf(stderr, " %s", p);
7037 debug_printf_exec("set shell var:'%s'->'%s'\n",
7038 *argv, p);
7039 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7040 /* Do we need to flag set_local_var() errors?
7041 * "assignment to readonly var" and "putenv error"
7042 */
7043 argv++;
7044 }
7045 if (G_x_mode)
7046 bb_putchar_stderr('\n');
7047 /* Redirect error sets $? to 1. Otherwise,
7048 * if evaluating assignment value set $?, retain it.
7049 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7050 if (rcode == 0)
7051 rcode = G.last_exitcode;
7052 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7053 debug_leave();
7054 debug_printf_exec("run_pipe: return %d\n", rcode);
7055 return rcode;
7056#endif
7057 }
7058
7059 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007060#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007061 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007062 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007063 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007064#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007065 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007066 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7067 }
7068
7069 /* if someone gives us an empty string: `cmd with empty output` */
7070 if (!argv_expanded[0]) {
7071 free(argv_expanded);
7072 debug_leave();
7073 return G.last_exitcode;
7074 }
7075
7076 x = find_builtin(argv_expanded[0]);
7077#if ENABLE_HUSH_FUNCTIONS
7078 funcp = NULL;
7079 if (!x)
7080 funcp = find_function(argv_expanded[0]);
7081#endif
7082 if (x || funcp) {
7083 if (!funcp) {
7084 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7085 debug_printf("exec with redirects only\n");
7086 rcode = setup_redirects(command, NULL);
7087 goto clean_up_and_ret1;
7088 }
7089 }
7090 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7091 if (rcode == 0) {
7092 if (!funcp) {
7093 debug_printf_exec(": builtin '%s' '%s'...\n",
7094 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007095 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007096 rcode = x->b_function(argv_expanded) & 0xff;
7097 fflush_all();
7098 }
7099#if ENABLE_HUSH_FUNCTIONS
7100 else {
7101# if ENABLE_HUSH_LOCAL
7102 struct variable **sv;
7103 sv = G.shadowed_vars_pp;
7104 G.shadowed_vars_pp = &old_vars;
7105# endif
7106 debug_printf_exec(": function '%s' '%s'...\n",
7107 funcp->name, argv_expanded[1]);
7108 rcode = run_function(funcp, argv_expanded) & 0xff;
7109# if ENABLE_HUSH_LOCAL
7110 G.shadowed_vars_pp = sv;
7111# endif
7112 }
7113#endif
7114 }
7115 clean_up_and_ret:
7116 unset_vars(new_env);
7117 add_vars(old_vars);
7118/* clean_up_and_ret0: */
7119 restore_redirects(squirrel);
7120 clean_up_and_ret1:
7121 free(argv_expanded);
7122 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7123 debug_leave();
7124 debug_printf_exec("run_pipe return %d\n", rcode);
7125 return rcode;
7126 }
7127
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01007128 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007129 int n = find_applet_by_name(argv_expanded[0]);
7130 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7131 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7132 if (rcode == 0) {
7133 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7134 argv_expanded[0], argv_expanded[1]);
7135 rcode = run_nofork_applet(n, argv_expanded);
7136 }
7137 goto clean_up_and_ret;
7138 }
7139 }
7140 /* It is neither builtin nor applet. We must fork. */
7141 }
7142
7143 must_fork:
7144 /* NB: argv_expanded may already be created, and that
7145 * might include `cmd` runs! Do not rerun it! We *must*
7146 * use argv_expanded if it's non-NULL */
7147
7148 /* Going to fork a child per each pipe member */
7149 pi->alive_cmds = 0;
7150 next_infd = 0;
7151
7152 cmd_no = 0;
7153 while (cmd_no < pi->num_cmds) {
7154 struct fd_pair pipefds;
7155#if !BB_MMU
7156 volatile nommu_save_t nommu_save;
7157 nommu_save.new_env = NULL;
7158 nommu_save.old_vars = NULL;
7159 nommu_save.argv = NULL;
7160 nommu_save.argv_from_re_execing = NULL;
7161#endif
7162 command = &pi->cmds[cmd_no];
7163 cmd_no++;
7164 if (command->argv) {
7165 debug_printf_exec(": pipe member '%s' '%s'...\n",
7166 command->argv[0], command->argv[1]);
7167 } else {
7168 debug_printf_exec(": pipe member with no argv\n");
7169 }
7170
7171 /* pipes are inserted between pairs of commands */
7172 pipefds.rd = 0;
7173 pipefds.wr = 1;
7174 if (cmd_no < pi->num_cmds)
7175 xpiped_pair(pipefds);
7176
7177 command->pid = BB_MMU ? fork() : vfork();
7178 if (!command->pid) { /* child */
7179#if ENABLE_HUSH_JOB
7180 disable_restore_tty_pgrp_on_exit();
7181 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7182
7183 /* Every child adds itself to new process group
7184 * with pgid == pid_of_first_child_in_pipe */
7185 if (G.run_list_level == 1 && G_interactive_fd) {
7186 pid_t pgrp;
7187 pgrp = pi->pgrp;
7188 if (pgrp < 0) /* true for 1st process only */
7189 pgrp = getpid();
7190 if (setpgid(0, pgrp) == 0
7191 && pi->followup != PIPE_BG
7192 && G_saved_tty_pgrp /* we have ctty */
7193 ) {
7194 /* We do it in *every* child, not just first,
7195 * to avoid races */
7196 tcsetpgrp(G_interactive_fd, pgrp);
7197 }
7198 }
7199#endif
7200 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7201 /* 1st cmd in backgrounded pipe
7202 * should have its stdin /dev/null'ed */
7203 close(0);
7204 if (open(bb_dev_null, O_RDONLY))
7205 xopen("/", O_RDONLY);
7206 } else {
7207 xmove_fd(next_infd, 0);
7208 }
7209 xmove_fd(pipefds.wr, 1);
7210 if (pipefds.rd > 1)
7211 close(pipefds.rd);
7212 /* Like bash, explicit redirects override pipes,
7213 * and the pipe fd is available for dup'ing. */
7214 if (setup_redirects(command, NULL))
7215 _exit(1);
7216
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007217 /* Stores to nommu_save list of env vars putenv'ed
7218 * (NOMMU, on MMU we don't need that) */
7219 /* cast away volatility... */
7220 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7221 /* pseudo_exec() does not return */
7222 }
7223
7224 /* parent or error */
7225#if ENABLE_HUSH_FAST
7226 G.count_SIGCHLD++;
7227//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7228#endif
7229 enable_restore_tty_pgrp_on_exit();
7230#if !BB_MMU
7231 /* Clean up after vforked child */
7232 free(nommu_save.argv);
7233 free(nommu_save.argv_from_re_execing);
7234 unset_vars(nommu_save.new_env);
7235 add_vars(nommu_save.old_vars);
7236#endif
7237 free(argv_expanded);
7238 argv_expanded = NULL;
7239 if (command->pid < 0) { /* [v]fork failed */
7240 /* Clearly indicate, was it fork or vfork */
7241 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7242 } else {
7243 pi->alive_cmds++;
7244#if ENABLE_HUSH_JOB
7245 /* Second and next children need to know pid of first one */
7246 if (pi->pgrp < 0)
7247 pi->pgrp = command->pid;
7248#endif
7249 }
7250
7251 if (cmd_no > 1)
7252 close(next_infd);
7253 if (cmd_no < pi->num_cmds)
7254 close(pipefds.wr);
7255 /* Pass read (output) pipe end to next iteration */
7256 next_infd = pipefds.rd;
7257 }
7258
7259 if (!pi->alive_cmds) {
7260 debug_leave();
7261 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7262 return 1;
7263 }
7264
7265 debug_leave();
7266 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7267 return -1;
7268}
7269
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007270/* NB: called by pseudo_exec, and therefore must not modify any
7271 * global data until exec/_exit (we can be a child after vfork!) */
7272static int run_list(struct pipe *pi)
7273{
7274#if ENABLE_HUSH_CASE
7275 char *case_word = NULL;
7276#endif
7277#if ENABLE_HUSH_LOOPS
7278 struct pipe *loop_top = NULL;
7279 char **for_lcur = NULL;
7280 char **for_list = NULL;
7281#endif
7282 smallint last_followup;
7283 smalluint rcode;
7284#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7285 smalluint cond_code = 0;
7286#else
7287 enum { cond_code = 0 };
7288#endif
7289#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007290 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007291 smallint last_rword; /* ditto */
7292#endif
7293
7294 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7295 debug_enter();
7296
7297#if ENABLE_HUSH_LOOPS
7298 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007299 {
7300 struct pipe *cpipe;
7301 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7302 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7303 continue;
7304 /* current word is FOR or IN (BOLD in comments below) */
7305 if (cpipe->next == NULL) {
7306 syntax_error("malformed for");
7307 debug_leave();
7308 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7309 return 1;
7310 }
7311 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7312 if (cpipe->next->res_word == RES_DO)
7313 continue;
7314 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7315 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7316 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7317 ) {
7318 syntax_error("malformed for");
7319 debug_leave();
7320 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7321 return 1;
7322 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007323 }
7324 }
7325#endif
7326
7327 /* Past this point, all code paths should jump to ret: label
7328 * in order to return, no direct "return" statements please.
7329 * This helps to ensure that no memory is leaked. */
7330
7331#if ENABLE_HUSH_JOB
7332 G.run_list_level++;
7333#endif
7334
7335#if HAS_KEYWORDS
7336 rword = RES_NONE;
7337 last_rword = RES_XXXX;
7338#endif
7339 last_followup = PIPE_SEQ;
7340 rcode = G.last_exitcode;
7341
7342 /* Go through list of pipes, (maybe) executing them. */
7343 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7344 if (G.flag_SIGINT)
7345 break;
7346
7347 IF_HAS_KEYWORDS(rword = pi->res_word;)
7348 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7349 rword, cond_code, last_rword);
7350#if ENABLE_HUSH_LOOPS
7351 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7352 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7353 ) {
7354 /* start of a loop: remember where loop starts */
7355 loop_top = pi;
7356 G.depth_of_loop++;
7357 }
7358#endif
7359 /* Still in the same "if...", "then..." or "do..." branch? */
7360 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7361 if ((rcode == 0 && last_followup == PIPE_OR)
7362 || (rcode != 0 && last_followup == PIPE_AND)
7363 ) {
7364 /* It is "<true> || CMD" or "<false> && CMD"
7365 * and we should not execute CMD */
7366 debug_printf_exec("skipped cmd because of || or &&\n");
7367 last_followup = pi->followup;
Denys Vlasenko3beab832013-04-07 18:16:58 +02007368 goto dont_check_jobs_but_continue;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007369 }
7370 }
7371 last_followup = pi->followup;
7372 IF_HAS_KEYWORDS(last_rword = rword;)
7373#if ENABLE_HUSH_IF
7374 if (cond_code) {
7375 if (rword == RES_THEN) {
7376 /* if false; then ... fi has exitcode 0! */
7377 G.last_exitcode = rcode = EXIT_SUCCESS;
7378 /* "if <false> THEN cmd": skip cmd */
7379 continue;
7380 }
7381 } else {
7382 if (rword == RES_ELSE || rword == RES_ELIF) {
7383 /* "if <true> then ... ELSE/ELIF cmd":
7384 * skip cmd and all following ones */
7385 break;
7386 }
7387 }
7388#endif
7389#if ENABLE_HUSH_LOOPS
7390 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7391 if (!for_lcur) {
7392 /* first loop through for */
7393
7394 static const char encoded_dollar_at[] ALIGN1 = {
7395 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7396 }; /* encoded representation of "$@" */
7397 static const char *const encoded_dollar_at_argv[] = {
7398 encoded_dollar_at, NULL
7399 }; /* argv list with one element: "$@" */
7400 char **vals;
7401
7402 vals = (char**)encoded_dollar_at_argv;
7403 if (pi->next->res_word == RES_IN) {
7404 /* if no variable values after "in" we skip "for" */
7405 if (!pi->next->cmds[0].argv) {
7406 G.last_exitcode = rcode = EXIT_SUCCESS;
7407 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7408 break;
7409 }
7410 vals = pi->next->cmds[0].argv;
7411 } /* else: "for var; do..." -> assume "$@" list */
7412 /* create list of variable values */
7413 debug_print_strings("for_list made from", vals);
7414 for_list = expand_strvec_to_strvec(vals);
7415 for_lcur = for_list;
7416 debug_print_strings("for_list", for_list);
7417 }
7418 if (!*for_lcur) {
7419 /* "for" loop is over, clean up */
7420 free(for_list);
7421 for_list = NULL;
7422 for_lcur = NULL;
7423 break;
7424 }
7425 /* Insert next value from for_lcur */
7426 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7427 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7428 continue;
7429 }
7430 if (rword == RES_IN) {
7431 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7432 }
7433 if (rword == RES_DONE) {
7434 continue; /* "done" has no cmds too */
7435 }
7436#endif
7437#if ENABLE_HUSH_CASE
7438 if (rword == RES_CASE) {
7439 case_word = expand_strvec_to_string(pi->cmds->argv);
7440 continue;
7441 }
7442 if (rword == RES_MATCH) {
7443 char **argv;
7444
7445 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7446 break;
7447 /* all prev words didn't match, does this one match? */
7448 argv = pi->cmds->argv;
7449 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007450 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007451 /* TODO: which FNM_xxx flags to use? */
7452 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7453 free(pattern);
7454 if (cond_code == 0) { /* match! we will execute this branch */
7455 free(case_word); /* make future "word)" stop */
7456 case_word = NULL;
7457 break;
7458 }
7459 argv++;
7460 }
7461 continue;
7462 }
7463 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7464 if (cond_code != 0)
7465 continue; /* not matched yet, skip this pipe */
7466 }
7467#endif
7468 /* Just pressing <enter> in shell should check for jobs.
7469 * OTOH, in non-interactive shell this is useless
7470 * and only leads to extra job checks */
7471 if (pi->num_cmds == 0) {
7472 if (G_interactive_fd)
7473 goto check_jobs_and_continue;
7474 continue;
7475 }
7476
7477 /* After analyzing all keywords and conditions, we decided
7478 * to execute this pipe. NB: have to do checkjobs(NULL)
7479 * after run_pipe to collect any background children,
7480 * even if list execution is to be stopped. */
7481 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7482 {
7483 int r;
7484#if ENABLE_HUSH_LOOPS
7485 G.flag_break_continue = 0;
7486#endif
7487 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7488 if (r != -1) {
7489 /* We ran a builtin, function, or group.
7490 * rcode is already known
7491 * and we don't need to wait for anything. */
7492 G.last_exitcode = rcode;
7493 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007494 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007495#if ENABLE_HUSH_LOOPS
7496 /* Was it "break" or "continue"? */
7497 if (G.flag_break_continue) {
7498 smallint fbc = G.flag_break_continue;
7499 /* We might fall into outer *loop*,
7500 * don't want to break it too */
7501 if (loop_top) {
7502 G.depth_break_continue--;
7503 if (G.depth_break_continue == 0)
7504 G.flag_break_continue = 0;
7505 /* else: e.g. "continue 2" should *break* once, *then* continue */
7506 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denys Vlasenko3beab832013-04-07 18:16:58 +02007507 if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
7508 checkjobs(NULL);
7509 break;
7510 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007511 /* "continue": simulate end of loop */
7512 rword = RES_DONE;
7513 continue;
7514 }
7515#endif
7516#if ENABLE_HUSH_FUNCTIONS
7517 if (G.flag_return_in_progress == 1) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007518 checkjobs(NULL);
7519 break;
7520 }
7521#endif
7522 } else if (pi->followup == PIPE_BG) {
7523 /* What does bash do with attempts to background builtins? */
7524 /* even bash 3.2 doesn't do that well with nested bg:
7525 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7526 * I'm NOT treating inner &'s as jobs */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007527 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007528#if ENABLE_HUSH_JOB
7529 if (G.run_list_level == 1)
7530 insert_bg_job(pi);
7531#endif
7532 /* Last command's pid goes to $! */
7533 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7534 G.last_exitcode = rcode = EXIT_SUCCESS;
7535 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7536 } else {
7537#if ENABLE_HUSH_JOB
7538 if (G.run_list_level == 1 && G_interactive_fd) {
7539 /* Waits for completion, then fg's main shell */
7540 rcode = checkjobs_and_fg_shell(pi);
7541 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007542 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007543 } else
7544#endif
7545 { /* This one just waits for completion */
7546 rcode = checkjobs(pi);
7547 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007548 check_and_run_traps();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007549 }
7550 G.last_exitcode = rcode;
7551 }
7552 }
7553
7554 /* Analyze how result affects subsequent commands */
7555#if ENABLE_HUSH_IF
7556 if (rword == RES_IF || rword == RES_ELIF)
7557 cond_code = rcode;
7558#endif
Denys Vlasenko3beab832013-04-07 18:16:58 +02007559 check_jobs_and_continue:
7560 checkjobs(NULL);
7561 dont_check_jobs_but_continue: ;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007562#if ENABLE_HUSH_LOOPS
7563 /* Beware of "while false; true; do ..."! */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007564 if (pi->next
7565 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
Denys Vlasenko56a3b822011-06-01 12:47:07 +02007566 /* check for RES_DONE is needed for "while ...; do \n done" case */
Denys Vlasenko00ae9892011-05-31 17:35:45 +02007567 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007568 if (rword == RES_WHILE) {
7569 if (rcode) {
7570 /* "while false; do...done" - exitcode 0 */
7571 G.last_exitcode = rcode = EXIT_SUCCESS;
7572 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
Denys Vlasenko3beab832013-04-07 18:16:58 +02007573 break;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007574 }
7575 }
7576 if (rword == RES_UNTIL) {
7577 if (!rcode) {
7578 debug_printf_exec(": until expr is true: breaking\n");
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007579 break;
7580 }
7581 }
7582 }
7583#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007584 } /* for (pi) */
7585
7586#if ENABLE_HUSH_JOB
7587 G.run_list_level--;
7588#endif
7589#if ENABLE_HUSH_LOOPS
7590 if (loop_top)
7591 G.depth_of_loop--;
7592 free(for_list);
7593#endif
7594#if ENABLE_HUSH_CASE
7595 free(case_word);
7596#endif
7597 debug_leave();
7598 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7599 return rcode;
7600}
7601
7602/* Select which version we will use */
7603static int run_and_free_list(struct pipe *pi)
7604{
7605 int rcode = 0;
7606 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007607 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007608 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7609 rcode = run_list(pi);
7610 }
7611 /* free_pipe_list has the side effect of clearing memory.
7612 * In the long run that function can be merged with run_list,
7613 * but doing that now would hobble the debugging effort. */
7614 free_pipe_list(pi);
7615 debug_printf_exec("run_and_free_list return %d\n", rcode);
7616 return rcode;
7617}
7618
7619
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007620static void install_sighandlers(unsigned mask)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007621{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007622 sighandler_t old_handler;
7623 unsigned sig = 0;
7624 while ((mask >>= 1) != 0) {
7625 sig++;
7626 if (!(mask & 1))
7627 continue;
Denys Vlasenko0806e402011-05-12 23:06:20 +02007628 old_handler = install_sighandler(sig, pick_sighandler(sig));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007629 /* POSIX allows shell to re-enable SIGCHLD
7630 * even if it was SIG_IGN on entry.
7631 * Therefore we skip IGN check for it:
7632 */
7633 if (sig == SIGCHLD)
7634 continue;
7635 if (old_handler == SIG_IGN) {
7636 /* oops... restore back to IGN, and record this fact */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007637 install_sighandler(sig, old_handler);
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007638 if (!G.traps)
7639 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7640 free(G.traps[sig]);
7641 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7642 }
7643 }
7644}
7645
7646/* Called a few times only (or even once if "sh -c") */
7647static void install_special_sighandlers(void)
7648{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007649 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007650
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007651 /* Which signals are shell-special? */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007652 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007653 if (G_interactive_fd) {
7654 mask |= SPECIAL_INTERACTIVE_SIGS;
7655 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007656 mask |= SPECIAL_JOBSTOP_SIGS;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007657 }
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007658 /* Careful, do not re-install handlers we already installed */
7659 if (G.special_sig_mask != mask) {
7660 unsigned diff = mask & ~G.special_sig_mask;
7661 G.special_sig_mask = mask;
7662 install_sighandlers(diff);
7663 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007664}
7665
7666#if ENABLE_HUSH_JOB
7667/* helper */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007668/* Set handlers to restore tty pgrp and exit */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007669static void install_fatal_sighandlers(void)
Denis Vlasenkof9375282009-04-05 19:13:39 +00007670{
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007671 unsigned mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007672
7673 /* We will restore tty pgrp on these signals */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007674 mask = 0
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007675 + (1 << SIGILL ) * HUSH_DEBUG
7676 + (1 << SIGFPE ) * HUSH_DEBUG
7677 + (1 << SIGBUS ) * HUSH_DEBUG
7678 + (1 << SIGSEGV) * HUSH_DEBUG
7679 + (1 << SIGTRAP) * HUSH_DEBUG
7680 + (1 << SIGABRT)
7681 /* bash 3.2 seems to handle these just like 'fatal' ones */
7682 + (1 << SIGPIPE)
7683 + (1 << SIGALRM)
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007684 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007685 * if we aren't interactive... but in this case
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007686 * we never want to restore pgrp on exit, and this fn is not called
7687 */
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007688 /*+ (1 << SIGHUP )*/
7689 /*+ (1 << SIGTERM)*/
7690 /*+ (1 << SIGINT )*/
7691 ;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007692 G_fatal_sig_mask = mask;
Denys Vlasenko54e9e122011-05-09 00:52:15 +02007693
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007694 install_sighandlers(mask);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007695}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007696#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007697
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007698static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007699{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007700 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007701 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007702 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007703 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007704 break;
7705 case 'x':
7706 IF_HUSH_MODE_X(G_x_mode = state;)
7707 break;
7708 case 'o':
7709 if (!o_opt) {
7710 /* "set -+o" without parameter.
7711 * in bash, set -o produces this output:
7712 * pipefail off
7713 * and set +o:
7714 * set +o pipefail
7715 * We always use the second form.
7716 */
7717 const char *p = o_opt_strings;
7718 idx = 0;
7719 while (*p) {
7720 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7721 idx++;
7722 p += strlen(p) + 1;
7723 }
7724 break;
7725 }
7726 idx = index_in_strings(o_opt_strings, o_opt);
7727 if (idx >= 0) {
7728 G.o_opt[idx] = state;
7729 break;
7730 }
7731 default:
7732 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007733 }
7734 return EXIT_SUCCESS;
7735}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007736
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007737int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007738int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007739{
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007740 enum {
7741 OPT_login = (1 << 0),
7742 };
7743 unsigned flags;
Eric Andersen25f27032001-04-26 23:22:31 +00007744 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007745 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007746 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007747 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007748 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007749
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007750 INIT_G();
Denys Vlasenko10c01312011-05-11 11:49:21 +02007751 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007752 G.last_exitcode = EXIT_SUCCESS;
Denys Vlasenko10c01312011-05-11 11:49:21 +02007753#if ENABLE_HUSH_FAST
7754 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7755#endif
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007756#if !BB_MMU
7757 G.argv0_for_re_execing = argv[0];
7758#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007759 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007760 shell_ver = xzalloc(sizeof(*shell_ver));
7761 shell_ver->flg_export = 1;
7762 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007763 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007764 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007765 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007766 /* Create shell local variables from the values
7767 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007768 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007769 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007770 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007771 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007772 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007773 if (e) while (*e) {
7774 char *value = strchr(*e, '=');
7775 if (value) { /* paranoia */
7776 cur_var->next = xzalloc(sizeof(*cur_var));
7777 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007778 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007779 cur_var->max_len = strlen(*e);
7780 cur_var->flg_export = 1;
7781 }
7782 e++;
7783 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007784 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007785 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7786 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007787
7788 /* Export PWD */
7789 set_pwd_var(/*exp:*/ 1);
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02007790
7791#if ENABLE_HUSH_BASH_COMPAT
7792 /* Set (but not export) HOSTNAME unless already set */
7793 if (!get_local_var_value("HOSTNAME")) {
7794 struct utsname uts;
7795 uname(&uts);
7796 set_local_var_from_halves("HOSTNAME", uts.nodename);
7797 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007798 /* bash also exports SHLVL and _,
7799 * and sets (but doesn't export) the following variables:
7800 * BASH=/bin/bash
7801 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7802 * BASH_VERSION='3.2.0(1)-release'
7803 * HOSTTYPE=i386
7804 * MACHTYPE=i386-pc-linux-gnu
7805 * OSTYPE=linux-gnu
Denys Vlasenkodea47882009-10-09 15:40:49 +02007806 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007807 * EUID=<NNNNN>
7808 * UID=<NNNNN>
7809 * GROUPS=()
7810 * LINES=<NNN>
7811 * COLUMNS=<NNN>
7812 * BASH_ARGC=()
7813 * BASH_ARGV=()
7814 * BASH_LINENO=()
7815 * BASH_SOURCE=()
7816 * DIRSTACK=()
7817 * PIPESTATUS=([0]="0")
7818 * HISTFILE=/<xxx>/.bash_history
7819 * HISTFILESIZE=500
7820 * HISTSIZE=500
7821 * MAILCHECK=60
7822 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7823 * SHELL=/bin/bash
7824 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7825 * TERM=dumb
7826 * OPTERR=1
7827 * OPTIND=1
7828 * IFS=$' \t\n'
7829 * PS1='\s-\v\$ '
7830 * PS2='> '
7831 * PS4='+ '
7832 */
Denys Vlasenko3fa97af2014-04-15 11:43:29 +02007833#endif
Denys Vlasenko6db47842009-09-05 20:15:17 +02007834
Denis Vlasenko38f63192007-01-22 09:03:07 +00007835#if ENABLE_FEATURE_EDITING
Denys Vlasenkoe45af7a2011-09-04 16:15:24 +02007836 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007837#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007838
Eric Andersen94ac2442001-05-22 19:05:18 +00007839 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007840 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007841
Denis Vlasenkoed782372009-04-10 00:45:02 +00007842 if (setjmp(die_jmp)) {
7843 /* xfunc has failed! die die die */
7844 /* no EXIT traps, this is an escape hatch! */
7845 G.exiting = 1;
7846 hush_exit(xfunc_error_retval);
7847 }
7848
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007849 /* Shell is non-interactive at first. We need to call
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007850 * install_special_sighandlers() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007851 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007852 * If we later decide that we are interactive, we run install_special_sighandlers()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007853 * in order to intercept (more) signals.
7854 */
7855
7856 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007857 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007858 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007859 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007860 while (1) {
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007861 opt = getopt(argc, argv, "+c:xinsl"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007862#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007863 "<:$:R:V:"
7864# if ENABLE_HUSH_FUNCTIONS
7865 "F:"
7866# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007867#endif
7868 );
7869 if (opt <= 0)
7870 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007871 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007872 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007873 /* Possibilities:
7874 * sh ... -c 'script'
7875 * sh ... -c 'script' ARG0 [ARG1...]
7876 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007877 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007878 * "" needs to be replaced with NULL
7879 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007880 * Note: the form without ARG0 never happens:
7881 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007882 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007883 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007884 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007885 G.root_ppid = getppid();
7886 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007887 G.global_argv = argv + optind;
7888 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007889 if (builtin_argc) {
7890 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7891 const struct built_in_command *x;
7892
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007893 install_special_sighandlers();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007894 x = find_builtin(optarg);
7895 if (x) { /* paranoia */
7896 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7897 G.global_argv += builtin_argc;
7898 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007899 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007900 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007901 }
7902 goto final_return;
7903 }
7904 if (!G.global_argv[0]) {
7905 /* -c 'script' (no params): prevent empty $0 */
7906 G.global_argv--; /* points to argv[i] of 'script' */
7907 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007908 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007909 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007910 install_special_sighandlers();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007911 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007912 goto final_return;
7913 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007914 /* Well, we cannot just declare interactiveness,
7915 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007916 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007917 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007918 case 's':
7919 /* "-s" means "read from stdin", but this is how we always
7920 * operate, so simply do nothing here. */
7921 break;
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007922 case 'l':
7923 flags |= OPT_login;
7924 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007925#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007926 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007927 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007928 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007929 case '$': {
7930 unsigned long long empty_trap_mask;
7931
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007932 G.root_pid = bb_strtou(optarg, &optarg, 16);
7933 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007934 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7935 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007936 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7937 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007938 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007939 optarg++;
7940 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007941 optarg++;
7942 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7943 if (empty_trap_mask != 0) {
7944 int sig;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02007945 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007946 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7947 for (sig = 1; sig < NSIG; sig++) {
7948 if (empty_trap_mask & (1LL << sig)) {
7949 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
Denys Vlasenko0806e402011-05-12 23:06:20 +02007950 install_sighandler(sig, SIG_IGN);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007951 }
7952 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007953 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007954# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007955 optarg++;
7956 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007957# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007958 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007959 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007960 case 'R':
7961 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007962 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007963 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007964# if ENABLE_HUSH_FUNCTIONS
7965 case 'F': {
7966 struct function *funcp = new_function(optarg);
7967 /* funcp->name is already set to optarg */
7968 /* funcp->body is set to NULL. It's a special case. */
7969 funcp->body_as_string = argv[optind];
7970 optind++;
7971 break;
7972 }
7973# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007974#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007975 case 'n':
7976 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007977 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007978 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007979 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007980#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007981 fprintf(stderr, "Usage: sh [FILE]...\n"
7982 " or: sh -c command [args]...\n\n");
7983 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007984#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007985 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007986#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007987 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007988 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007989
Denys Vlasenkof58f7052011-05-12 02:10:33 +02007990 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7991 G.global_argc = argc - (optind - 1);
7992 G.global_argv = argv + (optind - 1);
7993 G.global_argv[0] = argv[0];
7994
Denys Vlasenkodea47882009-10-09 15:40:49 +02007995 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007996 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007997 G.root_ppid = getppid();
7998 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007999
8000 /* If we are login shell... */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008001 if (flags & OPT_login) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008002 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008003 debug_printf("sourcing /etc/profile\n");
8004 input = fopen_for_read("/etc/profile");
8005 if (input != NULL) {
8006 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008007 install_special_sighandlers();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008008 parse_and_run_file(input);
8009 fclose(input);
8010 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008011 /* bash: after sourcing /etc/profile,
8012 * tries to source (in the given order):
8013 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008014 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00008015 * bash also sources ~/.bash_logout on exit.
8016 * If called as sh, skips .bash_XXX files.
8017 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00008018 }
8019
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008020 if (G.global_argv[1]) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008021 FILE *input;
8022 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00008023 * "bash <script>" (which is never interactive (unless -i?))
8024 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00008025 * If called as sh, does the same but with $ENV.
8026 */
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008027 G.global_argc--;
8028 G.global_argv++;
8029 debug_printf("running script '%s'\n", G.global_argv[0]);
8030 input = xfopen_for_read(G.global_argv[0]);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008031 close_on_exec_on(fileno(input));
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008032 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008033 parse_and_run_file(input);
8034#if ENABLE_FEATURE_CLEAN_UP
8035 fclose(input);
8036#endif
8037 goto final_return;
8038 }
8039
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008040 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008041 * NB: don't forget to (re)run install_special_sighandlers() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00008042 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00008043
Denys Vlasenko28a105d2009-06-01 11:26:30 +02008044 /* A shell is interactive if the '-i' flag was given,
8045 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00008046 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00008047 * no arguments remaining or the -s flag given
8048 * standard input is a terminal
8049 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00008050 * Refer to Posix.2, the description of the 'sh' utility.
8051 */
8052#if ENABLE_HUSH_JOB
8053 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04008054 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8055 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8056 if (G_saved_tty_pgrp < 0)
8057 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008058
8059 /* try to dup stdin to high fd#, >= 255 */
8060 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8061 if (G_interactive_fd < 0) {
8062 /* try to dup to any fd */
8063 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008064 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008065 /* give up */
8066 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04008067 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00008068 }
8069 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008070// TODO: track & disallow any attempts of user
8071// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00008072 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008073 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008074 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008075 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008076
Mike Frysinger38478a62009-05-20 04:48:06 -04008077 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008078 /* If we were run as 'hush &', sleep until we are
8079 * in the foreground (tty pgrp == our pgrp).
8080 * If we get started under a job aware app (like bash),
8081 * make sure we are now in charge so we don't fight over
8082 * who gets the foreground */
8083 while (1) {
8084 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04008085 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8086 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008087 break;
8088 /* send TTIN to ourself (should stop us) */
8089 kill(- shell_pgrp, SIGTTIN);
8090 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00008091 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008092
Denys Vlasenkof58f7052011-05-12 02:10:33 +02008093 /* Install more signal handlers */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008094 install_special_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008095
Mike Frysinger38478a62009-05-20 04:48:06 -04008096 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008097 /* Set other signals to restore saved_tty_pgrp */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008098 install_fatal_sighandlers();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008099 /* Put ourselves in our own process group
8100 * (bash, too, does this only if ctty is available) */
8101 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8102 /* Grab control of the terminal */
8103 tcsetpgrp(G_interactive_fd, getpid());
8104 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00008105 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00008106 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00008107 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008108
8109# if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8110 {
8111 const char *hp = get_local_var_value("HISTFILE");
8112 if (!hp) {
8113 hp = get_local_var_value("HOME");
8114 if (hp)
8115 hp = concat_path_file(hp, ".hush_history");
8116 } else {
8117 hp = xstrdup(hp);
8118 }
8119 if (hp) {
8120 G.line_input_state->hist_file = hp;
Denys Vlasenko4840ae82011-09-04 15:28:03 +02008121 //set_local_var(xasprintf("HISTFILE=%s", ...));
8122 }
8123# if ENABLE_FEATURE_SH_HISTFILESIZE
8124 hp = get_local_var_value("HISTFILESIZE");
8125 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8126# endif
8127 }
8128# endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008129 } else {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008130 install_special_sighandlers();
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008131 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008132#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00008133 /* No job control compiled in, only prompt/line editing */
8134 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008135 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8136 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008137 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008138 G_interactive_fd = dup(STDIN_FILENO);
8139 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008140 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008141 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00008142 }
8143 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008144 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00008145 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00008146 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008147 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008148#else
8149 /* We have interactiveness code disabled */
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008150 install_special_sighandlers();
Denis Vlasenkof9375282009-04-05 19:13:39 +00008151#endif
8152 /* bash:
8153 * if interactive but not a login shell, sources ~/.bashrc
8154 * (--norc turns this off, --rcfile <file> overrides)
8155 */
8156
8157 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008158 /* note: ash and hush share this string */
8159 printf("\n\n%s %s\n"
8160 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8161 "\n",
8162 bb_banner,
8163 "hush - the humble shell"
8164 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00008165 }
8166
Denis Vlasenkof9375282009-04-05 19:13:39 +00008167 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00008168
Denis Vlasenkod76c0492007-05-25 02:16:25 +00008169 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008170 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00008171}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00008172
8173
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02008174#if ENABLE_MSH
8175int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8176int msh_main(int argc, char **argv)
8177{
8178 //bb_error_msg("msh is deprecated, please use hush instead");
8179 return hush_main(argc, argv);
8180}
8181#endif
8182
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008183
8184/*
8185 * Built-ins
8186 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008187static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008188{
8189 return 0;
8190}
8191
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008192static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008193{
8194 int argc = 0;
8195 while (*argv) {
8196 argc++;
8197 argv++;
8198 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02008199 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04008200}
8201
8202static int FAST_FUNC builtin_test(char **argv)
8203{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008204 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008205}
8206
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008207static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008208{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008209 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008210}
8211
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008212#if ENABLE_PRINTF
8213static int FAST_FUNC builtin_printf(char **argv)
8214{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008215 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04008216}
8217#endif
8218
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008219static char **skip_dash_dash(char **argv)
8220{
8221 argv++;
8222 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8223 argv++;
8224 return argv;
8225}
8226
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008227static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008228{
8229 int rcode = EXIT_SUCCESS;
8230
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008231 argv = skip_dash_dash(argv);
8232 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008233 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008234 /* bash:
8235 * eval "echo Hi; done" ("done" is syntax error):
8236 * "echo Hi" will not execute too.
8237 */
8238 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008239 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008240 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008241 }
8242 return rcode;
8243}
8244
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008245static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008246{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008247 const char *newdir;
8248
8249 argv = skip_dash_dash(argv);
8250 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008251 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008252 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008253 * bash says "bash: cd: HOME not set" and does nothing
8254 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008255 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02008256 const char *home = get_local_var_value("HOME");
8257 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00008258 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008259 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008260 /* Mimic bash message exactly */
8261 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008262 return EXIT_FAILURE;
8263 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02008264 /* Read current dir (get_cwd(1) is inside) and set PWD.
8265 * Note: do not enforce exporting. If PWD was unset or unexported,
8266 * set it again, but do not export. bash does the same.
8267 */
8268 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008269 return EXIT_SUCCESS;
8270}
8271
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008272static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008273{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008274 argv = skip_dash_dash(argv);
8275 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008276 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008277
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008278 /* Careful: we can end up here after [v]fork. Do not restore
8279 * tty pgrp then, only top-level shell process does that */
8280 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8281 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8282
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008283 /* TODO: if exec fails, bash does NOT exit! We do.
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008284 * We'll need to undo trap cleanup (it's inside execvp_or_die)
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008285 * and tcsetpgrp, and this is inherently racy.
8286 */
8287 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008288}
8289
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008290static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008291{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008292 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008293
8294 /* interactive bash:
8295 * # trap "echo EEE" EXIT
8296 * # exit
8297 * exit
8298 * There are stopped jobs.
8299 * (if there are _stopped_ jobs, running ones don't count)
8300 * # exit
8301 * exit
Denys Vlasenko6830ade2013-01-15 13:58:01 +01008302 * EEE (then bash exits)
Denis Vlasenko40e84372009-04-18 11:23:38 +00008303 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008304 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008305 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008306
8307 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008308 argv = skip_dash_dash(argv);
8309 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008310 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008311 /* mimic bash: exit 123abc == exit 255 + error msg */
8312 xfunc_error_retval = 255;
8313 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008314 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008315}
8316
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008317static void print_escaped(const char *s)
8318{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008319 if (*s == '\'')
8320 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008321 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008322 const char *p = strchrnul(s, '\'');
8323 /* print 'xxxx', possibly just '' */
8324 printf("'%.*s'", (int)(p - s), s);
8325 if (*p == '\0')
8326 break;
8327 s = p;
8328 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008329 /* s points to '; print "'''...'''" */
8330 putchar('"');
8331 do putchar('\''); while (*++s == '\'');
8332 putchar('"');
8333 } while (*s);
8334}
8335
Denys Vlasenko295fef82009-06-03 12:47:26 +02008336#if !ENABLE_HUSH_LOCAL
8337#define helper_export_local(argv, exp, lvl) \
8338 helper_export_local(argv, exp)
8339#endif
8340static void helper_export_local(char **argv, int exp, int lvl)
8341{
8342 do {
8343 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008344 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008345
8346 /* So far we do not check that name is valid (TODO?) */
8347
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008348 if (*name_end == '\0') {
8349 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008350
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008351 vpp = get_ptr_to_local_var(name, name_end - name);
8352 var = vpp ? *vpp : NULL;
8353
Denys Vlasenko295fef82009-06-03 12:47:26 +02008354 if (exp == -1) { /* unexporting? */
8355 /* export -n NAME (without =VALUE) */
8356 if (var) {
8357 var->flg_export = 0;
8358 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8359 unsetenv(name);
8360 } /* else: export -n NOT_EXISTING_VAR: no-op */
8361 continue;
8362 }
8363 if (exp == 1) { /* exporting? */
8364 /* export NAME (without =VALUE) */
8365 if (var) {
8366 var->flg_export = 1;
8367 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8368 putenv(var->varstr);
8369 continue;
8370 }
8371 }
8372 /* Exporting non-existing variable.
8373 * bash does not put it in environment,
8374 * but remembers that it is exported,
8375 * and does put it in env when it is set later.
8376 * We just set it to "" and export. */
8377 /* Or, it's "local NAME" (without =VALUE).
8378 * bash sets the value to "". */
8379 name = xasprintf("%s=", name);
8380 } else {
8381 /* (Un)exporting/making local NAME=VALUE */
8382 name = xstrdup(name);
8383 }
8384 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8385 } while (*++argv);
8386}
8387
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008388static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008389{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008390 unsigned opt_unexport;
8391
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008392#if ENABLE_HUSH_EXPORT_N
8393 /* "!": do not abort on errors */
8394 opt_unexport = getopt32(argv, "!n");
8395 if (opt_unexport == (uint32_t)-1)
8396 return EXIT_FAILURE;
8397 argv += optind;
8398#else
8399 opt_unexport = 0;
8400 argv++;
8401#endif
8402
8403 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008404 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008405 if (e) {
8406 while (*e) {
8407#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008408 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008409#else
8410 /* ash emits: export VAR='VAL'
8411 * bash: declare -x VAR="VAL"
8412 * we follow ash example */
8413 const char *s = *e++;
8414 const char *p = strchr(s, '=');
8415
8416 if (!p) /* wtf? take next variable */
8417 continue;
8418 /* export var= */
8419 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008420 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008421 putchar('\n');
8422#endif
8423 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008424 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008425 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008426 return EXIT_SUCCESS;
8427 }
8428
Denys Vlasenko295fef82009-06-03 12:47:26 +02008429 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008430
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008431 return EXIT_SUCCESS;
8432}
8433
Denys Vlasenko295fef82009-06-03 12:47:26 +02008434#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008435static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008436{
8437 if (G.func_nest_level == 0) {
8438 bb_error_msg("%s: not in a function", argv[0]);
8439 return EXIT_FAILURE; /* bash compat */
8440 }
8441 helper_export_local(argv, 0, G.func_nest_level);
8442 return EXIT_SUCCESS;
8443}
8444#endif
8445
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008446static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008447{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008448 int sig;
8449 char *new_cmd;
8450
8451 if (!G.traps)
8452 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8453
8454 argv++;
8455 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008456 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008457 /* No args: print all trapped */
8458 for (i = 0; i < NSIG; ++i) {
8459 if (G.traps[i]) {
8460 printf("trap -- ");
8461 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008462 /* note: bash adds "SIG", but only if invoked
8463 * as "bash". If called as "sh", or if set -o posix,
8464 * then it prints short signal names.
8465 * We are printing short names: */
8466 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008467 }
8468 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008469 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008470 return EXIT_SUCCESS;
8471 }
8472
8473 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008474 /* If first arg is a number: reset all specified signals */
8475 sig = bb_strtou(*argv, NULL, 10);
8476 if (errno == 0) {
8477 int ret;
8478 process_sig_list:
8479 ret = EXIT_SUCCESS;
8480 while (*argv) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008481 sighandler_t handler;
8482
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008483 sig = get_signum(*argv++);
8484 if (sig < 0 || sig >= NSIG) {
8485 ret = EXIT_FAILURE;
8486 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008487 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008488 continue;
8489 }
8490
8491 free(G.traps[sig]);
8492 G.traps[sig] = xstrdup(new_cmd);
8493
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008494 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008495 get_signame(sig), sig, G.traps[sig]);
8496
8497 /* There is no signal for 0 (EXIT) */
8498 if (sig == 0)
8499 continue;
8500
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008501 if (new_cmd)
8502 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8503 else
8504 /* We are removing trap handler */
8505 handler = pick_sighandler(sig);
Denys Vlasenko0806e402011-05-12 23:06:20 +02008506 install_sighandler(sig, handler);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008507 }
8508 return ret;
8509 }
8510
8511 if (!argv[1]) { /* no second arg */
8512 bb_error_msg("trap: invalid arguments");
8513 return EXIT_FAILURE;
8514 }
8515
8516 /* First arg is "-": reset all specified to default */
8517 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8518 /* Everything else: set arg as signal handler
8519 * (includes "" case, which ignores signal) */
8520 if (argv[0][0] == '-') {
8521 if (argv[0][1] == '\0') { /* "-" */
8522 /* new_cmd remains NULL: "reset these sigs" */
8523 goto reset_traps;
8524 }
8525 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8526 argv++;
8527 }
8528 /* else: "-something", no special meaning */
8529 }
8530 new_cmd = *argv;
8531 reset_traps:
8532 argv++;
8533 goto process_sig_list;
8534}
8535
Mike Frysinger93cadc22009-05-27 17:06:25 -04008536/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008537static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008538{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008539 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008540
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008541 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008542 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008543 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008544
8545 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008546 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008547 type = "an alias";*/
8548#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008549 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008550 type = "a function";
8551#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008552 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008553 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008554 else if ((path = find_in_path(*argv)) != NULL)
8555 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008556 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008557 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008558 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008559 continue;
8560 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008561
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008562 printf("%s is %s\n", *argv, type);
8563 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008564 }
8565
8566 return ret;
8567}
8568
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008569#if ENABLE_HUSH_JOB
8570/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008571static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008572{
8573 int i, jobnum;
8574 struct pipe *pi;
8575
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008576 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008577 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008578
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008579 /* If they gave us no args, assume they want the last backgrounded task */
8580 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008581 for (pi = G.job_list; pi; pi = pi->next) {
8582 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008583 goto found;
8584 }
8585 }
8586 bb_error_msg("%s: no current job", argv[0]);
8587 return EXIT_FAILURE;
8588 }
8589 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8590 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8591 return EXIT_FAILURE;
8592 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008593 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008594 if (pi->jobid == jobnum) {
8595 goto found;
8596 }
8597 }
8598 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8599 return EXIT_FAILURE;
8600 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008601 /* TODO: bash prints a string representation
8602 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008603 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008604 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008605 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008606 }
8607
8608 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008609 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8610 for (i = 0; i < pi->num_cmds; i++) {
8611 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008612 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008613 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008614
8615 i = kill(- pi->pgrp, SIGCONT);
8616 if (i < 0) {
8617 if (errno == ESRCH) {
8618 delete_finished_bg_job(pi);
8619 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008620 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008621 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008622 }
8623
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008624 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008625 remove_bg_job(pi);
8626 return checkjobs_and_fg_shell(pi);
8627 }
8628 return EXIT_SUCCESS;
8629}
8630#endif
8631
8632#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008633static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008634{
8635 const struct built_in_command *x;
8636
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008637 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008638 "Built-in commands:\n"
8639 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008640 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008641 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008642 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008643 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008644 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008645 return EXIT_SUCCESS;
8646}
8647#endif
8648
Denys Vlasenkoff463a82013-05-12 02:45:23 +02008649#if MAX_HISTORY && ENABLE_FEATURE_EDITING
Flemming Madsend96ffda2013-04-07 18:47:24 +02008650static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
8651{
8652 show_history(G.line_input_state);
8653 return EXIT_SUCCESS;
8654}
8655#endif
8656
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008657#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008658static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008659{
8660 struct pipe *job;
8661 const char *status_string;
8662
Denis Vlasenko87a86552008-07-29 19:43:10 +00008663 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008664 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008665 status_string = "Stopped";
8666 else
8667 status_string = "Running";
8668
8669 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8670 }
8671 return EXIT_SUCCESS;
8672}
8673#endif
8674
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008675#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008676static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008677{
8678 void *p;
8679 unsigned long l;
8680
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008681# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008682 /* Optional. Reduces probability of false positives */
8683 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008684# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008685 /* Crude attempt to find where "free memory" starts,
8686 * sans fragmentation. */
8687 p = malloc(240);
8688 l = (unsigned long)p;
8689 free(p);
8690 p = malloc(3400);
8691 if (l < (unsigned long)p) l = (unsigned long)p;
8692 free(p);
8693
8694 if (!G.memleak_value)
8695 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008696
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008697 l -= G.memleak_value;
8698 if ((long)l < 0)
8699 l = 0;
8700 l /= 1024;
8701 if (l > 127)
8702 l = 127;
8703
8704 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8705 return l;
8706}
8707#endif
8708
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008709static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008710{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008711 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008712 return EXIT_SUCCESS;
8713}
8714
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008715/* Interruptibility of read builtin in bash
8716 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8717 *
8718 * Empty trap makes read ignore corresponding signal, for any signal.
8719 *
8720 * SIGINT:
8721 * - terminates non-interactive shell;
8722 * - interrupts read in interactive shell;
8723 * if it has non-empty trap:
8724 * - executes trap and returns to command prompt in interactive shell;
8725 * - executes trap and returns to read in non-interactive shell;
8726 * SIGTERM:
8727 * - is ignored (does not interrupt) read in interactive shell;
8728 * - terminates non-interactive shell;
8729 * if it has non-empty trap:
8730 * - executes trap and returns to read;
8731 * SIGHUP:
8732 * - terminates shell (regardless of interactivity);
8733 * if it has non-empty trap:
8734 * - executes trap and returns to read;
8735 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008736static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008737{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008738 const char *r;
8739 char *opt_n = NULL;
8740 char *opt_p = NULL;
8741 char *opt_t = NULL;
8742 char *opt_u = NULL;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008743 const char *ifs;
Denys Vlasenko03dad222010-01-12 23:29:57 +01008744 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008745
Denys Vlasenko03dad222010-01-12 23:29:57 +01008746 /* "!": do not abort on errors.
8747 * Option string must start with "sr" to match BUILTIN_READ_xxx
8748 */
8749 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8750 if (read_flags == (uint32_t)-1)
8751 return EXIT_FAILURE;
8752 argv += optind;
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008753 ifs = get_local_var_value("IFS"); /* can be NULL */
8754
8755 again:
Denys Vlasenko03dad222010-01-12 23:29:57 +01008756 r = shell_builtin_read(set_local_var_from_halves,
8757 argv,
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008758 ifs,
Denys Vlasenko03dad222010-01-12 23:29:57 +01008759 read_flags,
8760 opt_n,
8761 opt_p,
8762 opt_t,
8763 opt_u
8764 );
8765
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008766 if ((uintptr_t)r == 1 && errno == EINTR) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02008767 unsigned sig = check_and_run_traps();
Denys Vlasenko80542ba2011-05-08 21:23:43 +02008768 if (sig && sig != SIGINT)
8769 goto again;
8770 }
8771
Denys Vlasenko03dad222010-01-12 23:29:57 +01008772 if ((uintptr_t)r > 1) {
8773 bb_error_msg("%s", r);
8774 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008775 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008776
Denys Vlasenko03dad222010-01-12 23:29:57 +01008777 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008778}
8779
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008780/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8781 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008782 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008783 * set [-abCefhmnuvx] [-o option] [argument...]
8784 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008785 * set -- [argument...]
8786 * set -o
8787 * set +o
8788 * Implementations shall support the options in both their hyphen and
8789 * plus-sign forms. These options can also be specified as options to sh.
8790 * Examples:
8791 * Write out all variables and their values: set
8792 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8793 * Turn on the -x and -v options: set -xv
8794 * Unset all positional parameters: set --
8795 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8796 * Set the positional parameters to the expansion of x, even if x expands
8797 * with a leading '-' or '+': set -- $x
8798 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008799 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008800 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008801static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008802{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008803 int n;
8804 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008805 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008806
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008807 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008808 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008809 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008810 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008811 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008812 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008813
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008814 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008815 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008816 ++argv;
8817 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008818 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008819 if (arg[0] != '+' && arg[0] != '-')
8820 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008821 for (n = 1; arg[n]; ++n) {
8822 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008823 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008824 if (arg[n] == 'o' && argv[1])
8825 argv++;
8826 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008827 } while ((arg = *++argv) != NULL);
8828 /* Now argv[0] is 1st argument */
8829
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008830 if (arg == NULL)
8831 return EXIT_SUCCESS;
8832 set_argv:
8833
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008834 /* NB: G.global_argv[0] ($0) is never freed/changed */
8835 g_argv = G.global_argv;
8836 if (G.global_args_malloced) {
8837 pp = g_argv;
8838 while (*++pp)
8839 free(*pp);
8840 g_argv[1] = NULL;
8841 } else {
8842 G.global_args_malloced = 1;
8843 pp = xzalloc(sizeof(pp[0]) * 2);
8844 pp[0] = g_argv[0]; /* retain $0 */
8845 g_argv = pp;
8846 }
8847 /* This realloc's G.global_argv */
8848 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8849
8850 n = 1;
8851 while (*++pp)
8852 n++;
8853 G.global_argc = n;
8854
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008855 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008856
8857 /* Nothing known, so abort */
8858 error:
8859 bb_error_msg("set: %s: invalid option", arg);
8860 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008861}
8862
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008863static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008864{
8865 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008866 argv = skip_dash_dash(argv);
8867 if (argv[0]) {
8868 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008869 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008870 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008871 if (G.global_args_malloced) {
8872 int m = 1;
8873 while (m <= n)
8874 free(G.global_argv[m++]);
8875 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008876 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008877 memmove(&G.global_argv[1], &G.global_argv[n+1],
8878 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008879 return EXIT_SUCCESS;
8880 }
8881 return EXIT_FAILURE;
8882}
8883
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008884static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008885{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008886 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008887 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008888 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008889#if ENABLE_HUSH_FUNCTIONS
8890 smallint sv_flg;
8891#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008892
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008893 argv = skip_dash_dash(argv);
8894 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008895 if (!filename) {
8896 /* bash says: "bash: .: filename argument required" */
8897 return 2; /* bash compat */
8898 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008899 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008900 if (!strchr(filename, '/')) {
8901 arg_path = find_in_path(filename);
8902 if (arg_path)
8903 filename = arg_path;
8904 }
8905 input = fopen_or_warn(filename, "r");
8906 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008907 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008908 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denys Vlasenko88b532d2013-03-17 14:11:04 +01008909 /* POSIX: non-interactive shell should abort here,
8910 * not merely fail. So far no one complained :)
8911 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008912 return EXIT_FAILURE;
8913 }
8914 close_on_exec_on(fileno(input));
8915
Mike Frysinger885b6f22009-04-18 21:04:25 +00008916#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008917 sv_flg = G.flag_return_in_progress;
8918 /* "we are inside sourced file, ok to use return" */
8919 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008920#endif
Denys Vlasenko88b532d2013-03-17 14:11:04 +01008921 if (argv[1])
8922 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008923
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008924 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008925 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008926
Denys Vlasenko88b532d2013-03-17 14:11:04 +01008927 if (argv[1])
8928 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008929#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008930 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008931#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008932
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008933 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008934}
8935
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008936static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008937{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008938 int rc;
8939 mode_t mask;
8940
8941 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008942 argv = skip_dash_dash(argv);
8943 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008944 mode_t old_mask = mask;
8945
8946 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008947 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008948 mask ^= 0777;
8949 if (rc == 0) {
8950 mask = old_mask;
8951 /* bash messages:
8952 * bash: umask: 'q': invalid symbolic mode operator
8953 * bash: umask: 999: octal number out of range
8954 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008955 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008956 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008957 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008958 rc = 1;
8959 /* Mimic bash */
8960 printf("%04o\n", (unsigned) mask);
8961 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008962 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008963 umask(mask);
8964
8965 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008966}
8967
Mike Frysingerd690f682009-03-30 06:50:54 +00008968/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008969static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008970{
Mike Frysingerd690f682009-03-30 06:50:54 +00008971 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008972 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008973
Denis Vlasenko28e67962009-04-26 23:22:40 +00008974 /* "!": do not abort on errors */
8975 /* "+": stop at 1st non-option */
8976 opts = getopt32(argv, "!+vf");
8977 if (opts == (unsigned)-1)
8978 return EXIT_FAILURE;
8979 if (opts == 3) {
8980 bb_error_msg("unset: -v and -f are exclusive");
8981 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008982 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008983 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008984
8985 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008986 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008987 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008988 if (unset_local_var(*argv)) {
8989 /* unset <nonexistent_var> doesn't fail.
8990 * Error is when one tries to unset RO var.
8991 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008992 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008993 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008994 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008995#if ENABLE_HUSH_FUNCTIONS
8996 else {
8997 unset_func(*argv);
8998 }
8999#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00009000 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00009001 }
9002 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00009003}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009004
Mike Frysinger56bdea12009-03-28 20:01:58 +00009005/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009006static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00009007{
9008 int ret = EXIT_SUCCESS;
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009009 int status;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009010
Denys Vlasenkob131cce2010-05-20 03:39:43 +02009011 argv = skip_dash_dash(argv);
9012 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009013 /* Don't care about wait results */
9014 /* Note 1: must wait until there are no more children */
9015 /* Note 2: must be interruptible */
9016 /* Examples:
9017 * $ sleep 3 & sleep 6 & wait
9018 * [1] 30934 sleep 3
9019 * [2] 30935 sleep 6
9020 * [1] Done sleep 3
9021 * [2] Done sleep 6
9022 * $ sleep 3 & sleep 6 & wait
9023 * [1] 30936 sleep 3
9024 * [2] 30937 sleep 6
9025 * [1] Done sleep 3
9026 * ^C <-- after ~4 sec from keyboard
9027 * $
9028 */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009029 while (1) {
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009030 int sig;
9031 sigset_t oldset, allsigs;
9032
9033 /* waitpid is not interruptible by SA_RESTARTed
9034 * signals which we use. Thus, this ugly dance:
9035 */
9036
9037 /* Make sure possible SIGCHLD is stored in kernel's
9038 * pending signal mask before we call waitpid.
9039 * Or else we may race with SIGCHLD, lose it,
9040 * and get stuck in sigwaitinfo...
9041 */
9042 sigfillset(&allsigs);
9043 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9044
9045 if (!sigisemptyset(&G.pending_set)) {
9046 /* Crap! we raced with some signal! */
9047 // sig = 0;
9048 goto restore;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009049 }
Denys Vlasenko9d6cbaf2011-05-11 23:56:11 +02009050
9051 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9052 if (errno == ECHILD) {
9053 sigprocmask(SIG_SETMASK, &oldset, NULL);
9054 break;
9055 }
9056
9057 /* Wait for SIGCHLD or any other signal */
9058 //sig = sigwaitinfo(&allsigs, NULL);
9059 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9060 /* Note: sigsuspend invokes signal handler */
9061 sigsuspend(&oldset);
9062 restore:
9063 sigprocmask(SIG_SETMASK, &oldset, NULL);
9064
9065 /* So, did we get a signal? */
9066 //if (sig > 0)
9067 // raise(sig); /* run handler */
9068 sig = check_and_run_traps();
9069 if (sig /*&& sig != SIGCHLD - always true */) {
9070 /* see note 2 */
9071 ret = 128 + sig;
9072 break;
9073 }
9074 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009075 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009076 return ret;
9077 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00009078
Denis Vlasenko7566bae2009-03-31 17:24:49 +00009079 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00009080 while (*argv) {
9081 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00009082 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009083 /* mimic bash message */
9084 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009085 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00009086 }
9087 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00009088 if (WIFSIGNALED(status))
9089 ret = 128 + WTERMSIG(status);
9090 else if (WIFEXITED(status))
9091 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00009092 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00009093 ret = EXIT_FAILURE;
9094 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00009095 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00009096 ret = 127;
9097 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00009098 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00009099 }
9100
9101 return ret;
9102}
9103
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009104#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9105static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9106{
9107 if (argv[1]) {
9108 def = bb_strtou(argv[1], NULL, 10);
9109 if (errno || def < def_min || argv[2]) {
9110 bb_error_msg("%s: bad arguments", argv[0]);
9111 def = UINT_MAX;
9112 }
9113 }
9114 return def;
9115}
9116#endif
9117
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009118#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009119static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009120{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009121 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00009122 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009123 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00009124 return EXIT_SUCCESS; /* bash compat */
9125 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00009126 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009127
9128 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9129 if (depth == UINT_MAX)
9130 G.flag_break_continue = BC_BREAK;
9131 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00009132 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009133
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009134 return EXIT_SUCCESS;
9135}
9136
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009137static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009138{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00009139 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9140 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00009141}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00009142#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009143
9144#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009145static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00009146{
9147 int rc;
9148
9149 if (G.flag_return_in_progress != -1) {
9150 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9151 return EXIT_FAILURE; /* bash compat */
9152 }
9153
9154 G.flag_return_in_progress = 1;
9155
9156 /* bash:
9157 * out of range: wraps around at 256, does not error out
9158 * non-numeric param:
9159 * f() { false; return qwe; }; f; echo $?
9160 * bash: return: qwe: numeric argument required <== we do this
9161 * 255 <== we also do this
9162 */
9163 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9164 return rc;
9165}
9166#endif