blob: 64d5e8587dd0174b6d6100b9a444f472d1a2f149 [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 Vlasenkocb6ff252009-05-04 00:14:30 +020084#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denys Vlasenko8da415e2010-12-05 01:30:14 +010085#if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
86 || defined(__APPLE__) \
87 )
88# include <malloc.h> /* for malloc_trim */
89#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +000090#include <glob.h>
91/* #include <dmalloc.h> */
92#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000093# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000094#endif
Denys Vlasenko03dad222010-01-12 23:29:57 +010095
96#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000097#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000098#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +020099#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200100# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +0200101#else
102# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200103#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000104#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200105# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000106#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000107
Denys Vlasenkob9f2d9f2011-01-18 13:58:01 +0100108//applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
109//applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
110//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
111//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200112
113//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
114//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
115
116//config:config HUSH
117//config: bool "hush"
118//config: default y
119//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200120//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200121//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
122//config: case/esac. Redirections, here documents, $((arithmetic))
123//config: and functions are supported.
124//config:
125//config: It will compile and work on no-mmu systems.
126//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +0200127//config: It does not handle select, aliases, tilde expansion,
128//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200129//config:
130//config:config HUSH_BASH_COMPAT
131//config: bool "bash-compatible extensions"
132//config: default y
133//config: depends on HUSH
134//config: help
135//config: Enable bash-compatible extensions.
136//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200137//config:config HUSH_BRACE_EXPANSION
138//config: bool "Brace expansion"
139//config: default y
140//config: depends on HUSH_BASH_COMPAT
141//config: help
142//config: Enable {abc,def} extension.
143//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200144//config:config HUSH_HELP
145//config: bool "help builtin"
146//config: default y
147//config: depends on HUSH
148//config: help
149//config: Enable help builtin in hush. Code size + ~1 kbyte.
150//config:
151//config:config HUSH_INTERACTIVE
152//config: bool "Interactive mode"
153//config: default y
154//config: depends on HUSH
155//config: help
156//config: Enable interactive mode (prompt and command editing).
157//config: Without this, hush simply reads and executes commands
158//config: from stdin just like a shell script from a file.
159//config: No prompt, no PS1/PS2 magic shell variables.
160//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200161//config:config HUSH_SAVEHISTORY
162//config: bool "Save command history to .hush_history"
163//config: default y
164//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
165//config: help
166//config: Enable history saving in hush.
167//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200168//config:config HUSH_JOB
169//config: bool "Job control"
170//config: default y
171//config: depends on HUSH_INTERACTIVE
172//config: help
173//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
174//config: command (not entire shell), fg/bg builtins work. Without this option,
175//config: "cmd &" still works by simply spawning a process and immediately
176//config: prompting for next command (or executing next command in a script),
177//config: but no separate process group is formed.
178//config:
179//config:config HUSH_TICK
180//config: bool "Process substitution"
181//config: default y
182//config: depends on HUSH
183//config: help
184//config: Enable process substitution `command` and $(command) in hush.
185//config:
186//config:config HUSH_IF
187//config: bool "Support if/then/elif/else/fi"
188//config: default y
189//config: depends on HUSH
190//config: help
191//config: Enable if/then/elif/else/fi in hush.
192//config:
193//config:config HUSH_LOOPS
194//config: bool "Support for, while and until loops"
195//config: default y
196//config: depends on HUSH
197//config: help
198//config: Enable for, while and until loops in hush.
199//config:
200//config:config HUSH_CASE
201//config: bool "Support case ... esac statement"
202//config: default y
203//config: depends on HUSH
204//config: help
205//config: Enable case ... esac statement in hush. +400 bytes.
206//config:
207//config:config HUSH_FUNCTIONS
208//config: bool "Support funcname() { commands; } syntax"
209//config: default y
210//config: depends on HUSH
211//config: help
212//config: Enable support for shell functions in hush. +800 bytes.
213//config:
214//config:config HUSH_LOCAL
215//config: bool "Support local builtin"
216//config: default y
217//config: depends on HUSH_FUNCTIONS
218//config: help
219//config: Enable support for local variables in functions.
220//config:
221//config:config HUSH_RANDOM_SUPPORT
222//config: bool "Pseudorandom generator and $RANDOM variable"
223//config: default y
224//config: depends on HUSH
225//config: help
226//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
227//config: Each read of "$RANDOM" will generate a new pseudorandom value.
228//config:
229//config:config HUSH_EXPORT_N
230//config: bool "Support 'export -n' option"
231//config: default y
232//config: depends on HUSH
233//config: help
234//config: export -n unexports variables. It is a bash extension.
235//config:
236//config:config HUSH_MODE_X
237//config: bool "Support 'hush -x' option and 'set -x' command"
238//config: default y
239//config: depends on HUSH
240//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200241//config: This instructs hush to print commands before execution.
242//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200243//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200244//config:config MSH
245//config: bool "msh (deprecated: aliased to hush)"
246//config: default n
247//config: select HUSH
248//config: help
249//config: msh is deprecated and will be removed, please migrate to hush.
250//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200251
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100252/* -i (interactive) and -s (read stdin) are also accepted,
253 * but currently do nothing, therefore aren't shown in help.
254 * NOMMU-specific options are not meant to be used by users,
255 * therefore we don't show them either.
256 */
257//usage:#define hush_trivial_usage
Denys Vlasenko6b6af532011-03-08 10:24:17 +0100258//usage: "[-nx] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100259//usage:#define hush_full_usage "\n\n"
260//usage: "Unix shell interpreter"
261
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100262//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenkob0b83432011-03-07 12:34:59 +0100263//usage:#define msh_full_usage hush_full_usage
264
265//usage:#if ENABLE_FEATURE_SH_IS_HUSH
266//usage:# define sh_trivial_usage hush_trivial_usage
267//usage:# define sh_full_usage hush_full_usage
268//usage:#endif
269//usage:#if ENABLE_FEATURE_BASH_IS_HUSH
270//usage:# define bash_trivial_usage hush_trivial_usage
271//usage:# define bash_full_usage hush_full_usage
272//usage:#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200273
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000274
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200275/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000276#define LEAK_HUNTING 0
277#define BUILD_AS_NOMMU 0
278/* Enable/disable sanity checks. Ok to enable in production,
279 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
280 * Keeping 1 for now even in released versions.
281 */
282#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200283/* Slightly bigger (+200 bytes), but faster hush.
284 * So far it only enables a trick with counting SIGCHLDs and forks,
285 * which allows us to do fewer waitpid's.
286 * (we can detect a case where neither forks were done nor SIGCHLDs happened
287 * and therefore waitpid will return the same result as last time)
288 */
289#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200290/* TODO: implement simplified code for users which do not need ${var%...} ops
291 * So far ${var%...} ops are always enabled:
292 */
293#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000294
295
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000296#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000297# undef BB_MMU
298# undef USE_FOR_NOMMU
299# undef USE_FOR_MMU
300# define BB_MMU 0
301# define USE_FOR_NOMMU(...) __VA_ARGS__
302# define USE_FOR_MMU(...)
303#endif
304
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200305#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100306#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000307/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000308# undef CONFIG_FEATURE_SH_STANDALONE
309# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000310# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100311# undef IF_NOT_FEATURE_SH_STANDALONE
312# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000313# define IF_FEATURE_SH_STANDALONE(...)
314# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000315#endif
316
Denis Vlasenko05743d72008-02-10 12:10:08 +0000317#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000318# undef ENABLE_FEATURE_EDITING
319# define ENABLE_FEATURE_EDITING 0
320# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
321# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000322#endif
323
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000324/* Do we support ANY keywords? */
325#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000326# define HAS_KEYWORDS 1
327# define IF_HAS_KEYWORDS(...) __VA_ARGS__
328# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000329#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000330# define HAS_KEYWORDS 0
331# define IF_HAS_KEYWORDS(...)
332# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000333#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000334
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000335/* If you comment out one of these below, it will be #defined later
336 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000337#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000338/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000339#define debug_printf_parse(...) do {} while (0)
340#define debug_print_tree(a, b) do {} while (0)
341#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000342#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000343#define debug_printf_jobs(...) do {} while (0)
344#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200345#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000346#define debug_printf_glob(...) do {} while (0)
347#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000348#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000349#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000350
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000351#define ERR_PTR ((void*)(long)1)
352
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200353#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000354
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200355#define _SPECIAL_VARS_STR "_*@$!?#"
356#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
357#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200358#if ENABLE_HUSH_BASH_COMPAT
359/* Support / and // replace ops */
360/* Note that // is stored as \ in "encoded" string representation */
361# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
362# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
363# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
364#else
365# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
366# define VAR_SUBST_OPS "%#:-=+?"
367# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
368#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200369
370#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000371
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200372struct variable;
373
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000374static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
375
376/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000377 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000378 */
379#if !BB_MMU
380typedef struct nommu_save_t {
381 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200382 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000383 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000384 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000385} nommu_save_t;
386#endif
387
Denys Vlasenko9b782552010-09-08 13:33:26 +0200388enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000389 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000390#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000391 RES_IF ,
392 RES_THEN ,
393 RES_ELIF ,
394 RES_ELSE ,
395 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000396#endif
397#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000398 RES_FOR ,
399 RES_WHILE ,
400 RES_UNTIL ,
401 RES_DO ,
402 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000403#endif
404#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000405 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000406#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000407#if ENABLE_HUSH_CASE
408 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200409 /* three pseudo-keywords support contrived "case" syntax: */
410 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
411 RES_MATCH , /* "word)" */
412 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000413 RES_ESAC ,
414#endif
415 RES_XXXX ,
416 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200417};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000418
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000419typedef struct o_string {
420 char *data;
421 int length; /* position where data is appended */
422 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200423 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000424 /* At least some part of the string was inside '' or "",
425 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200426 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000427 smallint has_empty_slot;
428 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
429} o_string;
430enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200431 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
432 EXP_FLAG_GLOB = 0x2,
433 /* Protect newly added chars against globbing
434 * by prepending \ to *, ?, [, \ */
435 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
436};
437enum {
438 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000439 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200440 NOT_ASSIGNMENT = 2,
441 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
442 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000443};
444/* Used for initialization: o_string foo = NULL_O_STRING; */
445#define NULL_O_STRING { NULL }
446
447/* I can almost use ordinary FILE*. Is open_memstream() universally
448 * available? Where is it documented? */
449typedef struct in_str {
450 const char *p;
451 /* eof_flag=1: last char in ->p is really an EOF */
452 char eof_flag; /* meaningless if ->p == NULL */
453 char peek_buf[2];
454#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000455 smallint promptmode; /* 0: PS1, 1: PS2 */
456#endif
457 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200458 int (*get) (struct in_str *) FAST_FUNC;
459 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000460} in_str;
461#define i_getch(input) ((input)->get(input))
462#define i_peek(input) ((input)->peek(input))
463
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200464/* The descrip member of this structure is only used to make
465 * debugging output pretty */
466static const struct {
467 int mode;
468 signed char default_fd;
469 char descrip[3];
470} redir_table[] = {
471 { O_RDONLY, 0, "<" },
472 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
473 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
474 { O_CREAT|O_RDWR, 1, "<>" },
475 { O_RDONLY, 0, "<<" },
476/* Should not be needed. Bogus default_fd helps in debugging */
477/* { O_RDONLY, 77, "<<" }, */
478};
479
Eric Andersen25f27032001-04-26 23:22:31 +0000480struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000481 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000482 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000483 int rd_fd; /* fd to redirect */
484 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
485 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000486 smallint rd_type; /* (enum redir_type) */
487 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000488 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200489 * bit 0: do we need to trim leading tabs?
490 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000491 */
Eric Andersen25f27032001-04-26 23:22:31 +0000492};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000493typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200494 REDIRECT_INPUT = 0,
495 REDIRECT_OVERWRITE = 1,
496 REDIRECT_APPEND = 2,
497 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000498 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200499 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000500
501 REDIRFD_CLOSE = -3,
502 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000503 REDIRFD_TO_FILE = -1,
504 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000505
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000506 HEREDOC_SKIPTABS = 1,
507 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000508} redir_type;
509
Eric Andersen25f27032001-04-26 23:22:31 +0000510
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000511struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000512 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000513 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000514 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200515 smallint cmd_type; /* CMD_xxx */
516#define CMD_NORMAL 0
517#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200518#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200519/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200520# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000521#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200522#if ENABLE_HUSH_FUNCTIONS
523# define CMD_FUNCDEF 3
524#endif
525
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100526 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200527 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
528 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000529#if !BB_MMU
530 char *group_as_string;
531#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000532#if ENABLE_HUSH_FUNCTIONS
533 struct function *child_func;
534/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200535 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000536 * When we execute "f1() {a;}" cmd, we create new function and clear
537 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200538 * When we execute "f1() {b;}", we notice that f1 exists,
539 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000540 * we put those fields back into cmd->xxx
541 * (struct function has ->parent_cmd ptr to facilitate that).
542 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
543 * Without this trick, loop would execute a;b;b;b;...
544 * instead of correct sequence a;b;a;b;...
545 * When command is freed, it severs the link
546 * (sets ->child_func->parent_cmd to NULL).
547 */
548#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000549 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000550/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
551 * and on execution these are substituted with their values.
552 * Substitution can make _several_ words out of one argv[n]!
553 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000554 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000555 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000556 struct redir_struct *redirects; /* I/O redirections */
557};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000558/* Is there anything in this command at all? */
559#define IS_NULL_CMD(cmd) \
560 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
561
Eric Andersen25f27032001-04-26 23:22:31 +0000562struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000563 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000564 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000565 int alive_cmds; /* number of commands running (not exited) */
566 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000567#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000568 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000569 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000570 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000571#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000572 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000573 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000574 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
575 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000576};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000577typedef enum pipe_style {
578 PIPE_SEQ = 1,
579 PIPE_AND = 2,
580 PIPE_OR = 3,
581 PIPE_BG = 4,
582} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000583/* Is there anything in this pipe at all? */
584#define IS_NULL_PIPE(pi) \
585 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000586
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000587/* This holds pointers to the various results of parsing */
588struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000589 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000590 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000591 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000592 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000593 /* last command in pipe (being constructed right now) */
594 struct command *command;
595 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000596 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000597#if !BB_MMU
598 o_string as_string;
599#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000600#if HAS_KEYWORDS
601 smallint ctx_res_w;
602 smallint ctx_inverted; /* "! cmd | cmd" */
603#if ENABLE_HUSH_CASE
604 smallint ctx_dsemicolon; /* ";;" seen */
605#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000606 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
607 int old_flag;
608 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000609 * example: "if pipe1; pipe2; then pipe3; fi"
610 * when we see "if" or "then", we malloc and copy current context,
611 * and make ->stack point to it. then we parse pipeN.
612 * when closing "then" / fi" / whatever is found,
613 * we move list_head into ->stack->command->group,
614 * copy ->stack into current context, and delete ->stack.
615 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000616 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000617 struct parse_context *stack;
618#endif
619};
620
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000621/* On program start, environ points to initial environment.
622 * putenv adds new pointers into it, unsetenv removes them.
623 * Neither of these (de)allocates the strings.
624 * setenv allocates new strings in malloc space and does putenv,
625 * and thus setenv is unusable (leaky) for shell's purposes */
626#define setenv(...) setenv_is_leaky_dont_use()
627struct variable {
628 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000629 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200630#if ENABLE_HUSH_LOCAL
631 unsigned func_nest_level;
632#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000633 int max_len; /* if > 0, name is part of initial env; else name is malloced */
634 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000635 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000636};
637
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000638enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000639 BC_BREAK = 1,
640 BC_CONTINUE = 2,
641};
642
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000643#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000644struct function {
645 struct function *next;
646 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000647 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000648 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200649# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000650 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200651# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000652};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000653#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000654
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000655
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100656/* set -/+o OPT support. (TODO: make it optional)
657 * bash supports the following opts:
658 * allexport off
659 * braceexpand on
660 * emacs on
661 * errexit off
662 * errtrace off
663 * functrace off
664 * hashall on
665 * histexpand off
666 * history on
667 * ignoreeof off
668 * interactive-comments on
669 * keyword off
670 * monitor on
671 * noclobber off
672 * noexec off
673 * noglob off
674 * nolog off
675 * notify off
676 * nounset off
677 * onecmd off
678 * physical off
679 * pipefail off
680 * posix off
681 * privileged off
682 * verbose off
683 * vi off
684 * xtrace off
685 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800686static const char o_opt_strings[] ALIGN1 =
687 "pipefail\0"
688 "noexec\0"
689#if ENABLE_HUSH_MODE_X
690 "xtrace\0"
691#endif
692 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100693enum {
694 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800695 OPT_O_NOEXEC,
696#if ENABLE_HUSH_MODE_X
697 OPT_O_XTRACE,
698#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100699 NUM_OPT_O
700};
701
702
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000703/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000704/* Sorted roughly by size (smaller offsets == smaller code) */
705struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000706 /* interactive_fd != 0 means we are an interactive shell.
707 * If we are, then saved_tty_pgrp can also be != 0, meaning
708 * that controlling tty is available. With saved_tty_pgrp == 0,
709 * job control still works, but terminal signals
710 * (^C, ^Z, ^Y, ^\) won't work at all, and background
711 * process groups can only be created with "cmd &".
712 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
713 * to give tty to the foreground process group,
714 * and will take it back when the group is stopped (^Z)
715 * or killed (^C).
716 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000717#if ENABLE_HUSH_INTERACTIVE
718 /* 'interactive_fd' is a fd# open to ctty, if we have one
719 * _AND_ if we decided to act interactively */
720 int interactive_fd;
721 const char *PS1;
722 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000723# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000724#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000725# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000726#endif
727#if ENABLE_FEATURE_EDITING
728 line_input_t *line_input_state;
729#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000730 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200731 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000732 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200733#if ENABLE_HUSH_RANDOM_SUPPORT
734 random_t random_gen;
735#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000736#if ENABLE_HUSH_JOB
737 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000738 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000739 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000740 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400741# define G_saved_tty_pgrp (G.saved_tty_pgrp)
742#else
743# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000744#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100745 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100746#if ENABLE_HUSH_MODE_X
747# define G_x_mode (G.o_opt[OPT_O_XTRACE])
748#else
749# define G_x_mode 0
750#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000751 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000752#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000753 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000754#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000755#if ENABLE_HUSH_FUNCTIONS
756 /* 0: outside of a function (or sourced file)
757 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000758 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000759 */
760 smallint flag_return_in_progress;
761#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000762 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000763 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000764 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000765 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000766 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100767 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000768 /* how many non-NULL argv's we have. NB: $# + 1 */
769 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000770 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000771#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000772 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000773#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000774#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000775 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000776 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000777#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000778 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000779 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200780 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200781 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000782#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000783 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200784# if ENABLE_HUSH_LOCAL
785 struct variable **shadowed_vars_pp;
786 unsigned func_nest_level;
787# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000788#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000789 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200790#if ENABLE_HUSH_FAST
791 unsigned count_SIGCHLD;
792 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200793 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200794#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000795 /* which signals have non-DFL handler (even with no traps set)? */
796 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000797 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000798 sigset_t blocked_set;
799 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000800#if HUSH_DEBUG
801 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000802 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000803#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200804 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000805};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000806#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000807/* Not #defining name to G.name - this quickly gets unwieldy
808 * (too many defines). Also, I actually prefer to see when a variable
809 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000810#define INIT_G() do { \
811 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
812} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000813
814
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000815/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200816static int builtin_cd(char **argv) FAST_FUNC;
817static int builtin_echo(char **argv) FAST_FUNC;
818static int builtin_eval(char **argv) FAST_FUNC;
819static int builtin_exec(char **argv) FAST_FUNC;
820static int builtin_exit(char **argv) FAST_FUNC;
821static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000822#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200823static int builtin_fg_bg(char **argv) FAST_FUNC;
824static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000825#endif
826#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200827static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000828#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200829#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200830static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200831#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000832#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200833static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000834#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400835#if ENABLE_PRINTF
836static int builtin_printf(char **argv) FAST_FUNC;
837#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200838static int builtin_pwd(char **argv) FAST_FUNC;
839static int builtin_read(char **argv) FAST_FUNC;
840static int builtin_set(char **argv) FAST_FUNC;
841static int builtin_shift(char **argv) FAST_FUNC;
842static int builtin_source(char **argv) FAST_FUNC;
843static int builtin_test(char **argv) FAST_FUNC;
844static int builtin_trap(char **argv) FAST_FUNC;
845static int builtin_type(char **argv) FAST_FUNC;
846static int builtin_true(char **argv) FAST_FUNC;
847static int builtin_umask(char **argv) FAST_FUNC;
848static int builtin_unset(char **argv) FAST_FUNC;
849static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000850#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200851static int builtin_break(char **argv) FAST_FUNC;
852static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000853#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000854#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200855static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000856#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000857
858/* Table of built-in functions. They can be forked or not, depending on
859 * context: within pipes, they fork. As simple commands, they do not.
860 * When used in non-forking context, they can change global variables
861 * in the parent shell process. If forked, of course they cannot.
862 * For example, 'unset foo | whatever' will parse and run, but foo will
863 * still be set at the end. */
864struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100865 const char *b_cmd;
866 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000867#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100868 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200869# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000870#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200871# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000872#endif
873};
874
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200875static const struct built_in_command bltins1[] = {
876 BLTIN("." , builtin_source , "Run commands in a file"),
877 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000878#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200879 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000880#endif
881#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200882 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000883#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200884 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000885#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200886 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000887#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200888 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
889 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
890 BLTIN("exit" , builtin_exit , "Exit"),
891 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000892#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200893 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000894#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000895#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200896 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000897#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000898#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200899 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000900#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200901#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200902 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200903#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000904#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200905 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000906#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200907 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000908#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200909 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000910#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200911 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
912 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200913#if ENABLE_HUSH_BASH_COMPAT
914 BLTIN("source" , builtin_source , "Run commands in a file"),
915#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200916 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100917 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100918 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200919 BLTIN("umask" , builtin_umask , "Set file creation mask"),
920 BLTIN("unset" , builtin_unset , "Unset variables"),
921 BLTIN("wait" , builtin_wait , "Wait for process"),
922};
923/* For now, echo and test are unconditionally enabled.
924 * Maybe make it configurable? */
925static const struct built_in_command bltins2[] = {
926 BLTIN("[" , builtin_test , NULL),
927 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400928#if ENABLE_PRINTF
929 BLTIN("printf" , builtin_printf , NULL),
930#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200931 BLTIN("pwd" , builtin_pwd , NULL),
932 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000933};
934
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000935
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000936/* Debug printouts.
937 */
938#if HUSH_DEBUG
939/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100940# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000941# define debug_enter() (G.debug_indent++)
942# define debug_leave() (G.debug_indent--)
943#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200944# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000945# define debug_enter() ((void)0)
946# define debug_leave() ((void)0)
947#endif
948
949#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100950# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000951#endif
952
953#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100954# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000955#endif
956
957#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100958#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000959#endif
960
961#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100962# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000963#endif
964
965#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100966# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000967# define DEBUG_JOBS 1
968#else
969# define DEBUG_JOBS 0
970#endif
971
972#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100973# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000974# define DEBUG_EXPAND 1
975#else
976# define DEBUG_EXPAND 0
977#endif
978
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200979#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100980# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200981#endif
982
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000983#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100984# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000985# define DEBUG_GLOB 1
986#else
987# define DEBUG_GLOB 0
988#endif
989
990#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100991# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000992#endif
993
994#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100995# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000996#endif
997
998#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100999# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001000# define DEBUG_CLEAN 1
1001#else
1002# define DEBUG_CLEAN 0
1003#endif
1004
1005#if DEBUG_EXPAND
1006static void debug_print_strings(const char *prefix, char **vv)
1007{
1008 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001009 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001010 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001011 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001012}
1013#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001014# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001015#endif
1016
1017
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001018/* Leak hunting. Use hush_leaktool.sh for post-processing.
1019 */
1020#if LEAK_HUNTING
1021static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001022{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001023 void *ptr = xmalloc((size + 0xff) & ~0xff);
1024 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1025 return ptr;
1026}
1027static void *xxrealloc(int lineno, void *ptr, size_t size)
1028{
1029 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1030 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1031 return ptr;
1032}
1033static char *xxstrdup(int lineno, const char *str)
1034{
1035 char *ptr = xstrdup(str);
1036 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1037 return ptr;
1038}
1039static void xxfree(void *ptr)
1040{
1041 fdprintf(2, "free %p\n", ptr);
1042 free(ptr);
1043}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001044# define xmalloc(s) xxmalloc(__LINE__, s)
1045# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1046# define xstrdup(s) xxstrdup(__LINE__, s)
1047# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001048#endif
1049
1050
1051/* Syntax and runtime errors. They always abort scripts.
1052 * In interactive use they usually discard unparsed and/or unexecuted commands
1053 * and return to the prompt.
1054 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1055 */
1056#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001057# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001058# define syntax_error(lineno, msg) syntax_error(msg)
1059# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1060# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1061# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1062# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001063#endif
1064
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001065static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001066{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001067 va_list p;
1068
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001069#if HUSH_DEBUG >= 2
1070 bb_error_msg("hush.c:%u", lineno);
1071#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001072 va_start(p, fmt);
1073 bb_verror_msg(fmt, p, NULL);
1074 va_end(p);
1075 if (!G_interactive_fd)
1076 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001077}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001078
1079static void syntax_error(unsigned lineno, const char *msg)
1080{
1081 if (msg)
1082 die_if_script(lineno, "syntax error: %s", msg);
1083 else
1084 die_if_script(lineno, "syntax error", NULL);
1085}
1086
1087static void syntax_error_at(unsigned lineno, const char *msg)
1088{
1089 die_if_script(lineno, "syntax error at '%s'", msg);
1090}
1091
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001092static void syntax_error_unterm_str(unsigned lineno, const char *s)
1093{
1094 die_if_script(lineno, "syntax error: unterminated %s", s);
1095}
1096
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001097/* It so happens that all such cases are totally fatal
1098 * even if shell is interactive: EOF while looking for closing
1099 * delimiter. There is nowhere to read stuff from after that,
1100 * it's EOF! The only choice is to terminate.
1101 */
1102static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001103static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001104{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001105 char msg[2] = { ch, '\0' };
1106 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001107 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001108}
1109
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001110static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001111{
1112 char msg[2];
1113 msg[0] = ch;
1114 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001115 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001116}
1117
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001118#if HUSH_DEBUG < 2
1119# undef die_if_script
1120# undef syntax_error
1121# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001122# undef syntax_error_unterm_ch
1123# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001124# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001125#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001126# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001127# define syntax_error(msg) syntax_error(__LINE__, msg)
1128# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1129# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1130# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1131# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001132#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001133
Denis Vlasenko552433b2009-04-04 19:29:21 +00001134
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001135#if ENABLE_HUSH_INTERACTIVE
1136static void cmdedit_update_prompt(void);
1137#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001138# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001139#endif
1140
1141
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001142/* Utility functions
1143 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001144/* Replace each \x with x in place, return ptr past NUL. */
1145static char *unbackslash(char *src)
1146{
Denys Vlasenko71885402009-09-24 01:44:13 +02001147 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001148 while (1) {
1149 if (*src == '\\')
1150 src++;
1151 if ((*dst++ = *src++) == '\0')
1152 break;
1153 }
1154 return dst;
1155}
1156
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001157static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001158{
1159 int i;
1160 unsigned count1;
1161 unsigned count2;
1162 char **v;
1163
1164 v = strings;
1165 count1 = 0;
1166 if (v) {
1167 while (*v) {
1168 count1++;
1169 v++;
1170 }
1171 }
1172 count2 = 0;
1173 v = add;
1174 while (*v) {
1175 count2++;
1176 v++;
1177 }
1178 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1179 v[count1 + count2] = NULL;
1180 i = count2;
1181 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001182 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001183 return v;
1184}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001185#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001186static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1187{
1188 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1189 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1190 return ptr;
1191}
1192#define add_strings_to_strings(strings, add, need_to_dup) \
1193 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1194#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001195
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001196/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001197static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001198{
1199 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001200 v[0] = add;
1201 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001202 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001203}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001204#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001205static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1206{
1207 char **ptr = add_string_to_strings(strings, add);
1208 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1209 return ptr;
1210}
1211#define add_string_to_strings(strings, add) \
1212 xx_add_string_to_strings(__LINE__, strings, add)
1213#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001214
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001215static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001216{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001217 char **v;
1218
1219 if (!strings)
1220 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001221 v = strings;
1222 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001223 free(*v);
1224 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001225 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001226 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001227}
1228
Denis Vlasenko76d50412008-06-10 16:19:39 +00001229
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001230/* Helpers for setting new $n and restoring them back
1231 */
1232typedef struct save_arg_t {
1233 char *sv_argv0;
1234 char **sv_g_argv;
1235 int sv_g_argc;
1236 smallint sv_g_malloced;
1237} save_arg_t;
1238
1239static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1240{
1241 int n;
1242
1243 sv->sv_argv0 = argv[0];
1244 sv->sv_g_argv = G.global_argv;
1245 sv->sv_g_argc = G.global_argc;
1246 sv->sv_g_malloced = G.global_args_malloced;
1247
1248 argv[0] = G.global_argv[0]; /* retain $0 */
1249 G.global_argv = argv;
1250 G.global_args_malloced = 0;
1251
1252 n = 1;
1253 while (*++argv)
1254 n++;
1255 G.global_argc = n;
1256}
1257
1258static void restore_G_args(save_arg_t *sv, char **argv)
1259{
1260 char **pp;
1261
1262 if (G.global_args_malloced) {
1263 /* someone ran "set -- arg1 arg2 ...", undo */
1264 pp = G.global_argv;
1265 while (*++pp) /* note: does not free $0 */
1266 free(*pp);
1267 free(G.global_argv);
1268 }
1269 argv[0] = sv->sv_argv0;
1270 G.global_argv = sv->sv_g_argv;
1271 G.global_argc = sv->sv_g_argc;
1272 G.global_args_malloced = sv->sv_g_malloced;
1273}
1274
1275
Denis Vlasenkod5762932009-03-31 11:22:57 +00001276/* Basic theory of signal handling in shell
1277 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001278 * This does not describe what hush does, rather, it is current understanding
1279 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001280 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1281 *
1282 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1283 * is finished or backgrounded. It is the same in interactive and
1284 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001285 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001286 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001287 * backgrounds (i.e. stops) or kills all members of currently running
1288 * pipe.
1289 *
1290 * Wait builtin in interruptible by signals for which user trap is set
1291 * or by SIGINT in interactive shell.
1292 *
1293 * Trap handlers will execute even within trap handlers. (right?)
1294 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001295 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1296 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001297 *
1298 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001299 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001300 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001301 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001302 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001303 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001304 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001305 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001306 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001307 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001308 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001309 *
1310 * SIGQUIT: ignore
1311 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001312 * SIGHUP (interactive):
1313 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001314 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001315 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1316 * that all pipe members are stopped. Try this in bash:
1317 * while :; do :; done - ^Z does not background it
1318 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001319 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001320 * of the command line, show prompt. NB: ^C does not send SIGINT
1321 * to interactive shell while shell is waiting for a pipe,
1322 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001323 * Example 1: this waits 5 sec, but does not execute ls:
1324 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1325 * Example 2: this does not wait and does not execute ls:
1326 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1327 * Example 3: this does not wait 5 sec, but executes ls:
1328 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001329 *
1330 * (What happens to signals which are IGN on shell start?)
1331 * (What happens with signal mask on shell start?)
1332 *
1333 * Implementation in hush
1334 * ======================
1335 * We use in-kernel pending signal mask to determine which signals were sent.
1336 * We block all signals which we don't want to take action immediately,
1337 * i.e. we block all signals which need to have special handling as described
1338 * above, and all signals which have traps set.
1339 * After each pipe execution, we extract any pending signals via sigtimedwait()
1340 * and act on them.
1341 *
1342 * unsigned non_DFL_mask: a mask of such "special" signals
1343 * sigset_t blocked_set: current blocked signal set
1344 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001345 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001346 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001347 * "trap 'cmd' SIGxxx":
1348 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001349 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001350 * unblock signals with special interactive handling
1351 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001352 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001353 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001354 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001355 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001356 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001357 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001358 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001359 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001360 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001361 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001362 * Standard says "When a subshell is entered, traps that are not being ignored
1363 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001364 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001365 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001366enum {
1367 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001368 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001369 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001370 | (1 << SIGHUP)
1371 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001372 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001373#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001374 | (1 << SIGTTIN)
1375 | (1 << SIGTTOU)
1376 | (1 << SIGTSTP)
1377#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001378};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001379
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001380#if ENABLE_HUSH_FAST
1381static void SIGCHLD_handler(int sig UNUSED_PARAM)
1382{
1383 G.count_SIGCHLD++;
1384//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1385}
1386#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001387
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001388#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001389
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001390/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001391# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001392/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001393# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001394
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001395/* Restores tty foreground process group, and exits.
1396 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001397 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001398 * or called directly with -EXITCODE.
1399 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001400static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001401static void sigexit(int sig)
1402{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001403 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001404 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001405
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001406 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001407 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001408 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1409 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001410
1411 /* Not a signal, just exit */
1412 if (sig <= 0)
1413 _exit(- sig);
1414
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001415 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001416}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001417#else
1418
Denys Vlasenko8391c482010-05-22 17:50:43 +02001419# define disable_restore_tty_pgrp_on_exit() ((void)0)
1420# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001421
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001422#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001423
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001424/* Restores tty foreground process group, and exits. */
1425static void hush_exit(int exitcode) NORETURN;
1426static void hush_exit(int exitcode)
1427{
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01001428 fflush_all();
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001429 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1430 /* Prevent recursion:
1431 * trap "echo Hi; exit" EXIT; exit
1432 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001433 char *argv[3];
1434 /* argv[0] is unused */
1435 argv[1] = G.traps[0];
1436 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001437 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001438 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001439 * "trap" will still show it, if executed
1440 * in the handler */
1441 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001442 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001443
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001444#if ENABLE_FEATURE_CLEAN_UP
1445 {
1446 struct variable *cur_var;
1447 if (G.cwd != bb_msg_unknown)
1448 free((char*)G.cwd);
1449 cur_var = G.top_var;
1450 while (cur_var) {
1451 struct variable *tmp = cur_var;
1452 if (!cur_var->max_len)
1453 free(cur_var->varstr);
1454 cur_var = cur_var->next;
1455 free(tmp);
1456 }
1457 }
1458#endif
1459
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001460#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001461 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001462 sigexit(- (exitcode & 0xff));
1463#else
1464 exit(exitcode);
1465#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001466}
1467
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001468
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001469static int check_and_run_traps(int sig)
1470{
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001471 /* I want it in rodata, not in bss.
1472 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1473 * initializer. But other compilers may still use bss.
1474 * TODO: find more portable solution.
1475 */
1476 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001477 smalluint save_rcode;
1478 int last_sig = 0;
1479
1480 if (sig)
1481 goto jump_in;
1482 while (1) {
1483 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1484 if (sig <= 0)
1485 break;
1486 jump_in:
1487 last_sig = sig;
1488 if (G.traps && G.traps[sig]) {
1489 if (G.traps[sig][0]) {
1490 /* We have user-defined handler */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001491 char *argv[3];
1492 /* argv[0] is unused */
1493 argv[1] = G.traps[sig];
1494 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001495 save_rcode = G.last_exitcode;
1496 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001497 G.last_exitcode = save_rcode;
1498 } /* else: "" trap, ignoring signal */
1499 continue;
1500 }
1501 /* not a trap: special action */
1502 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001503#if ENABLE_HUSH_FAST
1504 case SIGCHLD:
1505 G.count_SIGCHLD++;
1506//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1507 break;
1508#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001509 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001510 /* Builtin was ^C'ed, make it look prettier: */
1511 bb_putchar('\n');
1512 G.flag_SIGINT = 1;
1513 break;
1514#if ENABLE_HUSH_JOB
1515 case SIGHUP: {
1516 struct pipe *job;
1517 /* bash is observed to signal whole process groups,
1518 * not individual processes */
1519 for (job = G.job_list; job; job = job->next) {
1520 if (job->pgrp <= 0)
1521 continue;
1522 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1523 if (kill(- job->pgrp, SIGHUP) == 0)
1524 kill(- job->pgrp, SIGCONT);
1525 }
1526 sigexit(SIGHUP);
1527 }
1528#endif
1529 default: /* ignored: */
1530 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1531 break;
1532 }
1533 }
1534 return last_sig;
1535}
1536
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001537
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001538static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001539{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001540 if (force || G.cwd == NULL) {
1541 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1542 * we must not try to free(bb_msg_unknown) */
1543 if (G.cwd == bb_msg_unknown)
1544 G.cwd = NULL;
1545 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1546 if (!G.cwd)
1547 G.cwd = bb_msg_unknown;
1548 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001549 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001550}
1551
Denis Vlasenko83506862007-11-23 13:11:42 +00001552
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001553/*
1554 * Shell and environment variable support
1555 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001556static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001557{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001558 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001559 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001560
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001561 pp = &G.top_var;
1562 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001563 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001564 return pp;
1565 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001566 }
1567 return NULL;
1568}
1569
Denys Vlasenko03dad222010-01-12 23:29:57 +01001570static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001571{
Denys Vlasenko29082232010-07-16 13:52:32 +02001572 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001573 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001574
1575 if (G.expanded_assignments) {
1576 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001577 while (*cpp) {
1578 char *cp = *cpp;
1579 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1580 return cp + len + 1;
1581 cpp++;
1582 }
1583 }
1584
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001585 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001586 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001587 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001588
Denys Vlasenkodea47882009-10-09 15:40:49 +02001589 if (strcmp(name, "PPID") == 0)
1590 return utoa(G.root_ppid);
1591 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001592#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001593 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001594 return utoa(next_random(&G.random_gen));
1595#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001596 return NULL;
1597}
1598
1599/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001600 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001601 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001602 * 0: do not change export flag
1603 * (if creating new variable, flag will be 0)
1604 * 1: set export flag and putenv the variable
1605 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001606 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001607 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001608#if !BB_MMU && ENABLE_HUSH_LOCAL
1609/* all params are used */
1610#elif BB_MMU && ENABLE_HUSH_LOCAL
1611#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1612 set_local_var(str, flg_export, local_lvl)
1613#elif BB_MMU && !ENABLE_HUSH_LOCAL
1614#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001615 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001616#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1617#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1618 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001619#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001620static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001621{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001622 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001623 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001624 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001625 int name_len;
1626
Denis Vlasenko950bd722009-04-21 11:23:56 +00001627 eq_sign = strchr(str, '=');
1628 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001629 free(str);
1630 return -1;
1631 }
1632
Denis Vlasenko950bd722009-04-21 11:23:56 +00001633 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001634 var_pp = &G.top_var;
1635 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001636 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001637 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001638 continue;
1639 }
1640 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001641 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001642#if !BB_MMU
1643 if (!flg_read_only)
1644#endif
1645 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001646 free(str);
1647 return -1;
1648 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001649 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001650 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1651 *eq_sign = '\0';
1652 unsetenv(str);
1653 *eq_sign = '=';
1654 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001655#if ENABLE_HUSH_LOCAL
1656 if (cur->func_nest_level < local_lvl) {
1657 /* New variable is declared as local,
1658 * and existing one is global, or local
1659 * from enclosing function.
1660 * Remove and save old one: */
1661 *var_pp = cur->next;
1662 cur->next = *G.shadowed_vars_pp;
1663 *G.shadowed_vars_pp = cur;
1664 /* bash 3.2.33(1) and exported vars:
1665 * # export z=z
1666 * # f() { local z=a; env | grep ^z; }
1667 * # f
1668 * z=a
1669 * # env | grep ^z
1670 * z=z
1671 */
1672 if (cur->flg_export)
1673 flg_export = 1;
1674 break;
1675 }
1676#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001677 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001678 free_and_exp:
1679 free(str);
1680 goto exp;
1681 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001682 if (cur->max_len != 0) {
1683 if (cur->max_len >= strlen(str)) {
1684 /* This one is from startup env, reuse space */
1685 strcpy(cur->varstr, str);
1686 goto free_and_exp;
1687 }
1688 } else {
1689 /* max_len == 0 signifies "malloced" var, which we can
1690 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001691 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001692 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001693 cur->max_len = 0;
1694 goto set_str_and_exp;
1695 }
1696
Denys Vlasenko295fef82009-06-03 12:47:26 +02001697 /* Not found - create new variable struct */
1698 cur = xzalloc(sizeof(*cur));
1699#if ENABLE_HUSH_LOCAL
1700 cur->func_nest_level = local_lvl;
1701#endif
1702 cur->next = *var_pp;
1703 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001704
1705 set_str_and_exp:
1706 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001707#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001708 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001709#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001710 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001711 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001712 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001713 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1714 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001715 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001716 if (flg_export == -1) {
1717 cur->flg_export = 0;
1718 /* unsetenv was already done */
1719 } else {
1720 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1721 return putenv(cur->varstr);
1722 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001723 }
1724 return 0;
1725}
1726
Denys Vlasenko6db47842009-09-05 20:15:17 +02001727/* Used at startup and after each cd */
1728static void set_pwd_var(int exp)
1729{
1730 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1731 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1732}
1733
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001734static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001735{
1736 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001737 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001738
1739 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001740 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001741 var_pp = &G.top_var;
1742 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001743 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1744 if (cur->flg_read_only) {
1745 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001746 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001747 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001748 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001749 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1750 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001751 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1752 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001753 if (!cur->max_len)
1754 free(cur->varstr);
1755 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001756 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001757 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001758 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001759 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001760 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001761}
1762
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001763static int unset_local_var(const char *name)
1764{
1765 return unset_local_var_len(name, strlen(name));
1766}
1767
1768static void unset_vars(char **strings)
1769{
1770 char **v;
1771
1772 if (!strings)
1773 return;
1774 v = strings;
1775 while (*v) {
1776 const char *eq = strchrnul(*v, '=');
1777 unset_local_var_len(*v, (int)(eq - *v));
1778 v++;
1779 }
1780 free(strings);
1781}
1782
Denys Vlasenko03dad222010-01-12 23:29:57 +01001783static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001784{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001785 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001786 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001787}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001788
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001789
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001790/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001791 * Helpers for "var1=val1 var2=val2 cmd" feature
1792 */
1793static void add_vars(struct variable *var)
1794{
1795 struct variable *next;
1796
1797 while (var) {
1798 next = var->next;
1799 var->next = G.top_var;
1800 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001801 if (var->flg_export) {
1802 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001803 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001804 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001805 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001806 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001807 var = next;
1808 }
1809}
1810
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001811static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001812{
1813 char **s;
1814 struct variable *old = NULL;
1815
1816 if (!strings)
1817 return old;
1818 s = strings;
1819 while (*s) {
1820 struct variable *var_p;
1821 struct variable **var_pp;
1822 char *eq;
1823
1824 eq = strchr(*s, '=');
1825 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001826 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001827 if (var_pp) {
1828 /* Remove variable from global linked list */
1829 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001830 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001831 *var_pp = var_p->next;
1832 /* Add it to returned list */
1833 var_p->next = old;
1834 old = var_p;
1835 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001836 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001837 }
1838 s++;
1839 }
1840 return old;
1841}
1842
1843
1844/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001845 * in_str support
1846 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001847static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001848{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001849 int ch = *i->p;
1850 if (ch != '\0') {
1851 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001852 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001853 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001854 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001855}
1856
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001857static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001858{
1859 return *i->p;
1860}
1861
1862#if ENABLE_HUSH_INTERACTIVE
1863
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001864static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001865{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001866 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001867 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001868 if (G.PS1 == NULL)
1869 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001870 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001871 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001872 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001873 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001874 if (G.PS2 == NULL)
1875 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001876}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001877
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001878static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001879{
1880 const char *prompt_str;
1881 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001882 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1883 /* Set up the prompt */
1884 if (promptmode == 0) { /* PS1 */
1885 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001886 /* bash uses $PWD value, even if it is set by user.
1887 * It uses current dir only if PWD is unset.
1888 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001889 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001890 prompt_str = G.PS1;
1891 } else
1892 prompt_str = G.PS2;
1893 } else
1894 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001895 debug_printf("result '%s'\n", prompt_str);
1896 return prompt_str;
1897}
1898
1899static void get_user_input(struct in_str *i)
1900{
1901 int r;
1902 const char *prompt_str;
1903
1904 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001905# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001906 /* Enable command line editing only while a command line
1907 * is actually being read */
1908 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001909 G.flag_SIGINT = 0;
1910 /* buglet: SIGINT will not make new prompt to appear _at once_,
1911 * only after <Enter>. (^C will work) */
Denys Vlasenko66c5b122011-02-08 05:07:02 +01001912 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 +00001913 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001914 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001915 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001916 i->eof_flag = (r < 0);
1917 if (i->eof_flag) { /* EOF/error detected */
1918 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1919 G.user_input_buf[1] = '\0';
1920 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001921# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001922 do {
1923 G.flag_SIGINT = 0;
1924 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001925 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001926 G.user_input_buf[0] = r = fgetc(i->file);
1927 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001928//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001929 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001930 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001931# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001932 i->p = G.user_input_buf;
1933}
1934
1935#endif /* INTERACTIVE */
1936
1937/* This is the magic location that prints prompts
1938 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001939static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001940{
1941 int ch;
1942
1943 /* If there is data waiting, eat it up */
1944 if (i->p && *i->p) {
1945#if ENABLE_HUSH_INTERACTIVE
1946 take_cached:
1947#endif
1948 ch = *i->p++;
1949 if (i->eof_flag && !*i->p)
1950 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001951 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001952 } else {
1953 /* need to double check i->file because we might be doing something
1954 * more complicated by now, like sourcing or substituting. */
1955#if ENABLE_HUSH_INTERACTIVE
Denys Vlasenkoa1463192011-01-18 17:55:04 +01001956 if (G_interactive_fd && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001957 do {
1958 get_user_input(i);
1959 } while (!*i->p); /* need non-empty line */
1960 i->promptmode = 1; /* PS2 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001961 goto take_cached;
1962 }
1963#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001964 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001965 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001966 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001967 return ch;
1968}
1969
Denis Vlasenko913a2012009-04-05 22:17:04 +00001970/* All callers guarantee this routine will never
1971 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001972 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001973static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001974{
1975 int ch;
1976 if (i->p && *i->p) {
1977 if (i->eof_flag && !i->p[1])
1978 return EOF;
1979 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001980 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001981 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001982 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001983 i->eof_flag = (ch == EOF);
1984 i->peek_buf[0] = ch;
1985 i->peek_buf[1] = '\0';
1986 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001987 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001988 return ch;
1989}
1990
1991static void setup_file_in_str(struct in_str *i, FILE *f)
1992{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01001993 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001994 i->peek = file_peek;
1995 i->get = file_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01001996 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001997 i->file = f;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01001998 /* i->p = NULL; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001999}
2000
2001static void setup_string_in_str(struct in_str *i, const char *s)
2002{
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002003 memset(i, 0, sizeof(*i));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002004 i->peek = static_peek;
2005 i->get = static_get;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002006 /* i->promptmode = 0; - PS1 (memset did it) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002007 i->p = s;
Denys Vlasenkoa1463192011-01-18 17:55:04 +01002008 /* i->eof_flag = 0; */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002009}
2010
2011
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002012/*
2013 * o_string support
2014 */
2015#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002016
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002017static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002018{
2019 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002020 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002021 if (o->data)
2022 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002023}
2024
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002025static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002026{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002027 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002028 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002029}
2030
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002031static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2032{
2033 free(o->data);
2034}
2035
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002036static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002037{
2038 if (o->length + len > o->maxlen) {
2039 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2040 o->data = xrealloc(o->data, 1 + o->maxlen);
2041 }
2042}
2043
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002044static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002045{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002046 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2047 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002048 o->data[o->length] = ch;
2049 o->length++;
2050 o->data[o->length] = '\0';
2051}
2052
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002053static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002054{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002055 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002056 memcpy(&o->data[o->length], str, len);
2057 o->length += len;
2058 o->data[o->length] = '\0';
2059}
2060
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002061static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002062{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002063 o_addblock(o, str, strlen(str));
2064}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002065
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002066#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002067static void nommu_addchr(o_string *o, int ch)
2068{
2069 if (o)
2070 o_addchr(o, ch);
2071}
2072#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002073# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002074#endif
2075
2076static void o_addstr_with_NUL(o_string *o, const char *str)
2077{
2078 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002079}
2080
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002081/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002082 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002083 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2084 * Apparently, on unquoted $v bash still does globbing
2085 * ("v='*.txt'; echo $v" prints all .txt files),
2086 * but NOT brace expansion! Thus, there should be TWO independent
2087 * quoting mechanisms on $v expansion side: one protects
2088 * $v from brace expansion, and other additionally protects "$v" against globbing.
2089 * We have only second one.
2090 */
2091
Denys Vlasenko9e800222010-10-03 14:28:04 +02002092#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002093# define MAYBE_BRACES "{}"
2094#else
2095# define MAYBE_BRACES ""
2096#endif
2097
Eric Andersen25f27032001-04-26 23:22:31 +00002098/* My analysis of quoting semantics tells me that state information
2099 * is associated with a destination, not a source.
2100 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002101static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002102{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002103 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002104 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002105 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002106 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002107 o_grow_by(o, sz);
2108 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002109 o->data[o->length] = '\\';
2110 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002111 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002112 o->data[o->length] = ch;
2113 o->length++;
2114 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002115}
2116
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002117static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002118{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002119 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002120 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2121 && strchr("*?[\\" MAYBE_BRACES, ch)
2122 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002123 sz++;
2124 o->data[o->length] = '\\';
2125 o->length++;
2126 }
2127 o_grow_by(o, sz);
2128 o->data[o->length] = ch;
2129 o->length++;
2130 o->data[o->length] = '\0';
2131}
2132
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002133static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002134{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002135 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002136 char ch;
2137 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002138 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002139 if (ordinary_cnt > len) /* paranoia */
2140 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002141 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002142 if (ordinary_cnt == len)
2143 return;
2144 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002145 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002146
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002147 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002148 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002149 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002150 sz++;
2151 o->data[o->length] = '\\';
2152 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002153 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002154 o_grow_by(o, sz);
2155 o->data[o->length] = ch;
2156 o->length++;
2157 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002158 }
2159}
2160
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002161static void o_addQblock(o_string *o, const char *str, int len)
2162{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002163 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002164 o_addblock(o, str, len);
2165 return;
2166 }
2167 o_addqblock(o, str, len);
2168}
2169
Denys Vlasenko38292b62010-09-05 14:49:40 +02002170static void o_addQstr(o_string *o, const char *str)
2171{
2172 o_addQblock(o, str, strlen(str));
2173}
2174
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002175/* A special kind of o_string for $VAR and `cmd` expansion.
2176 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002177 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002178 * list[i] contains an INDEX (int!) into this string data.
2179 * It means that if list[] needs to grow, data needs to be moved higher up
2180 * but list[i]'s need not be modified.
2181 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002182 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002183 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2184 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002185#if DEBUG_EXPAND || DEBUG_GLOB
2186static void debug_print_list(const char *prefix, o_string *o, int n)
2187{
2188 char **list = (char**)o->data;
2189 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2190 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002191
2192 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002193 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 +02002194 prefix, list, n, string_start, o->length, o->maxlen,
2195 !!(o->o_expflags & EXP_FLAG_GLOB),
2196 o->has_quoted_part,
2197 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002198 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002199 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002200 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2201 o->data + (int)(uintptr_t)list[i] + string_start,
2202 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002203 i++;
2204 }
2205 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002206 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002207 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002208 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002209 }
2210}
2211#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002212# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002213#endif
2214
2215/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2216 * in list[n] so that it points past last stored byte so far.
2217 * It returns n+1. */
2218static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002219{
2220 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002221 int string_start;
2222 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002223
2224 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002225 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2226 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002227 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002228 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002229 /* list[n] points to string_start, make space for 16 more pointers */
2230 o->maxlen += 0x10 * sizeof(list[0]);
2231 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002232 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002233 memmove(list + n + 0x10, list + n, string_len);
2234 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002235 } else {
2236 debug_printf_list("list[%d]=%d string_start=%d\n",
2237 n, string_len, string_start);
2238 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002239 } else {
2240 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002241 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2242 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002243 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2244 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002245 o->has_empty_slot = 0;
2246 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002247 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002248 return n + 1;
2249}
2250
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002251/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002252static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002253{
2254 char **list = (char**)o->data;
2255 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2256
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002257 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002258}
2259
Denys Vlasenko9e800222010-10-03 14:28:04 +02002260#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002261/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2262 * first, it processes even {a} (no commas), second,
2263 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002264 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002265 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002266
2267/* Helper */
2268static int glob_needed(const char *s)
2269{
2270 while (*s) {
2271 if (*s == '\\') {
2272 if (!s[1])
2273 return 0;
2274 s += 2;
2275 continue;
2276 }
2277 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2278 return 1;
2279 s++;
2280 }
2281 return 0;
2282}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002283/* Return pointer to next closing brace or to comma */
2284static const char *next_brace_sub(const char *cp)
2285{
2286 unsigned depth = 0;
2287 cp++;
2288 while (*cp != '\0') {
2289 if (*cp == '\\') {
2290 if (*++cp == '\0')
2291 break;
2292 cp++;
2293 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002294 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002295 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002296 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002297 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002298 depth++;
2299 }
2300
2301 return *cp != '\0' ? cp : NULL;
2302}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002303/* Recursive brace globber. Note: may garble pattern[]. */
2304static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002305{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002306 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002307 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002308 const char *next;
2309 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002310 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002311 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002312
2313 debug_printf_glob("glob_brace('%s')\n", pattern);
2314
2315 begin = pattern;
2316 while (1) {
2317 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002318 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002319 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002320 /* Find the first sub-pattern and at the same time
2321 * find the rest after the closing brace */
2322 next = next_brace_sub(begin);
2323 if (next == NULL) {
2324 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002325 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002326 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002327 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002328 /* "{abc}" with no commas - illegal
2329 * brace expr, disregard and skip it */
2330 begin = next + 1;
2331 continue;
2332 }
2333 break;
2334 }
2335 if (*begin == '\\' && begin[1] != '\0')
2336 begin++;
2337 begin++;
2338 }
2339 debug_printf_glob("begin:%s\n", begin);
2340 debug_printf_glob("next:%s\n", next);
2341
2342 /* Now find the end of the whole brace expression */
2343 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002344 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002345 rest = next_brace_sub(rest);
2346 if (rest == NULL) {
2347 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002348 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002349 }
2350 debug_printf_glob("rest:%s\n", rest);
2351 }
2352 rest_len = strlen(++rest) + 1;
2353
2354 /* We are sure the brace expression is well-formed */
2355
2356 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002357 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002358
2359 /* We have a brace expression. BEGIN points to the opening {,
2360 * NEXT points past the terminator of the first element, and REST
2361 * points past the final }. We will accumulate result names from
2362 * recursive runs for each brace alternative in the buffer using
2363 * GLOB_APPEND. */
2364
2365 p = begin + 1;
2366 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002367 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002368 memcpy(
2369 mempcpy(
2370 mempcpy(new_pattern_buf,
2371 /* We know the prefix for all sub-patterns */
2372 pattern, begin - pattern),
2373 p, next - p),
2374 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002375
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002376 /* Note: glob_brace() may garble new_pattern_buf[].
2377 * That's why we re-copy prefix every time (1st memcpy above).
2378 */
2379 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002380 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002381 /* We saw the last entry */
2382 break;
2383 }
2384 p = next + 1;
2385 next = next_brace_sub(next);
2386 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002387 free(new_pattern_buf);
2388 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002389
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002390 simple_glob:
2391 {
2392 int gr;
2393 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002394
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002395 memset(&globdata, 0, sizeof(globdata));
2396 gr = glob(pattern, 0, NULL, &globdata);
2397 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2398 if (gr != 0) {
2399 if (gr == GLOB_NOMATCH) {
2400 globfree(&globdata);
2401 /* NB: garbles parameter */
2402 unbackslash(pattern);
2403 o_addstr_with_NUL(o, pattern);
2404 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2405 return o_save_ptr_helper(o, n);
2406 }
2407 if (gr == GLOB_NOSPACE)
2408 bb_error_msg_and_die(bb_msg_memory_exhausted);
2409 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2410 * but we didn't specify it. Paranoia again. */
2411 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2412 }
2413 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2414 char **argv = globdata.gl_pathv;
2415 while (1) {
2416 o_addstr_with_NUL(o, *argv);
2417 n = o_save_ptr_helper(o, n);
2418 argv++;
2419 if (!*argv)
2420 break;
2421 }
2422 }
2423 globfree(&globdata);
2424 }
2425 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002426}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002427/* Performs globbing on last list[],
2428 * saving each result as a new list[].
2429 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002430static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002431{
2432 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002433
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002434 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002435 if (!o->data)
2436 return o_save_ptr_helper(o, n);
2437 pattern = o->data + o_get_last_ptr(o, n);
2438 debug_printf_glob("glob pattern '%s'\n", pattern);
2439 if (!glob_needed(pattern)) {
2440 /* unbackslash last string in o in place, fix length */
2441 o->length = unbackslash(pattern) - o->data;
2442 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2443 return o_save_ptr_helper(o, n);
2444 }
2445
2446 copy = xstrdup(pattern);
2447 /* "forget" pattern in o */
2448 o->length = pattern - o->data;
2449 n = glob_brace(copy, o, n);
2450 free(copy);
2451 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002452 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002453 return n;
2454}
2455
Denys Vlasenko238081f2010-10-03 14:26:26 +02002456#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002457
2458/* Helper */
2459static int glob_needed(const char *s)
2460{
2461 while (*s) {
2462 if (*s == '\\') {
2463 if (!s[1])
2464 return 0;
2465 s += 2;
2466 continue;
2467 }
2468 if (*s == '*' || *s == '[' || *s == '?')
2469 return 1;
2470 s++;
2471 }
2472 return 0;
2473}
2474/* Performs globbing on last list[],
2475 * saving each result as a new list[].
2476 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002477static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002478{
2479 glob_t globdata;
2480 int gr;
2481 char *pattern;
2482
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002483 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002484 if (!o->data)
2485 return o_save_ptr_helper(o, n);
2486 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002487 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002488 if (!glob_needed(pattern)) {
2489 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002490 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002491 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002492 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002493 return o_save_ptr_helper(o, n);
2494 }
2495
2496 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002497 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2498 * If we glob "*.\*" and don't find anything, we need
2499 * to fall back to using literal "*.*", but GLOB_NOCHECK
2500 * will return "*.\*"!
2501 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002502 gr = glob(pattern, 0, NULL, &globdata);
2503 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002504 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002505 if (gr == GLOB_NOMATCH) {
2506 globfree(&globdata);
2507 goto literal;
2508 }
2509 if (gr == GLOB_NOSPACE)
2510 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002511 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2512 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002513 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002514 }
2515 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2516 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002517 /* "forget" pattern in o */
2518 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002519 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002520 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002521 n = o_save_ptr_helper(o, n);
2522 argv++;
2523 if (!*argv)
2524 break;
2525 }
2526 }
2527 globfree(&globdata);
2528 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002529 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002530 return n;
2531}
2532
Denys Vlasenko238081f2010-10-03 14:26:26 +02002533#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002534
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002535/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002536 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002537static int o_save_ptr(o_string *o, int n)
2538{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002539 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002540 /* If o->has_empty_slot, list[n] was already globbed
2541 * (if it was requested back then when it was filled)
2542 * so don't do that again! */
2543 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002544 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002545 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002546 return o_save_ptr_helper(o, n);
2547}
2548
2549/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002550static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002551{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002552 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002553 int string_start;
2554
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002555 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2556 if (DEBUG_EXPAND)
2557 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002558 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002559 list = (char**)o->data;
2560 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2561 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002562 while (n) {
2563 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002564 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002565 }
2566 return list;
2567}
2568
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002569static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002570
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002571/* Returns pi->next - next pipe in the list */
2572static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002573{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002574 struct pipe *next;
2575 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002576
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002577 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002578 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002579 struct command *command;
2580 struct redir_struct *r, *rnext;
2581
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002582 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002583 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002584 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002585 if (DEBUG_CLEAN) {
2586 int a;
2587 char **p;
2588 for (a = 0, p = command->argv; *p; a++, p++) {
2589 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2590 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002591 }
2592 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002593 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002594 }
2595 /* not "else if": on syntax error, we may have both! */
2596 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002597 debug_printf_clean(" begin group (cmd_type:%d)\n",
2598 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002599 free_pipe_list(command->group);
2600 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002601 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002602 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002603 /* else is crucial here.
2604 * If group != NULL, child_func is meaningless */
2605#if ENABLE_HUSH_FUNCTIONS
2606 else if (command->child_func) {
2607 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2608 command->child_func->parent_cmd = NULL;
2609 }
2610#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002611#if !BB_MMU
2612 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002613 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002614#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002615 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002616 debug_printf_clean(" redirect %d%s",
2617 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002618 /* guard against the case >$FOO, where foo is unset or blank */
2619 if (r->rd_filename) {
2620 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2621 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002622 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002623 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002624 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002625 rnext = r->next;
2626 free(r);
2627 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002628 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002629 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002630 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002631 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002632#if ENABLE_HUSH_JOB
2633 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002634 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002635#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002636
2637 next = pi->next;
2638 free(pi);
2639 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002640}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002641
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002642static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002643{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002644 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002645#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002646 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002647#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002648 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002649 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002650 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002651}
2652
2653
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002654/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002655
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002656#ifndef debug_print_tree
2657static void debug_print_tree(struct pipe *pi, int lvl)
2658{
2659 static const char *const PIPE[] = {
2660 [PIPE_SEQ] = "SEQ",
2661 [PIPE_AND] = "AND",
2662 [PIPE_OR ] = "OR" ,
2663 [PIPE_BG ] = "BG" ,
2664 };
2665 static const char *RES[] = {
2666 [RES_NONE ] = "NONE" ,
2667# if ENABLE_HUSH_IF
2668 [RES_IF ] = "IF" ,
2669 [RES_THEN ] = "THEN" ,
2670 [RES_ELIF ] = "ELIF" ,
2671 [RES_ELSE ] = "ELSE" ,
2672 [RES_FI ] = "FI" ,
2673# endif
2674# if ENABLE_HUSH_LOOPS
2675 [RES_FOR ] = "FOR" ,
2676 [RES_WHILE] = "WHILE",
2677 [RES_UNTIL] = "UNTIL",
2678 [RES_DO ] = "DO" ,
2679 [RES_DONE ] = "DONE" ,
2680# endif
2681# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2682 [RES_IN ] = "IN" ,
2683# endif
2684# if ENABLE_HUSH_CASE
2685 [RES_CASE ] = "CASE" ,
2686 [RES_CASE_IN ] = "CASE_IN" ,
2687 [RES_MATCH] = "MATCH",
2688 [RES_CASE_BODY] = "CASE_BODY",
2689 [RES_ESAC ] = "ESAC" ,
2690# endif
2691 [RES_XXXX ] = "XXXX" ,
2692 [RES_SNTX ] = "SNTX" ,
2693 };
2694 static const char *const CMDTYPE[] = {
2695 "{}",
2696 "()",
2697 "[noglob]",
2698# if ENABLE_HUSH_FUNCTIONS
2699 "func()",
2700# endif
2701 };
2702
2703 int pin, prn;
2704
2705 pin = 0;
2706 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002707 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002708 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2709 prn = 0;
2710 while (prn < pi->num_cmds) {
2711 struct command *command = &pi->cmds[prn];
2712 char **argv = command->argv;
2713
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002714 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002715 lvl*2, "", prn,
2716 command->assignment_cnt);
2717 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002718 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002719 CMDTYPE[command->cmd_type],
2720 argv
2721# if !BB_MMU
2722 , " group_as_string:", command->group_as_string
2723# else
2724 , "", ""
2725# endif
2726 );
2727 debug_print_tree(command->group, lvl+1);
2728 prn++;
2729 continue;
2730 }
2731 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002732 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002733 argv++;
2734 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002735 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002736 prn++;
2737 }
2738 pi = pi->next;
2739 pin++;
2740 }
2741}
2742#endif /* debug_print_tree */
2743
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002744static struct pipe *new_pipe(void)
2745{
Eric Andersen25f27032001-04-26 23:22:31 +00002746 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002747 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002748 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002749 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002750 return pi;
2751}
2752
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002753/* Command (member of a pipe) is complete, or we start a new pipe
2754 * if ctx->command is NULL.
2755 * No errors possible here.
2756 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002757static int done_command(struct parse_context *ctx)
2758{
2759 /* The command is really already in the pipe structure, so
2760 * advance the pipe counter and make a new, null command. */
2761 struct pipe *pi = ctx->pipe;
2762 struct command *command = ctx->command;
2763
2764 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002765 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002766 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002767 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002768 }
2769 pi->num_cmds++;
2770 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002771 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002772 } else {
2773 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2774 }
2775
2776 /* Only real trickiness here is that the uncommitted
2777 * command structure is not counted in pi->num_cmds. */
2778 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002779 ctx->command = command = &pi->cmds[pi->num_cmds];
2780 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002781 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002782 return pi->num_cmds; /* used only for 0/nonzero check */
2783}
2784
2785static void done_pipe(struct parse_context *ctx, pipe_style type)
2786{
2787 int not_null;
2788
2789 debug_printf_parse("done_pipe entered, followup %d\n", type);
2790 /* Close previous command */
2791 not_null = done_command(ctx);
2792 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002793#if HAS_KEYWORDS
2794 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2795 ctx->ctx_inverted = 0;
2796 ctx->pipe->res_word = ctx->ctx_res_w;
2797#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002798
2799 /* Without this check, even just <enter> on command line generates
2800 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002801 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002802 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002803#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002804 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002805#endif
2806#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002807 || ctx->ctx_res_w == RES_DONE
2808 || ctx->ctx_res_w == RES_FOR
2809 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002810#endif
2811#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002812 || ctx->ctx_res_w == RES_ESAC
2813#endif
2814 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002815 struct pipe *new_p;
2816 debug_printf_parse("done_pipe: adding new pipe: "
2817 "not_null:%d ctx->ctx_res_w:%d\n",
2818 not_null, ctx->ctx_res_w);
2819 new_p = new_pipe();
2820 ctx->pipe->next = new_p;
2821 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002822 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002823 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002824 * This is used to control execution.
2825 * RES_FOR and RES_IN are NOT sticky (needed to support
2826 * cases where variable or value happens to match a keyword):
2827 */
2828#if ENABLE_HUSH_LOOPS
2829 if (ctx->ctx_res_w == RES_FOR
2830 || ctx->ctx_res_w == RES_IN)
2831 ctx->ctx_res_w = RES_NONE;
2832#endif
2833#if ENABLE_HUSH_CASE
2834 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002835 ctx->ctx_res_w = RES_CASE_BODY;
2836 if (ctx->ctx_res_w == RES_CASE)
2837 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002838#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002839 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002840 /* Create the memory for command, roughly:
2841 * ctx->pipe->cmds = new struct command;
2842 * ctx->command = &ctx->pipe->cmds[0];
2843 */
2844 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002845 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002846 }
2847 debug_printf_parse("done_pipe return\n");
2848}
2849
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002850static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002851{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002852 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002853 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002854 /* Create the memory for command, roughly:
2855 * ctx->pipe->cmds = new struct command;
2856 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002857 */
2858 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002859}
2860
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002861/* If a reserved word is found and processed, parse context is modified
2862 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002863 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002864#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002865struct reserved_combo {
2866 char literal[6];
2867 unsigned char res;
2868 unsigned char assignment_flag;
2869 int flag;
2870};
2871enum {
2872 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002873# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002874 FLAG_IF = (1 << RES_IF ),
2875 FLAG_THEN = (1 << RES_THEN ),
2876 FLAG_ELIF = (1 << RES_ELIF ),
2877 FLAG_ELSE = (1 << RES_ELSE ),
2878 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002879# endif
2880# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002881 FLAG_FOR = (1 << RES_FOR ),
2882 FLAG_WHILE = (1 << RES_WHILE),
2883 FLAG_UNTIL = (1 << RES_UNTIL),
2884 FLAG_DO = (1 << RES_DO ),
2885 FLAG_DONE = (1 << RES_DONE ),
2886 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002887# endif
2888# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002889 FLAG_MATCH = (1 << RES_MATCH),
2890 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002891# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002892 FLAG_START = (1 << RES_XXXX ),
2893};
2894
2895static const struct reserved_combo* match_reserved_word(o_string *word)
2896{
Eric Andersen25f27032001-04-26 23:22:31 +00002897 /* Mostly a list of accepted follow-up reserved words.
2898 * FLAG_END means we are done with the sequence, and are ready
2899 * to turn the compound list into a command.
2900 * FLAG_START means the word must start a new compound list.
2901 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002902 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002903# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002904 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2905 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2906 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2907 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2908 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2909 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002910# endif
2911# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002912 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2913 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2914 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2915 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2916 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2917 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002918# endif
2919# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002920 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2921 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002922# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002923 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002924 const struct reserved_combo *r;
2925
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02002926 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002927 if (strcmp(word->data, r->literal) == 0)
2928 return r;
2929 }
2930 return NULL;
2931}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002932/* Return 0: not a keyword, 1: keyword
2933 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002934static int reserved_word(o_string *word, struct parse_context *ctx)
2935{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002936# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002937 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002938 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002939 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002940# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002941 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002942
Denys Vlasenko38292b62010-09-05 14:49:40 +02002943 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002944 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002945 r = match_reserved_word(word);
2946 if (!r)
2947 return 0;
2948
2949 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002950# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002951 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2952 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002953 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002954 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002955# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002956 if (r->flag == 0) { /* '!' */
2957 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002958 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002959 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002960 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002961 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002962 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002963 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002964 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002965 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002966
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002967 old = xmalloc(sizeof(*old));
2968 debug_printf_parse("push stack %p\n", old);
2969 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002970 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002971 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002972 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002973 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002974 ctx->ctx_res_w = RES_SNTX;
2975 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002976 } else {
2977 /* "{...} fi" is ok. "{...} if" is not
2978 * Example:
2979 * if { echo foo; } then { echo bar; } fi */
2980 if (ctx->command->group)
2981 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002982 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002983
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002984 ctx->ctx_res_w = r->res;
2985 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002986 word->o_assignment = r->assignment_flag;
2987
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002988 if (ctx->old_flag & FLAG_END) {
2989 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002990
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002991 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002992 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002993 old = ctx->stack;
2994 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002995 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002996# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002997 o_addstr(&old->as_string, ctx->as_string.data);
2998 o_free_unsafe(&ctx->as_string);
2999 old->command->group_as_string = xstrdup(old->as_string.data);
3000 debug_printf_parse("pop, remembering as:'%s'\n",
3001 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003002# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003003 *ctx = *old; /* physical copy */
3004 free(old);
3005 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003006 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003007}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003008#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003009
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003010/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003011 * Normal return is 0. Syntax errors return 1.
3012 * Note: on return, word is reset, but not o_free'd!
3013 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003014static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003015{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003016 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003017
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003018 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003019 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003020 debug_printf_parse("done_word return 0: true null, ignored\n");
3021 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003022 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003023
Eric Andersen25f27032001-04-26 23:22:31 +00003024 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003025 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3026 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003027 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3028 * "2.7 Redirection
3029 * ...the word that follows the redirection operator
3030 * shall be subjected to tilde expansion, parameter expansion,
3031 * command substitution, arithmetic expansion, and quote
3032 * removal. Pathname expansion shall not be performed
3033 * on the word by a non-interactive shell; an interactive
3034 * shell may perform it, but shall do so only when
3035 * the expansion would result in one word."
3036 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003037 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003038 /* Cater for >\file case:
3039 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3040 * Same with heredocs:
3041 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3042 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003043 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3044 unbackslash(ctx->pending_redirect->rd_filename);
3045 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003046 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003047 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3048 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003049 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003050 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003051 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003052 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003053 /* If this word wasn't an assignment, next ones definitely
3054 * can't be assignments. Even if they look like ones. */
3055 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3056 && word->o_assignment != WORD_IS_KEYWORD
3057 ) {
3058 word->o_assignment = NOT_ASSIGNMENT;
3059 } else {
3060 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3061 command->assignment_cnt++;
3062 word->o_assignment = MAYBE_ASSIGNMENT;
3063 }
3064
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003065#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003066# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003067 if (ctx->ctx_dsemicolon
3068 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3069 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003070 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003071 /* ctx->ctx_res_w = RES_MATCH; */
3072 ctx->ctx_dsemicolon = 0;
3073 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003074# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003075 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003076# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003077 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3078 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003079# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003080# if ENABLE_HUSH_CASE
3081 && ctx->ctx_res_w != RES_CASE
3082# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003083 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003084 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003085 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003086 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003087 debug_printf_parse("done_word return %d\n",
3088 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003089 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003090 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003091# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003092 if (strcmp(word->data, "[[") == 0) {
3093 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3094 }
3095 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003096# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003097 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003098#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003099 if (command->group) {
3100 /* "{ echo foo; } echo bar" - bad */
3101 syntax_error_at(word->data);
3102 debug_printf_parse("done_word return 1: syntax error, "
3103 "groups and arglists don't mix\n");
3104 return 1;
3105 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02003106 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003107 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3108 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003109 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003110 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003111 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003112 char *p = word->data;
3113 while (p[0] == SPECIAL_VAR_SYMBOL
3114 && (p[1] & 0x7f) == '@'
3115 && p[2] == SPECIAL_VAR_SYMBOL
3116 ) {
3117 p += 3;
3118 }
3119 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003120 /* saw no "$@", or not only "$@" but some
3121 * real text is there too */
3122 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003123 * e.g. "", $empty"" etc to not disappear */
3124 o_addchr(word, SPECIAL_VAR_SYMBOL);
3125 o_addchr(word, SPECIAL_VAR_SYMBOL);
3126 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003127 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003128 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003129 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003130 }
Eric Andersen25f27032001-04-26 23:22:31 +00003131
Denis Vlasenko06810332007-05-21 23:30:54 +00003132#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003133 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003134 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003135 || !is_well_formed_var_name(command->argv[0], '\0')
3136 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003137 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003138 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003139 return 1;
3140 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003141 /* Force FOR to have just one word (variable name) */
3142 /* NB: basically, this makes hush see "for v in ..."
3143 * syntax as if it is "for v; in ...". FOR and IN become
3144 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003145 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003146 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003147#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003148#if ENABLE_HUSH_CASE
3149 /* Force CASE to have just one word */
3150 if (ctx->ctx_res_w == RES_CASE) {
3151 done_pipe(ctx, PIPE_SEQ);
3152 }
3153#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003154
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003155 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003156
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003157 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003158 return 0;
3159}
3160
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003161
3162/* Peek ahead in the input to find out if we have a "&n" construct,
3163 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003164 * Return:
3165 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3166 * REDIRFD_SYNTAX_ERR if syntax error,
3167 * REDIRFD_TO_FILE if no & was seen,
3168 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003169 */
3170#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003171#define parse_redir_right_fd(as_string, input) \
3172 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003173#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003174static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003175{
3176 int ch, d, ok;
3177
3178 ch = i_peek(input);
3179 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003180 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003181
3182 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003183 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003184 ch = i_peek(input);
3185 if (ch == '-') {
3186 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003187 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003188 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003189 }
3190 d = 0;
3191 ok = 0;
3192 while (ch != EOF && isdigit(ch)) {
3193 d = d*10 + (ch-'0');
3194 ok = 1;
3195 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003196 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003197 ch = i_peek(input);
3198 }
3199 if (ok) return d;
3200
3201//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3202
3203 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003204 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003205}
3206
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003207/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003208 */
3209static int parse_redirect(struct parse_context *ctx,
3210 int fd,
3211 redir_type style,
3212 struct in_str *input)
3213{
3214 struct command *command = ctx->command;
3215 struct redir_struct *redir;
3216 struct redir_struct **redirp;
3217 int dup_num;
3218
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003219 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003220 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003221 /* Check for a '>&1' type redirect */
3222 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3223 if (dup_num == REDIRFD_SYNTAX_ERR)
3224 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003225 } else {
3226 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003227 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003228 if (dup_num) { /* <<-... */
3229 ch = i_getch(input);
3230 nommu_addchr(&ctx->as_string, ch);
3231 ch = i_peek(input);
3232 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003233 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003234
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003235 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003236 int ch = i_peek(input);
3237 if (ch == '|') {
3238 /* >|FILE redirect ("clobbering" >).
3239 * Since we do not support "set -o noclobber" yet,
3240 * >| and > are the same for now. Just eat |.
3241 */
3242 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003243 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003244 }
3245 }
3246
3247 /* Create a new redir_struct and append it to the linked list */
3248 redirp = &command->redirects;
3249 while ((redir = *redirp) != NULL) {
3250 redirp = &(redir->next);
3251 }
3252 *redirp = redir = xzalloc(sizeof(*redir));
3253 /* redir->next = NULL; */
3254 /* redir->rd_filename = NULL; */
3255 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003256 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003257
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003258 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3259 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003260
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003261 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003262 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003263 /* Erik had a check here that the file descriptor in question
3264 * is legit; I postpone that to "run time"
3265 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003266 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3267 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003268 } else {
3269 /* Set ctx->pending_redirect, so we know what to do at the
3270 * end of the next parsed word. */
3271 ctx->pending_redirect = redir;
3272 }
3273 return 0;
3274}
3275
Eric Andersen25f27032001-04-26 23:22:31 +00003276/* If a redirect is immediately preceded by a number, that number is
3277 * supposed to tell which file descriptor to redirect. This routine
3278 * looks for such preceding numbers. In an ideal world this routine
3279 * needs to handle all the following classes of redirects...
3280 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3281 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3282 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3283 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003284 *
3285 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3286 * "2.7 Redirection
3287 * ... If n is quoted, the number shall not be recognized as part of
3288 * the redirection expression. For example:
3289 * echo \2>a
3290 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003291 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003292 *
3293 * A -1 return means no valid number was found,
3294 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003295 */
3296static int redirect_opt_num(o_string *o)
3297{
3298 int num;
3299
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003300 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003301 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003302 num = bb_strtou(o->data, NULL, 10);
3303 if (errno || num < 0)
3304 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003305 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003306 return num;
3307}
3308
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003309#if BB_MMU
3310#define fetch_till_str(as_string, input, word, skip_tabs) \
3311 fetch_till_str(input, word, skip_tabs)
3312#endif
3313static char *fetch_till_str(o_string *as_string,
3314 struct in_str *input,
3315 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003316 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003317{
3318 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003319 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003320 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003321 int ch;
3322
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003323 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003324 while (1) {
3325 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003326 if (ch != EOF)
3327 nommu_addchr(as_string, ch);
3328 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003329 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3330 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003331 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3332 heredoc.data[past_EOL] = '\0';
3333 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3334 return heredoc.data;
3335 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003336 while (ch == '\n') {
3337 o_addchr(&heredoc, ch);
3338 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003339 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003340 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003341 do {
3342 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003343 if (ch != EOF)
3344 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003345 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003346 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003347 }
3348 if (ch == EOF) {
3349 o_free_unsafe(&heredoc);
3350 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003351 }
3352 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003353 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003354 if (prev == '\\' && ch == '\\')
3355 /* Correctly handle foo\\<eol> (not a line cont.) */
3356 prev = 0; /* not \ */
3357 else
3358 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003359 }
3360}
3361
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003362/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3363 * and load them all. There should be exactly heredoc_cnt of them.
3364 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003365static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3366{
3367 struct pipe *pi = ctx->list_head;
3368
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003369 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003370 int i;
3371 struct command *cmd = pi->cmds;
3372
3373 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3374 pi->num_cmds,
3375 cmd->argv ? cmd->argv[0] : "NONE");
3376 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003377 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003378
3379 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3380 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003381 while (redir) {
3382 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003383 char *p;
3384
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003385 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003386 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003387 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003388 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003389 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003390 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003391 return 1;
3392 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003393 free(redir->rd_filename);
3394 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003395 heredoc_cnt--;
3396 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003397 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003398 }
3399 cmd++;
3400 }
3401 pi = pi->next;
3402 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003403#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003404 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003405 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003406 bb_error_msg_and_die("heredoc BUG 2");
3407#endif
3408 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003409}
3410
3411
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003412static int run_list(struct pipe *pi);
3413#if BB_MMU
3414#define parse_stream(pstring, input, end_trigger) \
3415 parse_stream(input, end_trigger)
3416#endif
3417static struct pipe *parse_stream(char **pstring,
3418 struct in_str *input,
3419 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003420
Eric Andersen25f27032001-04-26 23:22:31 +00003421
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003422#if !ENABLE_HUSH_FUNCTIONS
3423#define parse_group(dest, ctx, input, ch) \
3424 parse_group(ctx, input, ch)
3425#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003426static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003427 struct in_str *input, int ch)
3428{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003429 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003430 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003431 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003432 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003433 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003434 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003435
3436 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003437#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003438 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003439 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003440 if (done_word(dest, ctx))
3441 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003442 if (!command->argv)
3443 goto skip; /* (... */
3444 if (command->argv[1]) { /* word word ... (... */
3445 syntax_error_unexpected_ch('(');
3446 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003447 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003448 /* it is "word(..." or "word (..." */
3449 do
3450 ch = i_getch(input);
3451 while (ch == ' ' || ch == '\t');
3452 if (ch != ')') {
3453 syntax_error_unexpected_ch(ch);
3454 return 1;
3455 }
3456 nommu_addchr(&ctx->as_string, ch);
3457 do
3458 ch = i_getch(input);
3459 while (ch == ' ' || ch == '\t' || ch == '\n');
3460 if (ch != '{') {
3461 syntax_error_unexpected_ch(ch);
3462 return 1;
3463 }
3464 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003465 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003466 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003467 }
3468#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003469
3470#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003471 if (command->argv /* word [word]{... */
3472 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003473 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003474 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003475 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003476 debug_printf_parse("parse_group return 1: "
3477 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003478 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003479 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003480#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003481
3482#if ENABLE_HUSH_FUNCTIONS
3483 skip:
3484#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003485 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003486 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003487 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003488 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003489 } else {
3490 /* bash does not allow "{echo...", requires whitespace */
3491 ch = i_getch(input);
3492 if (ch != ' ' && ch != '\t' && ch != '\n') {
3493 syntax_error_unexpected_ch(ch);
3494 return 1;
3495 }
3496 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003497 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003498
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003499 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003500#if BB_MMU
3501# define as_string NULL
3502#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003503 char *as_string = NULL;
3504#endif
3505 pipe_list = parse_stream(&as_string, input, endch);
3506#if !BB_MMU
3507 if (as_string)
3508 o_addstr(&ctx->as_string, as_string);
3509#endif
3510 /* empty ()/{} or parse error? */
3511 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003512 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003513 if (!BB_MMU)
3514 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003515 debug_printf_parse("parse_group return 1: "
3516 "parse_stream returned %p\n", pipe_list);
3517 return 1;
3518 }
3519 command->group = pipe_list;
3520#if !BB_MMU
3521 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3522 command->group_as_string = as_string;
3523 debug_printf_parse("end of group, remembering as:'%s'\n",
3524 command->group_as_string);
3525#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003526#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003527 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003528 debug_printf_parse("parse_group return 0\n");
3529 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003530 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003531}
3532
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003533#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003534/* Subroutines for copying $(...) and `...` things */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003535static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003536/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003537static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003538{
3539 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003540 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003541 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003542 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003543 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003544 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003545 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003546 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003547 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003548 }
3549}
3550/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003551static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003552{
3553 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003554 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003555 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003556 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003557 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003558 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003559 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003560 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003561 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003562 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003563 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003564 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003565 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003566 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003567 add_till_backquote(dest, input, /*in_dquote:*/ 1);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003568 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003569 continue;
3570 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003571 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003572 }
3573}
3574/* Process `cmd` - copy contents until "`" is seen. Complicated by
3575 * \` quoting.
3576 * "Within the backquoted style of command substitution, backslash
3577 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3578 * The search for the matching backquote shall be satisfied by the first
3579 * backquote found without a preceding backslash; during this search,
3580 * if a non-escaped backquote is encountered within a shell comment,
3581 * a here-document, an embedded command substitution of the $(command)
3582 * form, or a quoted string, undefined results occur. A single-quoted
3583 * or double-quoted string that begins, but does not end, within the
3584 * "`...`" sequence produces undefined results."
3585 * Example Output
3586 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3587 */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003588static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003589{
3590 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003591 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003592 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003593 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003594 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003595 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3596 ch = i_getch(input);
3597 if (ch != '`'
3598 && ch != '$'
3599 && ch != '\\'
3600 && (!in_dquote || ch != '"')
3601 ) {
3602 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003603 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003604 }
3605 if (ch == EOF) {
3606 syntax_error_unterm_ch('`');
3607 /*xfunc_die(); - redundant */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003608 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003609 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003610 }
3611}
3612/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3613 * quoting and nested ()s.
3614 * "With the $(command) style of command substitution, all characters
3615 * following the open parenthesis to the matching closing parenthesis
3616 * constitute the command. Any valid shell script can be used for command,
3617 * except a script consisting solely of redirections which produces
3618 * unspecified results."
3619 * Example Output
3620 * echo $(echo '(TEST)' BEST) (TEST) BEST
3621 * echo $(echo 'TEST)' BEST) TEST) BEST
3622 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003623 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003624 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003625 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003626 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3627 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003628 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003629#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003630static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003631{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003632 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003633 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003634# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003635 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003636# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003637 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3638
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003639 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003640 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003641 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003642 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003643 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003644 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003645 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003646 if (!dbl)
3647 break;
3648 /* we look for closing )) of $((EXPR)) */
3649 if (i_peek(input) == end_ch) {
3650 i_getch(input); /* eat second ')' */
3651 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003652 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003653 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003654 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003655 if (ch == '(' || ch == '{') {
3656 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003657 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003658 o_addchr(dest, ch);
3659 continue;
3660 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003661 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003662 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003663 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003664 continue;
3665 }
3666 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003667 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003668 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003669 continue;
3670 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003671 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003672 add_till_backquote(dest, input, /*in_dquote:*/ 0);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003673 o_addchr(dest, ch);
3674 continue;
3675 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003676 if (ch == '\\') {
3677 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003678 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003679 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003680 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003681 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003682 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003683 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003684 continue;
3685 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003686 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003687 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003688}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003689#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003690
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003691/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003692#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003693#define parse_dollar(as_string, dest, input, quote_mask) \
3694 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003695#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003696#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003697static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003698 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003699 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003700{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003701 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003702
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003703 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003704 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003705 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003706 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003707 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003708 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003709 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003710 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003711 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003712 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003713 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003714 if (!isalnum(ch) && ch != '_')
3715 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003716 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003717 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003718 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003719 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003720 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003721 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003722 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003723 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003724 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003725 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003726 o_addchr(dest, ch | quote_mask);
3727 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003728 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003729 case '$': /* pid */
3730 case '!': /* last bg pid */
3731 case '?': /* last exit code */
3732 case '#': /* number of args */
3733 case '*': /* args */
3734 case '@': /* args */
3735 goto make_one_char_var;
3736 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003737 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3738
Denys Vlasenko74369502010-05-21 19:52:01 +02003739 ch = i_getch(input); /* eat '{' */
3740 nommu_addchr(as_string, ch);
3741
3742 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003743 /* It should be ${?}, or ${#var},
3744 * or even ${?+subst} - operator acting on a special variable,
3745 * or the beginning of variable name.
3746 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003747 if (ch == EOF
3748 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3749 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003750 bad_dollar_syntax:
3751 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003752 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02003753 return 1;
3754 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003755 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003756 ch |= quote_mask;
3757
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003758 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003759 * However, this regresses some of our testsuite cases
3760 * which check invalid constructs like ${%}.
3761 * Oh well... let's check that the var name part is fine... */
3762
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003763 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003764 unsigned pos;
3765
Denys Vlasenko74369502010-05-21 19:52:01 +02003766 o_addchr(dest, ch);
3767 debug_printf_parse(": '%c'\n", ch);
3768
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003769 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003770 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003771 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003772 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003773
Denys Vlasenko74369502010-05-21 19:52:01 +02003774 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003775 unsigned end_ch;
3776 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003777 /* handle parameter expansions
3778 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3779 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003780 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003781 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003782
3783 /* Eat everything until closing '}' (or ':') */
3784 end_ch = '}';
3785 if (ENABLE_HUSH_BASH_COMPAT
3786 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003787 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003788 ) {
3789 /* It's ${var:N[:M]} thing */
3790 end_ch = '}' * 0x100 + ':';
3791 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003792 if (ENABLE_HUSH_BASH_COMPAT
3793 && ch == '/'
3794 ) {
3795 /* It's ${var/[/]pattern[/repl]} thing */
3796 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3797 i_getch(input);
3798 nommu_addchr(as_string, '/');
3799 ch = '\\';
3800 }
3801 end_ch = '}' * 0x100 + '/';
3802 }
3803 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003804 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003805 if (!BB_MMU)
3806 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003807#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003808 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003809#else
3810#error Simple code to only allow ${var} is not implemented
3811#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003812 if (as_string) {
3813 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003814 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003815 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003816
3817 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3818 /* close the first block: */
3819 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003820 /* while parsing N from ${var:N[:M]}
3821 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003822 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003823 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003824 end_ch = '}';
3825 goto again;
3826 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003827 /* got '}' */
3828 if (end_ch == '}' * 0x100 + ':') {
3829 /* it's ${var:N} - emulate :999999999 */
3830 o_addstr(dest, "999999999");
3831 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003832 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003833 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003834 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003835 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003836 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3837 break;
3838 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003839#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003840 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003841 unsigned pos;
3842
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003843 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003844 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003845# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003846 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003847 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003848 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003849 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3850 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003851 if (!BB_MMU)
3852 pos = dest->length;
3853 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003854 if (as_string) {
3855 o_addstr(as_string, dest->data + pos);
3856 o_addchr(as_string, ')');
3857 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003858 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003859 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003860 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003861 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003862# endif
3863# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003864 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3865 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003866 if (!BB_MMU)
3867 pos = dest->length;
3868 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003869 if (as_string) {
3870 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003871 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003872 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003873 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003874# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003875 break;
3876 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003877#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003878 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003879 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003880 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003881 ch = i_peek(input);
3882 if (isalnum(ch)) { /* it's $_name or $_123 */
3883 ch = '_';
3884 goto make_var;
3885 }
3886 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003887 /* TODO: $_ and $-: */
3888 /* $_ Shell or shell script name; or last argument of last command
3889 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3890 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003891 /* $- Option flags set by set builtin or shell options (-i etc) */
3892 default:
3893 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003894 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003895 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003896 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003897#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003898}
3899
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003900#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003901# if ENABLE_HUSH_BASH_COMPAT
3902#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3903 encode_string(dest, input, dquote_end, process_bkslash)
3904# else
3905/* only ${var/pattern/repl} (its pattern part) needs additional mode */
3906#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3907 encode_string(dest, input, dquote_end)
3908# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003909#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003910
3911#else /* !MMU */
3912
3913# if ENABLE_HUSH_BASH_COMPAT
3914/* all parameters are needed, no macro tricks */
3915# else
3916#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3917 encode_string(as_string, dest, input, dquote_end)
3918# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003919#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003920static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003921 o_string *dest,
3922 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02003923 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003924 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003925{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003926#if !ENABLE_HUSH_BASH_COMPAT
3927 const int process_bkslash = 1;
3928#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003929 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003930 int next;
3931
3932 again:
3933 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003934 if (ch != EOF)
3935 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003936 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003937 debug_printf_parse("encode_string return 0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003938 return 0;
3939 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003940 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003941 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003942 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003943 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003944 }
3945 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003946 if (ch != '\n') {
3947 next = i_peek(input);
3948 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003949 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003950 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003951 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003952 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003953 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003954 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003955 }
3956 /* bash:
3957 * "The backslash retains its special meaning [in "..."]
3958 * only when followed by one of the following characters:
3959 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003960 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003961 * NB: in (unquoted) heredoc, above does not apply to ",
3962 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003963 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003964 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003965 ch = i_getch(input); /* eat next */
3966 if (ch == '\n')
3967 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02003968 } /* else: ch remains == '\\', and we double it below: */
3969 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003970 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003971 goto again;
3972 }
3973 if (ch == '$') {
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003974 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003975 debug_printf_parse("encode_string return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003976 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003977 return 1;
3978 }
3979 goto again;
3980 }
3981#if ENABLE_HUSH_TICK
3982 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003983 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003984 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3985 o_addchr(dest, 0x80 | '`');
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003986 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003987 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3988 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003989 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003990 }
3991#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00003992 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003993 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003994#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003995}
3996
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003997/*
3998 * Scan input until EOF or end_trigger char.
3999 * Return a list of pipes to execute, or NULL on EOF
4000 * or if end_trigger character is met.
4001 * On syntax error, exit is shell is not interactive,
4002 * reset parsing machinery and start parsing anew,
4003 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004004 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004005static struct pipe *parse_stream(char **pstring,
4006 struct in_str *input,
4007 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004008{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004009 struct parse_context ctx;
4010 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004011 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004012
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004013 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004014 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004015 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004016 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004017 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004018 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004019
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004020 /* If very first arg is "" or '', dest.data may end up NULL.
4021 * Preventing this: */
4022 o_addchr(&dest, '\0');
4023 dest.length = 0;
4024
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004025 /* We used to separate words on $IFS here. This was wrong.
4026 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004027 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004028 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004029
4030 reset: /* we come back here only on syntax errors in interactive shell */
4031
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004032 if (MAYBE_ASSIGNMENT != 0)
4033 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004034 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004035 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004036 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004037 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004038 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004039 int ch;
4040 int next;
4041 int redir_fd;
4042 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004043
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004044 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004045 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004046 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004047 if (ch == EOF) {
4048 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004049
4050 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004051 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004052 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004053 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004054 /* end_trigger == '}' case errors out earlier,
4055 * checking only ')' */
4056 if (end_trigger == ')') {
4057 syntax_error_unterm_ch('('); /* exits */
4058 /* goto parse_error; */
4059 }
4060
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004061 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004062 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004063 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004064 o_free(&dest);
4065 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004066 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004067 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004068 /* (this makes bare "&" cmd a no-op.
4069 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004070 if (pi->num_cmds == 0
4071 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4072 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004073 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004074 pi = NULL;
4075 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004076#if !BB_MMU
4077 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4078 if (pstring)
4079 *pstring = ctx.as_string.data;
4080 else
4081 o_free_unsafe(&ctx.as_string);
4082#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004083 debug_leave();
4084 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004085 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004086 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004087 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004088
4089 next = '\0';
4090 if (ch != '\n')
4091 next = i_peek(input);
4092
4093 is_special = "{}<>;&|()#'" /* special outside of "str" */
4094 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4095 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004096 if (ctx.command->argv /* word [word]{... - non-special */
4097 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004098 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004099 || (next != ';' /* }; - special */
4100 && next != ')' /* }) - special */
4101 && next != '&' /* }& and }&& ... - special */
4102 && next != '|' /* }|| ... - special */
4103 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004104 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004105 ) {
4106 /* They are not special, skip "{}" */
4107 is_special += 2;
4108 }
4109 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004110 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004111
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004112 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004113 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004114 o_addQchr(&dest, ch);
4115 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4116 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004117 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004118 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004119 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004120 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004121 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004122 continue;
4123 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004124
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004125 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004126 if (done_word(&dest, &ctx)) {
4127 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004128 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004129 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004130 /* Is this a case when newline is simply ignored?
4131 * Some examples:
4132 * "cmd | <newline> cmd ..."
4133 * "case ... in <newline> word) ..."
4134 */
4135 if (IS_NULL_CMD(ctx.command)
4136 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004137 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004138 /* This newline can be ignored. But...
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004139 * Without check #1, interactive shell
4140 * ignores even bare <newline>,
4141 * and shows the continuation prompt:
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004142 * ps1_prompt$ <enter>
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004143 * ps2> _ <=== wrong, should be ps1
4144 * Without check #2, "cmd & <newline>"
4145 * is similarly mistreated.
4146 * (BTW, this makes "cmd & cmd"
4147 * and "cmd && cmd" non-orthogonal.
4148 * Really, ask yourself, why
4149 * "cmd && <newline>" doesn't start
4150 * cmd but waits for more input?
4151 * No reason...)
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004152 */
4153 struct pipe *pi = ctx.list_head;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004154 if (pi->num_cmds != 0 /* check #1 */
4155 && pi->followup != PIPE_BG /* check #2 */
4156 ) {
Denys Vlasenko642e71a2011-01-07 15:16:05 +01004157 continue;
Denys Vlasenko98c46d12011-01-18 17:30:07 +01004158 }
Denis Vlasenkof1736072008-07-31 10:09:26 +00004159 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004160 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004161 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004162 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4163 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004164 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004165 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004166 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004167 heredoc_cnt = 0;
4168 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004169 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004170 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004171 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004172 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004173 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004174 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004175
4176 /* "cmd}" or "cmd }..." without semicolon or &:
4177 * } is an ordinary char in this case, even inside { cmd; }
4178 * Pathological example: { ""}; } should exec "}" cmd
4179 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004180 if (ch == '}') {
4181 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4182 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004183 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004184 ) {
4185 goto ordinary_char;
4186 }
4187 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4188 goto skip_end_trigger;
4189 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004190 }
4191
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004192 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004193 && (ch != ';' || heredoc_cnt == 0)
4194#if ENABLE_HUSH_CASE
4195 && (ch != ')'
4196 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004197 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004198 )
4199#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004200 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004201 if (heredoc_cnt) {
4202 /* This is technically valid:
4203 * { cat <<HERE; }; echo Ok
4204 * heredoc
4205 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004206 * HERE
4207 * but we don't support this.
4208 * We require heredoc to be in enclosing {}/(),
4209 * if any.
4210 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004211 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004212 goto parse_error;
4213 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004214 if (done_word(&dest, &ctx)) {
4215 goto parse_error;
4216 }
4217 done_pipe(&ctx, PIPE_SEQ);
4218 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004219 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004220 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004221 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004222 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004223 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004224#if !BB_MMU
4225 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4226 if (pstring)
4227 *pstring = ctx.as_string.data;
4228 else
4229 o_free_unsafe(&ctx.as_string);
4230#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004231 debug_leave();
4232 debug_printf_parse("parse_stream return %p: "
4233 "end_trigger char found\n",
4234 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004235 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004236 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004237 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004238 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004239 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004240 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004241
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004242 /* Catch <, > before deciding whether this word is
4243 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4244 switch (ch) {
4245 case '>':
4246 redir_fd = redirect_opt_num(&dest);
4247 if (done_word(&dest, &ctx)) {
4248 goto parse_error;
4249 }
4250 redir_style = REDIRECT_OVERWRITE;
4251 if (next == '>') {
4252 redir_style = REDIRECT_APPEND;
4253 ch = i_getch(input);
4254 nommu_addchr(&ctx.as_string, ch);
4255 }
4256#if 0
4257 else if (next == '(') {
4258 syntax_error(">(process) not supported");
4259 goto parse_error;
4260 }
4261#endif
4262 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4263 goto parse_error;
4264 continue; /* back to top of while (1) */
4265 case '<':
4266 redir_fd = redirect_opt_num(&dest);
4267 if (done_word(&dest, &ctx)) {
4268 goto parse_error;
4269 }
4270 redir_style = REDIRECT_INPUT;
4271 if (next == '<') {
4272 redir_style = REDIRECT_HEREDOC;
4273 heredoc_cnt++;
4274 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4275 ch = i_getch(input);
4276 nommu_addchr(&ctx.as_string, ch);
4277 } else if (next == '>') {
4278 redir_style = REDIRECT_IO;
4279 ch = i_getch(input);
4280 nommu_addchr(&ctx.as_string, ch);
4281 }
4282#if 0
4283 else if (next == '(') {
4284 syntax_error("<(process) not supported");
4285 goto parse_error;
4286 }
4287#endif
4288 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4289 goto parse_error;
4290 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004291 case '#':
4292 if (dest.length == 0 && !dest.has_quoted_part) {
4293 /* skip "#comment" */
4294 while (1) {
4295 ch = i_peek(input);
4296 if (ch == EOF || ch == '\n')
4297 break;
4298 i_getch(input);
4299 /* note: we do not add it to &ctx.as_string */
4300 }
4301 nommu_addchr(&ctx.as_string, '\n');
4302 continue; /* back to top of while (1) */
4303 }
4304 break;
4305 case '\\':
4306 if (next == '\n') {
4307 /* It's "\<newline>" */
4308#if !BB_MMU
4309 /* Remove trailing '\' from ctx.as_string */
4310 ctx.as_string.data[--ctx.as_string.length] = '\0';
4311#endif
4312 ch = i_getch(input); /* eat it */
4313 continue; /* back to top of while (1) */
4314 }
4315 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004316 }
4317
4318 if (dest.o_assignment == MAYBE_ASSIGNMENT
4319 /* check that we are not in word in "a=1 2>word b=1": */
4320 && !ctx.pending_redirect
4321 ) {
4322 /* ch is a special char and thus this word
4323 * cannot be an assignment */
4324 dest.o_assignment = NOT_ASSIGNMENT;
4325 }
4326
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004327 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4328
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004329 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004330 case '#': /* non-comment #: "echo a#b" etc */
4331 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004332 break;
4333 case '\\':
4334 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004335 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004336 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004337 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004338 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004339 /* note: ch != '\n' (that case does not reach this place) */
4340 o_addchr(&dest, '\\');
4341 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4342 o_addchr(&dest, ch);
4343 nommu_addchr(&ctx.as_string, ch);
4344 /* Example: echo Hello \2>file
4345 * we need to know that word 2 is quoted */
4346 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004347 break;
4348 case '$':
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004349 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004350 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004351 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004352 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004353 }
Eric Andersen25f27032001-04-26 23:22:31 +00004354 break;
4355 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004356 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004357 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004358 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004359 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004360 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004361 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004362 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004363 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004364 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004365 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004366 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004367 }
Eric Andersen25f27032001-04-26 23:22:31 +00004368 break;
4369 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004370 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004371 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004372 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004373 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004374 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004375 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004376 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004377#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004378 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004379 unsigned pos;
4380
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004381 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4382 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004383 pos = dest.length;
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004384 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004385# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004386 o_addstr(&ctx.as_string, dest.data + pos);
4387 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004388# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004389 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4390 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004391 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004392 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004393#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004394 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004395#if ENABLE_HUSH_CASE
4396 case_semi:
4397#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004398 if (done_word(&dest, &ctx)) {
4399 goto parse_error;
4400 }
4401 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004402#if ENABLE_HUSH_CASE
4403 /* Eat multiple semicolons, detect
4404 * whether it means something special */
4405 while (1) {
4406 ch = i_peek(input);
4407 if (ch != ';')
4408 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004409 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004410 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004411 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004412 ctx.ctx_dsemicolon = 1;
4413 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004414 break;
4415 }
4416 }
4417#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004418 new_cmd:
4419 /* We just finished a cmd. New one may start
4420 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004421 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004422 break;
4423 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004424 if (done_word(&dest, &ctx)) {
4425 goto parse_error;
4426 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004427 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004428 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004429 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004430 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004431 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004432 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004433 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004434 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004435 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004436 if (done_word(&dest, &ctx)) {
4437 goto parse_error;
4438 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004439#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004440 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004441 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004442#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004443 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004444 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004445 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004446 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004447 } else {
4448 /* we could pick up a file descriptor choice here
4449 * with redirect_opt_num(), but bash doesn't do it.
4450 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004451 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004452#if !BB_MMU
4453 o_reset_to_empty_unquoted(&ctx.as_string);
4454#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004455 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004456 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004457 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004458#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004459 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004460 if (ctx.ctx_res_w == RES_MATCH
4461 && ctx.command->argv == NULL /* not (word|(... */
4462 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004463 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004464 ) {
4465 continue;
4466 }
4467#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004468 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004469 if (parse_group(&dest, &ctx, input, ch) != 0) {
4470 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004471 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004472 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004473 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004474#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004475 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004476 goto case_semi;
4477#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004478 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004479 /* proper use of this character is caught by end_trigger:
4480 * if we see {, we call parse_group(..., end_trigger='}')
4481 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004482 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004483 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004484 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004485 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004486 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004487 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004488 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004489
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004490 parse_error:
4491 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004492 struct parse_context *pctx;
4493 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004494
4495 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004496 * Sample for finding leaks on syntax error recovery path.
4497 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004498 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004499 * Samples to catch leaks at execution:
4500 * while if (true | {true;}); then echo ok; fi; do break; done
4501 * 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 +00004502 */
4503 pctx = &ctx;
4504 do {
4505 /* Update pipe/command counts,
4506 * otherwise freeing may miss some */
4507 done_pipe(pctx, PIPE_SEQ);
4508 debug_printf_clean("freeing list %p from ctx %p\n",
4509 pctx->list_head, pctx);
4510 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004511 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004512 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004513#if !BB_MMU
4514 o_free_unsafe(&pctx->as_string);
4515#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004516 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004517 if (pctx != &ctx) {
4518 free(pctx);
4519 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004520 IF_HAS_KEYWORDS(pctx = p2;)
4521 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004522 /* Free text, clear all dest fields */
4523 o_free(&dest);
4524 /* If we are not in top-level parse, we return,
4525 * our caller will propagate error.
4526 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004527 if (end_trigger != ';') {
4528#if !BB_MMU
4529 if (pstring)
4530 *pstring = NULL;
4531#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004532 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004533 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004534 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004535 /* Discard cached input, force prompt */
4536 input->p = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004537 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004538 }
Eric Andersen25f27032001-04-26 23:22:31 +00004539}
4540
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004541
4542/*** Execution routines ***/
4543
4544/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004545#if !ENABLE_HUSH_BASH_COMPAT
4546/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4547#define expand_string_to_string(str, do_unbackslash) \
4548 expand_string_to_string(str)
4549#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004550static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004551#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004552static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004553#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004554
4555/* expand_strvec_to_strvec() takes a list of strings, expands
4556 * all variable references within and returns a pointer to
4557 * a list of expanded strings, possibly with larger number
4558 * of strings. (Think VAR="a b"; echo $VAR).
4559 * This new list is allocated as a single malloc block.
4560 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004561 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004562 * Caller can deallocate entire list by single free(list). */
4563
Denys Vlasenko238081f2010-10-03 14:26:26 +02004564/* A horde of its helpers come first: */
4565
4566static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4567{
4568 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004569 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004570
Denys Vlasenko9e800222010-10-03 14:28:04 +02004571#if ENABLE_HUSH_BRACE_EXPANSION
4572 if (c == '{' || c == '}') {
4573 /* { -> \{, } -> \} */
4574 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004575 /* And now we want to add { or } and continue:
4576 * o_addchr(o, c);
4577 * continue;
4578 * luckily, just falling throught achieves this.
4579 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004580 }
4581#endif
4582 o_addchr(o, c);
4583 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004584 /* \z -> \\\z; \<eol> -> \\<eol> */
4585 o_addchr(o, '\\');
4586 if (len) {
4587 len--;
4588 o_addchr(o, '\\');
4589 o_addchr(o, *str++);
4590 }
4591 }
4592 }
4593}
4594
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004595/* Store given string, finalizing the word and starting new one whenever
4596 * we encounter IFS char(s). This is used for expanding variable values.
4597 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4598static int expand_on_ifs(o_string *output, int n, const char *str)
4599{
4600 while (1) {
4601 int word_len = strcspn(str, G.ifs);
4602 if (word_len) {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004603 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004604 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004605 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004606 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004607 * Example: "v='\*'; echo b$v" prints "b\*"
4608 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004609 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004610 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004611 /*/ Why can't we do it easier? */
4612 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4613 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4614 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004615 str += word_len;
4616 }
4617 if (!*str) /* EOL - do not finalize word */
4618 break;
4619 o_addchr(output, '\0');
4620 debug_print_list("expand_on_ifs", output, n);
4621 n = o_save_ptr(output, n);
4622 str += strspn(str, G.ifs); /* skip ifs chars */
4623 }
4624 debug_print_list("expand_on_ifs[1]", output, n);
4625 return n;
4626}
4627
4628/* Helper to expand $((...)) and heredoc body. These act as if
4629 * they are in double quotes, with the exception that they are not :).
4630 * Just the rules are similar: "expand only $var and `cmd`"
4631 *
4632 * Returns malloced string.
4633 * As an optimization, we return NULL if expansion is not needed.
4634 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004635#if !ENABLE_HUSH_BASH_COMPAT
4636/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4637#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4638 encode_then_expand_string(str)
4639#endif
4640static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004641{
4642 char *exp_str;
4643 struct in_str input;
4644 o_string dest = NULL_O_STRING;
4645
4646 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004647 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004648#if ENABLE_HUSH_TICK
4649 && !strchr(str, '`')
4650#endif
4651 ) {
4652 return NULL;
4653 }
4654
4655 /* We need to expand. Example:
4656 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4657 */
4658 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004659 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004660 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004661 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004662 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4663 o_free_unsafe(&dest);
4664 return exp_str;
4665}
4666
4667#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004668static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004669{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004670 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004671 arith_t res;
4672 char *exp_str;
4673
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004674 math_state.lookupvar = get_local_var_value;
4675 math_state.setvar = set_local_var_from_halves;
4676 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004677 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004678 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004679 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004680 if (errmsg_p)
4681 *errmsg_p = math_state.errmsg;
4682 if (math_state.errmsg)
4683 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004684 return res;
4685}
4686#endif
4687
4688#if ENABLE_HUSH_BASH_COMPAT
4689/* ${var/[/]pattern[/repl]} helpers */
4690static char *strstr_pattern(char *val, const char *pattern, int *size)
4691{
4692 while (1) {
4693 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4694 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4695 if (end) {
4696 *size = end - val;
4697 return val;
4698 }
4699 if (*val == '\0')
4700 return NULL;
4701 /* Optimization: if "*pat" did not match the start of "string",
4702 * we know that "tring", "ring" etc will not match too:
4703 */
4704 if (pattern[0] == '*')
4705 return NULL;
4706 val++;
4707 }
4708}
4709static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4710{
4711 char *result = NULL;
4712 unsigned res_len = 0;
4713 unsigned repl_len = strlen(repl);
4714
4715 while (1) {
4716 int size;
4717 char *s = strstr_pattern(val, pattern, &size);
4718 if (!s)
4719 break;
4720
4721 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4722 memcpy(result + res_len, val, s - val);
4723 res_len += s - val;
4724 strcpy(result + res_len, repl);
4725 res_len += repl_len;
4726 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4727
4728 val = s + size;
4729 if (exp_op == '/')
4730 break;
4731 }
4732 if (val[0] && result) {
4733 result = xrealloc(result, res_len + strlen(val) + 1);
4734 strcpy(result + res_len, val);
4735 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4736 }
4737 debug_printf_varexp("result:'%s'\n", result);
4738 return result;
4739}
4740#endif
4741
4742/* Helper:
4743 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4744 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004745static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004746{
4747 const char *val = NULL;
4748 char *to_be_freed = NULL;
4749 char *p = *pp;
4750 char *var;
4751 char first_char;
4752 char exp_op;
4753 char exp_save = exp_save; /* for compiler */
4754 char *exp_saveptr; /* points to expansion operator */
4755 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004756 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004757
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004758 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004759 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004760 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004761 arg0 = arg[0];
4762 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004763 exp_op = 0;
4764
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004765 if (first_char == '#' /* ${#... */
4766 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4767 ) {
4768 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004769 var++;
4770 exp_op = 'L';
4771 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004772 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004773 if (exp_saveptr /* if 2nd char is one of expansion operators */
4774 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4775 ) {
4776 /* ${?:0}, ${#[:]%0} etc */
4777 exp_saveptr = var + 1;
4778 } else {
4779 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4780 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4781 }
4782 exp_op = exp_save = *exp_saveptr;
4783 if (exp_op) {
4784 exp_word = exp_saveptr + 1;
4785 if (exp_op == ':') {
4786 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004787//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004788 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004789 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004790 ) {
4791 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4792 exp_op = ':';
4793 exp_word--;
4794 }
4795 }
4796 *exp_saveptr = '\0';
4797 } /* else: it's not an expansion op, but bare ${var} */
4798 }
4799
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004800 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004801 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004802 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004803 int n = xatoi_positive(var);
4804 if (n < G.global_argc)
4805 val = G.global_argv[n];
4806 /* else val remains NULL: $N with too big N */
4807 } else {
4808 switch (var[0]) {
4809 case '$': /* pid */
4810 val = utoa(G.root_pid);
4811 break;
4812 case '!': /* bg pid */
4813 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4814 break;
4815 case '?': /* exitcode */
4816 val = utoa(G.last_exitcode);
4817 break;
4818 case '#': /* argc */
4819 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4820 break;
4821 default:
4822 val = get_local_var_value(var);
4823 }
4824 }
4825
4826 /* Handle any expansions */
4827 if (exp_op == 'L') {
4828 debug_printf_expand("expand: length(%s)=", val);
4829 val = utoa(val ? strlen(val) : 0);
4830 debug_printf_expand("%s\n", val);
4831 } else if (exp_op) {
4832 if (exp_op == '%' || exp_op == '#') {
4833 /* Standard-mandated substring removal ops:
4834 * ${parameter%word} - remove smallest suffix pattern
4835 * ${parameter%%word} - remove largest suffix pattern
4836 * ${parameter#word} - remove smallest prefix pattern
4837 * ${parameter##word} - remove largest prefix pattern
4838 *
4839 * Word is expanded to produce a glob pattern.
4840 * Then var's value is matched to it and matching part removed.
4841 */
4842 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004843 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004844 char *exp_exp_word;
4845 char *loc;
4846 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02004847 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004848 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004849 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004850 if (exp_exp_word)
4851 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02004852 /* HACK ALERT. We depend here on the fact that
4853 * G.global_argv and results of utoa and get_local_var_value
4854 * are actually in writable memory:
4855 * scan_and_match momentarily stores NULs there. */
4856 t = (char*)val;
4857 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004858 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02004859 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004860 free(exp_exp_word);
4861 if (loc) { /* match was found */
4862 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004863 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004864 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004865 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004866 }
4867 }
4868 }
4869#if ENABLE_HUSH_BASH_COMPAT
4870 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004871 /* It's ${var/[/]pattern[/repl]} thing.
4872 * Note that in encoded form it has TWO parts:
4873 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02004874 * and if // is used, it is encoded as \:
4875 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004876 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004877 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004878 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004879 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004880 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004881 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004882 * by the usual expansion rules:
4883 * >az; >bz;
4884 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4885 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4886 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4887 * v='a bz'; echo ${v/a*z/\z} prints "z"
4888 * (note that a*z _pattern_ is never globbed!)
4889 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004890 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004891 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004892 if (!pattern)
4893 pattern = xstrdup(exp_word);
4894 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4895 *p++ = SPECIAL_VAR_SYMBOL;
4896 exp_word = p;
4897 p = strchr(p, SPECIAL_VAR_SYMBOL);
4898 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004899 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004900 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4901 /* HACK ALERT. We depend here on the fact that
4902 * G.global_argv and results of utoa and get_local_var_value
4903 * are actually in writable memory:
4904 * replace_pattern momentarily stores NULs there. */
4905 t = (char*)val;
4906 to_be_freed = replace_pattern(t,
4907 pattern,
4908 (repl ? repl : exp_word),
4909 exp_op);
4910 if (to_be_freed) /* at least one replace happened */
4911 val = to_be_freed;
4912 free(pattern);
4913 free(repl);
4914 }
4915 }
4916#endif
4917 else if (exp_op == ':') {
4918#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4919 /* It's ${var:N[:M]} bashism.
4920 * Note that in encoded form it has TWO parts:
4921 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4922 */
4923 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02004924 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004925
Denys Vlasenko063847d2010-09-15 13:33:02 +02004926 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4927 if (errmsg)
4928 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004929 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4930 *p++ = SPECIAL_VAR_SYMBOL;
4931 exp_word = p;
4932 p = strchr(p, SPECIAL_VAR_SYMBOL);
4933 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02004934 len = expand_and_evaluate_arith(exp_word, &errmsg);
4935 if (errmsg)
4936 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004937 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004938 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004939 if (beg < 0) /* bash compat */
4940 beg = 0;
4941 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004942 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02004943 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02004944 val = NULL;
4945 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004946 /* Paranoia. What if user entered 9999999999999
4947 * which fits in arith_t but not int? */
4948 if (len >= INT_MAX)
4949 len = INT_MAX;
4950 val = to_be_freed = xstrndup(val + beg, len);
4951 }
4952 debug_printf_varexp("val:'%s'\n", val);
4953 } else
4954#endif
4955 {
4956 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004957 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004958 }
4959 } else { /* one of "-=+?" */
4960 /* Standard-mandated substitution ops:
4961 * ${var?word} - indicate error if unset
4962 * If var is unset, word (or a message indicating it is unset
4963 * if word is null) is written to standard error
4964 * and the shell exits with a non-zero exit status.
4965 * Otherwise, the value of var is substituted.
4966 * ${var-word} - use default value
4967 * If var is unset, word is substituted.
4968 * ${var=word} - assign and use default value
4969 * If var is unset, word is assigned to var.
4970 * In all cases, final value of var is substituted.
4971 * ${var+word} - use alternative value
4972 * If var is unset, null is substituted.
4973 * Otherwise, word is substituted.
4974 *
4975 * Word is subjected to tilde expansion, parameter expansion,
4976 * command substitution, and arithmetic expansion.
4977 * If word is not needed, it is not expanded.
4978 *
4979 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4980 * but also treat null var as if it is unset.
4981 */
4982 int use_word = (!val || ((exp_save == ':') && !val[0]));
4983 if (exp_op == '+')
4984 use_word = !use_word;
4985 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4986 (exp_save == ':') ? "true" : "false", use_word);
4987 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004988 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004989 if (to_be_freed)
4990 exp_word = to_be_freed;
4991 if (exp_op == '?') {
4992 /* mimic bash message */
4993 die_if_script("%s: %s",
4994 var,
4995 exp_word[0] ? exp_word : "parameter null or not set"
4996 );
4997//TODO: how interactive bash aborts expansion mid-command?
4998 } else {
4999 val = exp_word;
5000 }
5001
5002 if (exp_op == '=') {
5003 /* ${var=[word]} or ${var:=[word]} */
5004 if (isdigit(var[0]) || var[0] == '#') {
5005 /* mimic bash message */
5006 die_if_script("$%s: cannot assign in this way", var);
5007 val = NULL;
5008 } else {
5009 char *new_var = xasprintf("%s=%s", var, val);
5010 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5011 }
5012 }
5013 }
5014 } /* one of "-=+?" */
5015
5016 *exp_saveptr = exp_save;
5017 } /* if (exp_op) */
5018
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005019 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005020
5021 *pp = p;
5022 *to_be_freed_pp = to_be_freed;
5023 return val;
5024}
5025
5026/* Expand all variable references in given string, adding words to list[]
5027 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5028 * to be filled). This routine is extremely tricky: has to deal with
5029 * variables/parameters with whitespace, $* and $@, and constructs like
5030 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005031static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005032{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005033 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005034 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005035 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005036 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005037 char *p;
5038
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005039 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5040 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005041 debug_print_list("expand_vars_to_list", output, n);
5042 n = o_save_ptr(output, n);
5043 debug_print_list("expand_vars_to_list[0]", output, n);
5044
5045 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5046 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005047 char *to_be_freed = NULL;
5048 const char *val = NULL;
5049#if ENABLE_HUSH_TICK
5050 o_string subst_result = NULL_O_STRING;
5051#endif
5052#if ENABLE_SH_MATH_SUPPORT
5053 char arith_buf[sizeof(arith_t)*3 + 2];
5054#endif
5055 o_addblock(output, arg, p - arg);
5056 debug_print_list("expand_vars_to_list[1]", output, n);
5057 arg = ++p;
5058 p = strchr(p, SPECIAL_VAR_SYMBOL);
5059
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005060 /* Fetch special var name (if it is indeed one of them)
5061 * and quote bit, force the bit on if singleword expansion -
5062 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005063 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005064
5065 /* Is this variable quoted and thus expansion can't be null?
5066 * "$@" is special. Even if quoted, it can still
5067 * expand to nothing (not even an empty string),
5068 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005069 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005070 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005071
5072 switch (first_ch & 0x7f) {
5073 /* Highest bit in first_ch indicates that var is double-quoted */
5074 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005075 case '@': {
5076 int i;
5077 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005078 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005079 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005080 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005081 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005082 while (G.global_argv[i]) {
5083 n = expand_on_ifs(output, n, G.global_argv[i]);
5084 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5085 if (G.global_argv[i++][0] && G.global_argv[i]) {
5086 /* this argv[] is not empty and not last:
5087 * put terminating NUL, start new word */
5088 o_addchr(output, '\0');
5089 debug_print_list("expand_vars_to_list[2]", output, n);
5090 n = o_save_ptr(output, n);
5091 debug_print_list("expand_vars_to_list[3]", output, n);
5092 }
5093 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005094 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005095 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005096 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005097 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005098 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005099 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005100 while (1) {
5101 o_addQstr(output, G.global_argv[i]);
5102 if (++i >= G.global_argc)
5103 break;
5104 o_addchr(output, '\0');
5105 debug_print_list("expand_vars_to_list[4]", output, n);
5106 n = o_save_ptr(output, n);
5107 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005108 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005109 while (1) {
5110 o_addQstr(output, G.global_argv[i]);
5111 if (!G.global_argv[++i])
5112 break;
5113 if (G.ifs[0])
5114 o_addchr(output, G.ifs[0]);
5115 }
5116 }
5117 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005118 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005119 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5120 /* "Empty variable", used to make "" etc to not disappear */
5121 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005122 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005123 break;
5124#if ENABLE_HUSH_TICK
5125 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005126 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005127 arg++;
5128 /* Can't just stuff it into output o_string,
5129 * expanded result may need to be globbed
5130 * and $IFS-splitted */
5131 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5132 G.last_exitcode = process_command_subs(&subst_result, arg);
5133 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5134 val = subst_result.data;
5135 goto store_val;
5136#endif
5137#if ENABLE_SH_MATH_SUPPORT
5138 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5139 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005140
5141 arg++; /* skip '+' */
5142 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5143 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005144 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005145 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5146 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005147 val = arith_buf;
5148 break;
5149 }
5150#endif
5151 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005152 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005153 IF_HUSH_TICK(store_val:)
5154 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005155 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5156 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005157 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005158 n = expand_on_ifs(output, n, val);
5159 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005160 }
5161 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005162 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5163 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005164 }
5165 break;
5166
5167 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5168
5169 if (val && val[0]) {
5170 o_addQstr(output, val);
5171 }
5172 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005173
5174 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5175 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005176 if (*p != SPECIAL_VAR_SYMBOL)
5177 *p = SPECIAL_VAR_SYMBOL;
5178
5179#if ENABLE_HUSH_TICK
5180 o_free(&subst_result);
5181#endif
5182 arg = ++p;
5183 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5184
5185 if (arg[0]) {
5186 debug_print_list("expand_vars_to_list[a]", output, n);
5187 /* this part is literal, and it was already pre-quoted
5188 * if needed (much earlier), do not use o_addQstr here! */
5189 o_addstr_with_NUL(output, arg);
5190 debug_print_list("expand_vars_to_list[b]", output, n);
5191 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005192 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005193 ) {
5194 n--;
5195 /* allow to reuse list[n] later without re-growth */
5196 output->has_empty_slot = 1;
5197 } else {
5198 o_addchr(output, '\0');
5199 }
5200
5201 return n;
5202}
5203
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005204static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005205{
5206 int n;
5207 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005208 o_string output = NULL_O_STRING;
5209
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005210 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005211
5212 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005213 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005214 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005215 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005216 }
5217 debug_print_list("expand_variables", &output, n);
5218
5219 /* output.data (malloced in one block) gets returned in "list" */
5220 list = o_finalize_list(&output, n);
5221 debug_print_strings("expand_variables[1]", list);
5222 return list;
5223}
5224
5225static char **expand_strvec_to_strvec(char **argv)
5226{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005227 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005228}
5229
5230#if ENABLE_HUSH_BASH_COMPAT
5231static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5232{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005233 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005234}
5235#endif
5236
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005237/* Used for expansion of right hand of assignments,
5238 * $((...)), heredocs, variable espansion parts.
5239 *
5240 * NB: should NOT do globbing!
5241 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5242 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005243static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005244{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005245#if !ENABLE_HUSH_BASH_COMPAT
5246 const int do_unbackslash = 1;
5247#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005248 char *argv[2], **list;
5249
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005250 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005251 /* This is generally an optimization, but it also
5252 * handles "", which otherwise trips over !list[0] check below.
5253 * (is this ever happens that we actually get str="" here?)
5254 */
5255 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5256 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005257 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005258 return xstrdup(str);
5259 }
5260
5261 argv[0] = (char*)str;
5262 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005263 list = expand_variables(argv, do_unbackslash
5264 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5265 : EXP_FLAG_SINGLEWORD
5266 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005267 if (HUSH_DEBUG)
5268 if (!list[0] || list[1])
5269 bb_error_msg_and_die("BUG in varexp2");
5270 /* actually, just move string 2*sizeof(char*) bytes back */
5271 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005272 if (do_unbackslash)
5273 unbackslash((char*)list);
5274 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005275 return (char*)list;
5276}
5277
5278/* Used for "eval" builtin */
5279static char* expand_strvec_to_string(char **argv)
5280{
5281 char **list;
5282
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005283 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005284 /* Convert all NULs to spaces */
5285 if (list[0]) {
5286 int n = 1;
5287 while (list[n]) {
5288 if (HUSH_DEBUG)
5289 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5290 bb_error_msg_and_die("BUG in varexp3");
5291 /* bash uses ' ' regardless of $IFS contents */
5292 list[n][-1] = ' ';
5293 n++;
5294 }
5295 }
5296 overlapping_strcpy((char*)list, list[0]);
5297 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5298 return (char*)list;
5299}
5300
5301static char **expand_assignments(char **argv, int count)
5302{
5303 int i;
5304 char **p;
5305
5306 G.expanded_assignments = p = NULL;
5307 /* Expand assignments into one string each */
5308 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005309 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005310 }
5311 G.expanded_assignments = NULL;
5312 return p;
5313}
5314
5315
5316#if BB_MMU
5317/* never called */
5318void re_execute_shell(char ***to_free, const char *s,
5319 char *g_argv0, char **g_argv,
5320 char **builtin_argv) NORETURN;
5321
5322static void reset_traps_to_defaults(void)
5323{
5324 /* This function is always called in a child shell
5325 * after fork (not vfork, NOMMU doesn't use this function).
5326 */
5327 unsigned sig;
5328 unsigned mask;
5329
5330 /* Child shells are not interactive.
5331 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5332 * Testcase: (while :; do :; done) + ^Z should background.
5333 * Same goes for SIGTERM, SIGHUP, SIGINT.
5334 */
5335 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5336 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5337
5338 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5339 * Stupid. It can be done with *single* &= op, but we can't use
5340 * the fact that G.blocked_set is implemented as a bitmask
5341 * in libc... */
5342 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5343 sig = 1;
5344 while (1) {
5345 if (mask & 1) {
5346 /* Careful. Only if no trap or trap is not "" */
5347 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5348 sigdelset(&G.blocked_set, sig);
5349 }
5350 mask >>= 1;
5351 if (!mask)
5352 break;
5353 sig++;
5354 }
5355 /* Our homegrown sig mask is saner to work with :) */
5356 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5357
5358 /* Resetting all traps to default except empty ones */
5359 mask = G.non_DFL_mask;
5360 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5361 if (!G.traps[sig] || !G.traps[sig][0])
5362 continue;
5363 free(G.traps[sig]);
5364 G.traps[sig] = NULL;
5365 /* There is no signal for 0 (EXIT) */
5366 if (sig == 0)
5367 continue;
5368 /* There was a trap handler, we just removed it.
5369 * But if sig still has non-DFL handling,
5370 * we should not unblock the sig. */
5371 if (mask & 1)
5372 continue;
5373 sigdelset(&G.blocked_set, sig);
5374 }
5375 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5376}
5377
5378#else /* !BB_MMU */
5379
5380static void re_execute_shell(char ***to_free, const char *s,
5381 char *g_argv0, char **g_argv,
5382 char **builtin_argv) NORETURN;
5383static void re_execute_shell(char ***to_free, const char *s,
5384 char *g_argv0, char **g_argv,
5385 char **builtin_argv)
5386{
5387# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5388 /* delims + 2 * (number of bytes in printed hex numbers) */
5389 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5390 char *heredoc_argv[4];
5391 struct variable *cur;
5392# if ENABLE_HUSH_FUNCTIONS
5393 struct function *funcp;
5394# endif
5395 char **argv, **pp;
5396 unsigned cnt;
5397 unsigned long long empty_trap_mask;
5398
5399 if (!g_argv0) { /* heredoc */
5400 argv = heredoc_argv;
5401 argv[0] = (char *) G.argv0_for_re_execing;
5402 argv[1] = (char *) "-<";
5403 argv[2] = (char *) s;
5404 argv[3] = NULL;
5405 pp = &argv[3]; /* used as pointer to empty environment */
5406 goto do_exec;
5407 }
5408
5409 cnt = 0;
5410 pp = builtin_argv;
5411 if (pp) while (*pp++)
5412 cnt++;
5413
5414 empty_trap_mask = 0;
5415 if (G.traps) {
5416 int sig;
5417 for (sig = 1; sig < NSIG; sig++) {
5418 if (G.traps[sig] && !G.traps[sig][0])
5419 empty_trap_mask |= 1LL << sig;
5420 }
5421 }
5422
5423 sprintf(param_buf, NOMMU_HACK_FMT
5424 , (unsigned) G.root_pid
5425 , (unsigned) G.root_ppid
5426 , (unsigned) G.last_bg_pid
5427 , (unsigned) G.last_exitcode
5428 , cnt
5429 , empty_trap_mask
5430 IF_HUSH_LOOPS(, G.depth_of_loop)
5431 );
5432# undef NOMMU_HACK_FMT
5433 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5434 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5435 */
5436 cnt += 6;
5437 for (cur = G.top_var; cur; cur = cur->next) {
5438 if (!cur->flg_export || cur->flg_read_only)
5439 cnt += 2;
5440 }
5441# if ENABLE_HUSH_FUNCTIONS
5442 for (funcp = G.top_func; funcp; funcp = funcp->next)
5443 cnt += 3;
5444# endif
5445 pp = g_argv;
5446 while (*pp++)
5447 cnt++;
5448 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5449 *pp++ = (char *) G.argv0_for_re_execing;
5450 *pp++ = param_buf;
5451 for (cur = G.top_var; cur; cur = cur->next) {
5452 if (strcmp(cur->varstr, hush_version_str) == 0)
5453 continue;
5454 if (cur->flg_read_only) {
5455 *pp++ = (char *) "-R";
5456 *pp++ = cur->varstr;
5457 } else if (!cur->flg_export) {
5458 *pp++ = (char *) "-V";
5459 *pp++ = cur->varstr;
5460 }
5461 }
5462# if ENABLE_HUSH_FUNCTIONS
5463 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5464 *pp++ = (char *) "-F";
5465 *pp++ = funcp->name;
5466 *pp++ = funcp->body_as_string;
5467 }
5468# endif
5469 /* We can pass activated traps here. Say, -Tnn:trap_string
5470 *
5471 * However, POSIX says that subshells reset signals with traps
5472 * to SIG_DFL.
5473 * I tested bash-3.2 and it not only does that with true subshells
5474 * of the form ( list ), but with any forked children shells.
5475 * I set trap "echo W" WINCH; and then tried:
5476 *
5477 * { echo 1; sleep 20; echo 2; } &
5478 * while true; do echo 1; sleep 20; echo 2; break; done &
5479 * true | { echo 1; sleep 20; echo 2; } | cat
5480 *
5481 * In all these cases sending SIGWINCH to the child shell
5482 * did not run the trap. If I add trap "echo V" WINCH;
5483 * _inside_ group (just before echo 1), it works.
5484 *
5485 * I conclude it means we don't need to pass active traps here.
5486 * Even if we would use signal handlers instead of signal masking
5487 * in order to implement trap handling,
5488 * exec syscall below resets signals to SIG_DFL for us.
5489 */
5490 *pp++ = (char *) "-c";
5491 *pp++ = (char *) s;
5492 if (builtin_argv) {
5493 while (*++builtin_argv)
5494 *pp++ = *builtin_argv;
5495 *pp++ = (char *) "";
5496 }
5497 *pp++ = g_argv0;
5498 while (*g_argv)
5499 *pp++ = *g_argv++;
5500 /* *pp = NULL; - is already there */
5501 pp = environ;
5502
5503 do_exec:
5504 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5505 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5506 execve(bb_busybox_exec_path, argv, pp);
5507 /* Fallback. Useful for init=/bin/hush usage etc */
5508 if (argv[0][0] == '/')
5509 execve(argv[0], argv, pp);
5510 xfunc_error_retval = 127;
5511 bb_error_msg_and_die("can't re-execute the shell");
5512}
5513#endif /* !BB_MMU */
5514
5515
5516static int run_and_free_list(struct pipe *pi);
5517
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005518/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005519 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5520 * end_trigger controls how often we stop parsing
5521 * NUL: parse all, execute, return
5522 * ';': parse till ';' or newline, execute, repeat till EOF
5523 */
5524static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005525{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005526 /* Why we need empty flag?
5527 * An obscure corner case "false; ``; echo $?":
5528 * empty command in `` should still set $? to 0.
5529 * But we can't just set $? to 0 at the start,
5530 * this breaks "false; echo `echo $?`" case.
5531 */
5532 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005533 while (1) {
5534 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005535
Denys Vlasenkoa1463192011-01-18 17:55:04 +01005536#if ENABLE_HUSH_INTERACTIVE
5537 if (end_trigger == ';')
5538 inp->promptmode = 0; /* PS1 */
5539#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005540 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005541 if (!pipe_list) { /* EOF */
5542 if (empty)
5543 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005544 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005545 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005546 debug_print_tree(pipe_list, 0);
5547 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5548 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005549 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005550 }
Eric Andersen25f27032001-04-26 23:22:31 +00005551}
5552
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005553static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005554{
5555 struct in_str input;
5556 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005557 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005558}
5559
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005560static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005561{
Eric Andersen25f27032001-04-26 23:22:31 +00005562 struct in_str input;
5563 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005564 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005565}
5566
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005567#if ENABLE_HUSH_TICK
5568static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5569{
5570 pid_t pid;
5571 int channel[2];
5572# if !BB_MMU
5573 char **to_free = NULL;
5574# endif
5575
5576 xpipe(channel);
5577 pid = BB_MMU ? xfork() : xvfork();
5578 if (pid == 0) { /* child */
5579 disable_restore_tty_pgrp_on_exit();
5580 /* Process substitution is not considered to be usual
5581 * 'command execution'.
5582 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5583 */
5584 bb_signals(0
5585 + (1 << SIGTSTP)
5586 + (1 << SIGTTIN)
5587 + (1 << SIGTTOU)
5588 , SIG_IGN);
5589 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5590 close(channel[0]); /* NB: close _first_, then move fd! */
5591 xmove_fd(channel[1], 1);
5592 /* Prevent it from trying to handle ctrl-z etc */
5593 IF_HUSH_JOB(G.run_list_level = 1;)
5594 /* Awful hack for `trap` or $(trap).
5595 *
5596 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5597 * contains an example where "trap" is executed in a subshell:
5598 *
5599 * save_traps=$(trap)
5600 * ...
5601 * eval "$save_traps"
5602 *
5603 * Standard does not say that "trap" in subshell shall print
5604 * parent shell's traps. It only says that its output
5605 * must have suitable form, but then, in the above example
5606 * (which is not supposed to be normative), it implies that.
5607 *
5608 * bash (and probably other shell) does implement it
5609 * (traps are reset to defaults, but "trap" still shows them),
5610 * but as a result, "trap" logic is hopelessly messed up:
5611 *
5612 * # trap
5613 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5614 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5615 * # true | trap <--- trap is in subshell - no output (ditto)
5616 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5617 * trap -- 'echo Ho' SIGWINCH
5618 * # echo `(trap)` <--- in subshell in subshell - output
5619 * trap -- 'echo Ho' SIGWINCH
5620 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5621 * trap -- 'echo Ho' SIGWINCH
5622 *
5623 * The rules when to forget and when to not forget traps
5624 * get really complex and nonsensical.
5625 *
5626 * Our solution: ONLY bare $(trap) or `trap` is special.
5627 */
5628 s = skip_whitespace(s);
5629 if (strncmp(s, "trap", 4) == 0
5630 && skip_whitespace(s + 4)[0] == '\0'
5631 ) {
5632 static const char *const argv[] = { NULL, NULL };
5633 builtin_trap((char**)argv);
5634 exit(0); /* not _exit() - we need to fflush */
5635 }
5636# if BB_MMU
5637 reset_traps_to_defaults();
5638 parse_and_run_string(s);
5639 _exit(G.last_exitcode);
5640# else
5641 /* We re-execute after vfork on NOMMU. This makes this script safe:
5642 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5643 * huge=`cat BIG` # was blocking here forever
5644 * echo OK
5645 */
5646 re_execute_shell(&to_free,
5647 s,
5648 G.global_argv[0],
5649 G.global_argv + 1,
5650 NULL);
5651# endif
5652 }
5653
5654 /* parent */
5655 *pid_p = pid;
5656# if ENABLE_HUSH_FAST
5657 G.count_SIGCHLD++;
5658//bb_error_msg("[%d] fork in generate_stream_from_string:"
5659// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5660// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5661# endif
5662 enable_restore_tty_pgrp_on_exit();
5663# if !BB_MMU
5664 free(to_free);
5665# endif
5666 close(channel[1]);
5667 close_on_exec_on(channel[0]);
5668 return xfdopen_for_read(channel[0]);
5669}
5670
5671/* Return code is exit status of the process that is run. */
5672static int process_command_subs(o_string *dest, const char *s)
5673{
5674 FILE *fp;
5675 struct in_str pipe_str;
5676 pid_t pid;
5677 int status, ch, eol_cnt;
5678
5679 fp = generate_stream_from_string(s, &pid);
5680
5681 /* Now send results of command back into original context */
5682 setup_file_in_str(&pipe_str, fp);
5683 eol_cnt = 0;
5684 while ((ch = i_getch(&pipe_str)) != EOF) {
5685 if (ch == '\n') {
5686 eol_cnt++;
5687 continue;
5688 }
5689 while (eol_cnt) {
5690 o_addchr(dest, '\n');
5691 eol_cnt--;
5692 }
5693 o_addQchr(dest, ch);
5694 }
5695
5696 debug_printf("done reading from `cmd` pipe, closing it\n");
5697 fclose(fp);
5698 /* We need to extract exitcode. Test case
5699 * "true; echo `sleep 1; false` $?"
5700 * should print 1 */
5701 safe_waitpid(pid, &status, 0);
5702 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5703 return WEXITSTATUS(status);
5704}
5705#endif /* ENABLE_HUSH_TICK */
5706
5707
5708static void setup_heredoc(struct redir_struct *redir)
5709{
5710 struct fd_pair pair;
5711 pid_t pid;
5712 int len, written;
5713 /* the _body_ of heredoc (misleading field name) */
5714 const char *heredoc = redir->rd_filename;
5715 char *expanded;
5716#if !BB_MMU
5717 char **to_free;
5718#endif
5719
5720 expanded = NULL;
5721 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005722 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005723 if (expanded)
5724 heredoc = expanded;
5725 }
5726 len = strlen(heredoc);
5727
5728 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5729 xpiped_pair(pair);
5730 xmove_fd(pair.rd, redir->rd_fd);
5731
5732 /* Try writing without forking. Newer kernels have
5733 * dynamically growing pipes. Must use non-blocking write! */
5734 ndelay_on(pair.wr);
5735 while (1) {
5736 written = write(pair.wr, heredoc, len);
5737 if (written <= 0)
5738 break;
5739 len -= written;
5740 if (len == 0) {
5741 close(pair.wr);
5742 free(expanded);
5743 return;
5744 }
5745 heredoc += written;
5746 }
5747 ndelay_off(pair.wr);
5748
5749 /* Okay, pipe buffer was not big enough */
5750 /* Note: we must not create a stray child (bastard? :)
5751 * for the unsuspecting parent process. Child creates a grandchild
5752 * and exits before parent execs the process which consumes heredoc
5753 * (that exec happens after we return from this function) */
5754#if !BB_MMU
5755 to_free = NULL;
5756#endif
5757 pid = xvfork();
5758 if (pid == 0) {
5759 /* child */
5760 disable_restore_tty_pgrp_on_exit();
5761 pid = BB_MMU ? xfork() : xvfork();
5762 if (pid != 0)
5763 _exit(0);
5764 /* grandchild */
5765 close(redir->rd_fd); /* read side of the pipe */
5766#if BB_MMU
5767 full_write(pair.wr, heredoc, len); /* may loop or block */
5768 _exit(0);
5769#else
5770 /* Delegate blocking writes to another process */
5771 xmove_fd(pair.wr, STDOUT_FILENO);
5772 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5773#endif
5774 }
5775 /* parent */
5776#if ENABLE_HUSH_FAST
5777 G.count_SIGCHLD++;
5778//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5779#endif
5780 enable_restore_tty_pgrp_on_exit();
5781#if !BB_MMU
5782 free(to_free);
5783#endif
5784 close(pair.wr);
5785 free(expanded);
5786 wait(NULL); /* wait till child has died */
5787}
5788
5789/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5790 * and stderr if they are redirected. */
5791static int setup_redirects(struct command *prog, int squirrel[])
5792{
5793 int openfd, mode;
5794 struct redir_struct *redir;
5795
5796 for (redir = prog->redirects; redir; redir = redir->next) {
5797 if (redir->rd_type == REDIRECT_HEREDOC2) {
5798 /* rd_fd<<HERE case */
5799 if (squirrel && redir->rd_fd < 3
5800 && squirrel[redir->rd_fd] < 0
5801 ) {
5802 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5803 }
5804 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5805 * of the heredoc */
5806 debug_printf_parse("set heredoc '%s'\n",
5807 redir->rd_filename);
5808 setup_heredoc(redir);
5809 continue;
5810 }
5811
5812 if (redir->rd_dup == REDIRFD_TO_FILE) {
5813 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5814 char *p;
5815 if (redir->rd_filename == NULL) {
5816 /* Something went wrong in the parse.
5817 * Pretend it didn't happen */
5818 bb_error_msg("bug in redirect parse");
5819 continue;
5820 }
5821 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005822 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005823 openfd = open_or_warn(p, mode);
5824 free(p);
5825 if (openfd < 0) {
5826 /* this could get lost if stderr has been redirected, but
5827 * bash and ash both lose it as well (though zsh doesn't!) */
5828//what the above comment tries to say?
5829 return 1;
5830 }
5831 } else {
5832 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5833 openfd = redir->rd_dup;
5834 }
5835
5836 if (openfd != redir->rd_fd) {
5837 if (squirrel && redir->rd_fd < 3
5838 && squirrel[redir->rd_fd] < 0
5839 ) {
5840 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5841 }
5842 if (openfd == REDIRFD_CLOSE) {
5843 /* "n>-" means "close me" */
5844 close(redir->rd_fd);
5845 } else {
5846 xdup2(openfd, redir->rd_fd);
5847 if (redir->rd_dup == REDIRFD_TO_FILE)
5848 close(openfd);
5849 }
5850 }
5851 }
5852 return 0;
5853}
5854
5855static void restore_redirects(int squirrel[])
5856{
5857 int i, fd;
5858 for (i = 0; i < 3; i++) {
5859 fd = squirrel[i];
5860 if (fd != -1) {
5861 /* We simply die on error */
5862 xmove_fd(fd, i);
5863 }
5864 }
5865}
5866
5867static char *find_in_path(const char *arg)
5868{
5869 char *ret = NULL;
5870 const char *PATH = get_local_var_value("PATH");
5871
5872 if (!PATH)
5873 return NULL;
5874
5875 while (1) {
5876 const char *end = strchrnul(PATH, ':');
5877 int sz = end - PATH; /* must be int! */
5878
5879 free(ret);
5880 if (sz != 0) {
5881 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5882 } else {
5883 /* We have xxx::yyyy in $PATH,
5884 * it means "use current dir" */
5885 ret = xstrdup(arg);
5886 }
5887 if (access(ret, F_OK) == 0)
5888 break;
5889
5890 if (*end == '\0') {
5891 free(ret);
5892 return NULL;
5893 }
5894 PATH = end + 1;
5895 }
5896
5897 return ret;
5898}
5899
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005900static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005901 const struct built_in_command *x,
5902 const struct built_in_command *end)
5903{
5904 while (x != end) {
5905 if (strcmp(name, x->b_cmd) != 0) {
5906 x++;
5907 continue;
5908 }
5909 debug_printf_exec("found builtin '%s'\n", name);
5910 return x;
5911 }
5912 return NULL;
5913}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005914static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005915{
5916 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5917}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005918static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005919{
5920 const struct built_in_command *x = find_builtin1(name);
5921 if (x)
5922 return x;
5923 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5924}
5925
5926#if ENABLE_HUSH_FUNCTIONS
5927static struct function **find_function_slot(const char *name)
5928{
5929 struct function **funcpp = &G.top_func;
5930 while (*funcpp) {
5931 if (strcmp(name, (*funcpp)->name) == 0) {
5932 break;
5933 }
5934 funcpp = &(*funcpp)->next;
5935 }
5936 return funcpp;
5937}
5938
5939static const struct function *find_function(const char *name)
5940{
5941 const struct function *funcp = *find_function_slot(name);
5942 if (funcp)
5943 debug_printf_exec("found function '%s'\n", name);
5944 return funcp;
5945}
5946
5947/* Note: takes ownership on name ptr */
5948static struct function *new_function(char *name)
5949{
5950 struct function **funcpp = find_function_slot(name);
5951 struct function *funcp = *funcpp;
5952
5953 if (funcp != NULL) {
5954 struct command *cmd = funcp->parent_cmd;
5955 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5956 if (!cmd) {
5957 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5958 free(funcp->name);
5959 /* Note: if !funcp->body, do not free body_as_string!
5960 * This is a special case of "-F name body" function:
5961 * body_as_string was not malloced! */
5962 if (funcp->body) {
5963 free_pipe_list(funcp->body);
5964# if !BB_MMU
5965 free(funcp->body_as_string);
5966# endif
5967 }
5968 } else {
5969 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5970 cmd->argv[0] = funcp->name;
5971 cmd->group = funcp->body;
5972# if !BB_MMU
5973 cmd->group_as_string = funcp->body_as_string;
5974# endif
5975 }
5976 } else {
5977 debug_printf_exec("remembering new function '%s'\n", name);
5978 funcp = *funcpp = xzalloc(sizeof(*funcp));
5979 /*funcp->next = NULL;*/
5980 }
5981
5982 funcp->name = name;
5983 return funcp;
5984}
5985
5986static void unset_func(const char *name)
5987{
5988 struct function **funcpp = find_function_slot(name);
5989 struct function *funcp = *funcpp;
5990
5991 if (funcp != NULL) {
5992 debug_printf_exec("freeing function '%s'\n", funcp->name);
5993 *funcpp = funcp->next;
5994 /* funcp is unlinked now, deleting it.
5995 * Note: if !funcp->body, the function was created by
5996 * "-F name body", do not free ->body_as_string
5997 * and ->name as they were not malloced. */
5998 if (funcp->body) {
5999 free_pipe_list(funcp->body);
6000 free(funcp->name);
6001# if !BB_MMU
6002 free(funcp->body_as_string);
6003# endif
6004 }
6005 free(funcp);
6006 }
6007}
6008
6009# if BB_MMU
6010#define exec_function(to_free, funcp, argv) \
6011 exec_function(funcp, argv)
6012# endif
6013static void exec_function(char ***to_free,
6014 const struct function *funcp,
6015 char **argv) NORETURN;
6016static void exec_function(char ***to_free,
6017 const struct function *funcp,
6018 char **argv)
6019{
6020# if BB_MMU
6021 int n = 1;
6022
6023 argv[0] = G.global_argv[0];
6024 G.global_argv = argv;
6025 while (*++argv)
6026 n++;
6027 G.global_argc = n;
6028 /* On MMU, funcp->body is always non-NULL */
6029 n = run_list(funcp->body);
6030 fflush_all();
6031 _exit(n);
6032# else
6033 re_execute_shell(to_free,
6034 funcp->body_as_string,
6035 G.global_argv[0],
6036 argv + 1,
6037 NULL);
6038# endif
6039}
6040
6041static int run_function(const struct function *funcp, char **argv)
6042{
6043 int rc;
6044 save_arg_t sv;
6045 smallint sv_flg;
6046
6047 save_and_replace_G_args(&sv, argv);
6048
6049 /* "we are in function, ok to use return" */
6050 sv_flg = G.flag_return_in_progress;
6051 G.flag_return_in_progress = -1;
6052# if ENABLE_HUSH_LOCAL
6053 G.func_nest_level++;
6054# endif
6055
6056 /* On MMU, funcp->body is always non-NULL */
6057# if !BB_MMU
6058 if (!funcp->body) {
6059 /* Function defined by -F */
6060 parse_and_run_string(funcp->body_as_string);
6061 rc = G.last_exitcode;
6062 } else
6063# endif
6064 {
6065 rc = run_list(funcp->body);
6066 }
6067
6068# if ENABLE_HUSH_LOCAL
6069 {
6070 struct variable *var;
6071 struct variable **var_pp;
6072
6073 var_pp = &G.top_var;
6074 while ((var = *var_pp) != NULL) {
6075 if (var->func_nest_level < G.func_nest_level) {
6076 var_pp = &var->next;
6077 continue;
6078 }
6079 /* Unexport */
6080 if (var->flg_export)
6081 bb_unsetenv(var->varstr);
6082 /* Remove from global list */
6083 *var_pp = var->next;
6084 /* Free */
6085 if (!var->max_len)
6086 free(var->varstr);
6087 free(var);
6088 }
6089 G.func_nest_level--;
6090 }
6091# endif
6092 G.flag_return_in_progress = sv_flg;
6093
6094 restore_G_args(&sv, argv);
6095
6096 return rc;
6097}
6098#endif /* ENABLE_HUSH_FUNCTIONS */
6099
6100
6101#if BB_MMU
6102#define exec_builtin(to_free, x, argv) \
6103 exec_builtin(x, argv)
6104#else
6105#define exec_builtin(to_free, x, argv) \
6106 exec_builtin(to_free, argv)
6107#endif
6108static void exec_builtin(char ***to_free,
6109 const struct built_in_command *x,
6110 char **argv) NORETURN;
6111static void exec_builtin(char ***to_free,
6112 const struct built_in_command *x,
6113 char **argv)
6114{
6115#if BB_MMU
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006116 int rcode;
6117 fflush_all();
6118 rcode = x->b_function(argv);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006119 fflush_all();
6120 _exit(rcode);
6121#else
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006122 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006123 /* On NOMMU, we must never block!
6124 * Example: { sleep 99 | read line; } & echo Ok
6125 */
6126 re_execute_shell(to_free,
6127 argv[0],
6128 G.global_argv[0],
6129 G.global_argv + 1,
6130 argv);
6131#endif
6132}
6133
6134
6135static void execvp_or_die(char **argv) NORETURN;
6136static void execvp_or_die(char **argv)
6137{
6138 debug_printf_exec("execing '%s'\n", argv[0]);
6139 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6140 execvp(argv[0], argv);
6141 bb_perror_msg("can't execute '%s'", argv[0]);
6142 _exit(127); /* bash compat */
6143}
6144
6145#if ENABLE_HUSH_MODE_X
6146static void dump_cmd_in_x_mode(char **argv)
6147{
6148 if (G_x_mode && argv) {
6149 /* We want to output the line in one write op */
6150 char *buf, *p;
6151 int len;
6152 int n;
6153
6154 len = 3;
6155 n = 0;
6156 while (argv[n])
6157 len += strlen(argv[n++]) + 1;
6158 buf = xmalloc(len);
6159 buf[0] = '+';
6160 p = buf + 1;
6161 n = 0;
6162 while (argv[n])
6163 p += sprintf(p, " %s", argv[n++]);
6164 *p++ = '\n';
6165 *p = '\0';
6166 fputs(buf, stderr);
6167 free(buf);
6168 }
6169}
6170#else
6171# define dump_cmd_in_x_mode(argv) ((void)0)
6172#endif
6173
6174#if BB_MMU
6175#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6176 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6177#define pseudo_exec(nommu_save, command, argv_expanded) \
6178 pseudo_exec(command, argv_expanded)
6179#endif
6180
6181/* Called after [v]fork() in run_pipe, or from builtin_exec.
6182 * Never returns.
6183 * Don't exit() here. If you don't exec, use _exit instead.
6184 * The at_exit handlers apparently confuse the calling process,
6185 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6186static void pseudo_exec_argv(nommu_save_t *nommu_save,
6187 char **argv, int assignment_cnt,
6188 char **argv_expanded) NORETURN;
6189static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6190 char **argv, int assignment_cnt,
6191 char **argv_expanded)
6192{
6193 char **new_env;
6194
6195 new_env = expand_assignments(argv, assignment_cnt);
6196 dump_cmd_in_x_mode(new_env);
6197
6198 if (!argv[assignment_cnt]) {
6199 /* Case when we are here: ... | var=val | ...
6200 * (note that we do not exit early, i.e., do not optimize out
6201 * expand_assignments(): think about ... | var=`sleep 1` | ...
6202 */
6203 free_strings(new_env);
6204 _exit(EXIT_SUCCESS);
6205 }
6206
6207#if BB_MMU
6208 set_vars_and_save_old(new_env);
6209 free(new_env); /* optional */
6210 /* we can also destroy set_vars_and_save_old's return value,
6211 * to save memory */
6212#else
6213 nommu_save->new_env = new_env;
6214 nommu_save->old_vars = set_vars_and_save_old(new_env);
6215#endif
6216
6217 if (argv_expanded) {
6218 argv = argv_expanded;
6219 } else {
6220 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6221#if !BB_MMU
6222 nommu_save->argv = argv;
6223#endif
6224 }
6225 dump_cmd_in_x_mode(argv);
6226
6227#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6228 if (strchr(argv[0], '/') != NULL)
6229 goto skip;
6230#endif
6231
6232 /* Check if the command matches any of the builtins.
6233 * Depending on context, this might be redundant. But it's
6234 * easier to waste a few CPU cycles than it is to figure out
6235 * if this is one of those cases.
6236 */
6237 {
6238 /* On NOMMU, it is more expensive to re-execute shell
6239 * just in order to run echo or test builtin.
6240 * It's better to skip it here and run corresponding
6241 * non-builtin later. */
6242 const struct built_in_command *x;
6243 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6244 if (x) {
6245 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6246 }
6247 }
6248#if ENABLE_HUSH_FUNCTIONS
6249 /* Check if the command matches any functions */
6250 {
6251 const struct function *funcp = find_function(argv[0]);
6252 if (funcp) {
6253 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6254 }
6255 }
6256#endif
6257
6258#if ENABLE_FEATURE_SH_STANDALONE
6259 /* Check if the command matches any busybox applets */
6260 {
6261 int a = find_applet_by_name(argv[0]);
6262 if (a >= 0) {
6263# if BB_MMU /* see above why on NOMMU it is not allowed */
6264 if (APPLET_IS_NOEXEC(a)) {
6265 debug_printf_exec("running applet '%s'\n", argv[0]);
6266 run_applet_no_and_exit(a, argv);
6267 }
6268# endif
6269 /* Re-exec ourselves */
6270 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6271 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6272 execv(bb_busybox_exec_path, argv);
6273 /* If they called chroot or otherwise made the binary no longer
6274 * executable, fall through */
6275 }
6276 }
6277#endif
6278
6279#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6280 skip:
6281#endif
6282 execvp_or_die(argv);
6283}
6284
6285/* Called after [v]fork() in run_pipe
6286 */
6287static void pseudo_exec(nommu_save_t *nommu_save,
6288 struct command *command,
6289 char **argv_expanded) NORETURN;
6290static void pseudo_exec(nommu_save_t *nommu_save,
6291 struct command *command,
6292 char **argv_expanded)
6293{
6294 if (command->argv) {
6295 pseudo_exec_argv(nommu_save, command->argv,
6296 command->assignment_cnt, argv_expanded);
6297 }
6298
6299 if (command->group) {
6300 /* Cases when we are here:
6301 * ( list )
6302 * { list } &
6303 * ... | ( list ) | ...
6304 * ... | { list } | ...
6305 */
6306#if BB_MMU
6307 int rcode;
6308 debug_printf_exec("pseudo_exec: run_list\n");
6309 reset_traps_to_defaults();
6310 rcode = run_list(command->group);
6311 /* OK to leak memory by not calling free_pipe_list,
6312 * since this process is about to exit */
6313 _exit(rcode);
6314#else
6315 re_execute_shell(&nommu_save->argv_from_re_execing,
6316 command->group_as_string,
6317 G.global_argv[0],
6318 G.global_argv + 1,
6319 NULL);
6320#endif
6321 }
6322
6323 /* Case when we are here: ... | >file */
6324 debug_printf_exec("pseudo_exec'ed null command\n");
6325 _exit(EXIT_SUCCESS);
6326}
6327
6328#if ENABLE_HUSH_JOB
6329static const char *get_cmdtext(struct pipe *pi)
6330{
6331 char **argv;
6332 char *p;
6333 int len;
6334
6335 /* This is subtle. ->cmdtext is created only on first backgrounding.
6336 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6337 * On subsequent bg argv is trashed, but we won't use it */
6338 if (pi->cmdtext)
6339 return pi->cmdtext;
6340 argv = pi->cmds[0].argv;
6341 if (!argv || !argv[0]) {
6342 pi->cmdtext = xzalloc(1);
6343 return pi->cmdtext;
6344 }
6345
6346 len = 0;
6347 do {
6348 len += strlen(*argv) + 1;
6349 } while (*++argv);
6350 p = xmalloc(len);
6351 pi->cmdtext = p;
6352 argv = pi->cmds[0].argv;
6353 do {
6354 len = strlen(*argv);
6355 memcpy(p, *argv, len);
6356 p += len;
6357 *p++ = ' ';
6358 } while (*++argv);
6359 p[-1] = '\0';
6360 return pi->cmdtext;
6361}
6362
6363static void insert_bg_job(struct pipe *pi)
6364{
6365 struct pipe *job, **jobp;
6366 int i;
6367
6368 /* Linear search for the ID of the job to use */
6369 pi->jobid = 1;
6370 for (job = G.job_list; job; job = job->next)
6371 if (job->jobid >= pi->jobid)
6372 pi->jobid = job->jobid + 1;
6373
6374 /* Add job to the list of running jobs */
6375 jobp = &G.job_list;
6376 while ((job = *jobp) != NULL)
6377 jobp = &job->next;
6378 job = *jobp = xmalloc(sizeof(*job));
6379
6380 *job = *pi; /* physical copy */
6381 job->next = NULL;
6382 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6383 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6384 for (i = 0; i < pi->num_cmds; i++) {
6385 job->cmds[i].pid = pi->cmds[i].pid;
6386 /* all other fields are not used and stay zero */
6387 }
6388 job->cmdtext = xstrdup(get_cmdtext(pi));
6389
6390 if (G_interactive_fd)
6391 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6392 G.last_jobid = job->jobid;
6393}
6394
6395static void remove_bg_job(struct pipe *pi)
6396{
6397 struct pipe *prev_pipe;
6398
6399 if (pi == G.job_list) {
6400 G.job_list = pi->next;
6401 } else {
6402 prev_pipe = G.job_list;
6403 while (prev_pipe->next != pi)
6404 prev_pipe = prev_pipe->next;
6405 prev_pipe->next = pi->next;
6406 }
6407 if (G.job_list)
6408 G.last_jobid = G.job_list->jobid;
6409 else
6410 G.last_jobid = 0;
6411}
6412
6413/* Remove a backgrounded job */
6414static void delete_finished_bg_job(struct pipe *pi)
6415{
6416 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006417 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006418}
6419#endif /* JOB */
6420
6421/* Check to see if any processes have exited -- if they
6422 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006423static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006424{
6425 int attributes;
6426 int status;
6427#if ENABLE_HUSH_JOB
6428 struct pipe *pi;
6429#endif
6430 pid_t childpid;
6431 int rcode = 0;
6432
6433 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6434
6435 attributes = WUNTRACED;
6436 if (fg_pipe == NULL)
6437 attributes |= WNOHANG;
6438
6439 errno = 0;
6440#if ENABLE_HUSH_FAST
6441 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6442//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6443//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6444 /* There was neither fork nor SIGCHLD since last waitpid */
6445 /* Avoid doing waitpid syscall if possible */
6446 if (!G.we_have_children) {
6447 errno = ECHILD;
6448 return -1;
6449 }
6450 if (fg_pipe == NULL) { /* is WNOHANG set? */
6451 /* We have children, but they did not exit
6452 * or stop yet (we saw no SIGCHLD) */
6453 return 0;
6454 }
6455 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6456 }
6457#endif
6458
6459/* Do we do this right?
6460 * bash-3.00# sleep 20 | false
6461 * <ctrl-Z pressed>
6462 * [3]+ Stopped sleep 20 | false
6463 * bash-3.00# echo $?
6464 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6465 * [hush 1.14.0: yes we do it right]
6466 */
6467 wait_more:
6468 while (1) {
6469 int i;
6470 int dead;
6471
6472#if ENABLE_HUSH_FAST
6473 i = G.count_SIGCHLD;
6474#endif
6475 childpid = waitpid(-1, &status, attributes);
6476 if (childpid <= 0) {
6477 if (childpid && errno != ECHILD)
6478 bb_perror_msg("waitpid");
6479#if ENABLE_HUSH_FAST
6480 else { /* Until next SIGCHLD, waitpid's are useless */
6481 G.we_have_children = (childpid == 0);
6482 G.handled_SIGCHLD = i;
6483//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6484 }
6485#endif
6486 break;
6487 }
6488 dead = WIFEXITED(status) || WIFSIGNALED(status);
6489
6490#if DEBUG_JOBS
6491 if (WIFSTOPPED(status))
6492 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6493 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6494 if (WIFSIGNALED(status))
6495 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6496 childpid, WTERMSIG(status), WEXITSTATUS(status));
6497 if (WIFEXITED(status))
6498 debug_printf_jobs("pid %d exited, exitcode %d\n",
6499 childpid, WEXITSTATUS(status));
6500#endif
6501 /* Were we asked to wait for fg pipe? */
6502 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006503 i = fg_pipe->num_cmds;
6504 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006505 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6506 if (fg_pipe->cmds[i].pid != childpid)
6507 continue;
6508 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006509 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006510 fg_pipe->cmds[i].pid = 0;
6511 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006512 ex = WEXITSTATUS(status);
6513 /* bash prints killer signal's name for *last*
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006514 * process in pipe (prints just newline for SIGINT/SIGPIPE).
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006515 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6516 */
6517 if (WIFSIGNALED(status)) {
6518 int sig = WTERMSIG(status);
6519 if (i == fg_pipe->num_cmds-1)
Denys Vlasenko7c6f2462011-02-14 17:17:10 +01006520 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6521 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6522 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006523 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6524 * Maybe we need to use sig | 128? */
6525 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006526 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006527 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006528 } else {
6529 fg_pipe->cmds[i].is_stopped = 1;
6530 fg_pipe->stopped_cmds++;
6531 }
6532 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6533 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006534 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006535 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006536 i = fg_pipe->num_cmds;
6537 while (--i >= 0) {
6538 rcode = fg_pipe->cmds[i].cmd_exitcode;
6539 /* usually last process gives overall exitstatus,
6540 * but with "set -o pipefail", last *failed* process does */
6541 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6542 break;
6543 }
6544 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006545/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6546 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6547 * and "killall -STOP cat" */
6548 if (G_interactive_fd) {
6549#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006550 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006551 insert_bg_job(fg_pipe);
6552#endif
6553 return rcode;
6554 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006555 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006556 return rcode;
6557 }
6558 /* There are still running processes in the fg pipe */
6559 goto wait_more; /* do waitpid again */
6560 }
6561 /* it wasnt fg_pipe, look for process in bg pipes */
6562 }
6563
6564#if ENABLE_HUSH_JOB
6565 /* We asked to wait for bg or orphaned children */
6566 /* No need to remember exitcode in this case */
6567 for (pi = G.job_list; pi; pi = pi->next) {
6568 for (i = 0; i < pi->num_cmds; i++) {
6569 if (pi->cmds[i].pid == childpid)
6570 goto found_pi_and_prognum;
6571 }
6572 }
6573 /* Happens when shell is used as init process (init=/bin/sh) */
6574 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6575 continue; /* do waitpid again */
6576
6577 found_pi_and_prognum:
6578 if (dead) {
6579 /* child exited */
6580 pi->cmds[i].pid = 0;
6581 pi->alive_cmds--;
6582 if (!pi->alive_cmds) {
6583 if (G_interactive_fd)
6584 printf(JOB_STATUS_FORMAT, pi->jobid,
6585 "Done", pi->cmdtext);
6586 delete_finished_bg_job(pi);
6587 }
6588 } else {
6589 /* child stopped */
6590 pi->cmds[i].is_stopped = 1;
6591 pi->stopped_cmds++;
6592 }
6593#endif
6594 } /* while (waitpid succeeds)... */
6595
6596 return rcode;
6597}
6598
6599#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006600static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006601{
6602 pid_t p;
6603 int rcode = checkjobs(fg_pipe);
6604 if (G_saved_tty_pgrp) {
6605 /* Job finished, move the shell to the foreground */
6606 p = getpgrp(); /* our process group id */
6607 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6608 tcsetpgrp(G_interactive_fd, p);
6609 }
6610 return rcode;
6611}
6612#endif
6613
6614/* Start all the jobs, but don't wait for anything to finish.
6615 * See checkjobs().
6616 *
6617 * Return code is normally -1, when the caller has to wait for children
6618 * to finish to determine the exit status of the pipe. If the pipe
6619 * is a simple builtin command, however, the action is done by the
6620 * time run_pipe returns, and the exit code is provided as the
6621 * return value.
6622 *
6623 * Returns -1 only if started some children. IOW: we have to
6624 * mask out retvals of builtins etc with 0xff!
6625 *
6626 * The only case when we do not need to [v]fork is when the pipe
6627 * is single, non-backgrounded, non-subshell command. Examples:
6628 * cmd ; ... { list } ; ...
6629 * cmd && ... { list } && ...
6630 * cmd || ... { list } || ...
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006631 * If it is, then we can run cmd as a builtin, NOFORK,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006632 * or (if SH_STANDALONE) an applet, and we can run the { list }
6633 * with run_list. If it isn't one of these, we fork and exec cmd.
6634 *
6635 * Cases when we must fork:
6636 * non-single: cmd | cmd
6637 * backgrounded: cmd & { list } &
6638 * subshell: ( list ) [&]
6639 */
6640#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006641#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006642 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6643#endif
6644static int redirect_and_varexp_helper(char ***new_env_p,
6645 struct variable **old_vars_p,
6646 struct command *command,
6647 int squirrel[3],
6648 char **argv_expanded)
6649{
6650 /* setup_redirects acts on file descriptors, not FILEs.
6651 * This is perfect for work that comes after exec().
6652 * Is it really safe for inline use? Experimentally,
6653 * things seem to work. */
6654 int rcode = setup_redirects(command, squirrel);
6655 if (rcode == 0) {
6656 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6657 *new_env_p = new_env;
6658 dump_cmd_in_x_mode(new_env);
6659 dump_cmd_in_x_mode(argv_expanded);
6660 if (old_vars_p)
6661 *old_vars_p = set_vars_and_save_old(new_env);
6662 }
6663 return rcode;
6664}
6665static NOINLINE int run_pipe(struct pipe *pi)
6666{
6667 static const char *const null_ptr = NULL;
6668
6669 int cmd_no;
6670 int next_infd;
6671 struct command *command;
6672 char **argv_expanded;
6673 char **argv;
6674 /* it is not always needed, but we aim to smaller code */
6675 int squirrel[] = { -1, -1, -1 };
6676 int rcode;
6677
6678 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6679 debug_enter();
6680
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006681 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6682 * Result should be 3 lines: q w e, qwe, q w e
6683 */
6684 G.ifs = get_local_var_value("IFS");
6685 if (!G.ifs)
6686 G.ifs = defifs;
6687
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006688 IF_HUSH_JOB(pi->pgrp = -1;)
6689 pi->stopped_cmds = 0;
6690 command = &pi->cmds[0];
6691 argv_expanded = NULL;
6692
6693 if (pi->num_cmds != 1
6694 || pi->followup == PIPE_BG
6695 || command->cmd_type == CMD_SUBSHELL
6696 ) {
6697 goto must_fork;
6698 }
6699
6700 pi->alive_cmds = 1;
6701
6702 debug_printf_exec(": group:%p argv:'%s'\n",
6703 command->group, command->argv ? command->argv[0] : "NONE");
6704
6705 if (command->group) {
6706#if ENABLE_HUSH_FUNCTIONS
6707 if (command->cmd_type == CMD_FUNCDEF) {
6708 /* "executing" func () { list } */
6709 struct function *funcp;
6710
6711 funcp = new_function(command->argv[0]);
6712 /* funcp->name is already set to argv[0] */
6713 funcp->body = command->group;
6714# if !BB_MMU
6715 funcp->body_as_string = command->group_as_string;
6716 command->group_as_string = NULL;
6717# endif
6718 command->group = NULL;
6719 command->argv[0] = NULL;
6720 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6721 funcp->parent_cmd = command;
6722 command->child_func = funcp;
6723
6724 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6725 debug_leave();
6726 return EXIT_SUCCESS;
6727 }
6728#endif
6729 /* { list } */
6730 debug_printf("non-subshell group\n");
6731 rcode = 1; /* exitcode if redir failed */
6732 if (setup_redirects(command, squirrel) == 0) {
6733 debug_printf_exec(": run_list\n");
6734 rcode = run_list(command->group) & 0xff;
6735 }
6736 restore_redirects(squirrel);
6737 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6738 debug_leave();
6739 debug_printf_exec("run_pipe: return %d\n", rcode);
6740 return rcode;
6741 }
6742
6743 argv = command->argv ? command->argv : (char **) &null_ptr;
6744 {
6745 const struct built_in_command *x;
6746#if ENABLE_HUSH_FUNCTIONS
6747 const struct function *funcp;
6748#else
6749 enum { funcp = 0 };
6750#endif
6751 char **new_env = NULL;
6752 struct variable *old_vars = NULL;
6753
6754 if (argv[command->assignment_cnt] == NULL) {
6755 /* Assignments, but no command */
6756 /* Ensure redirects take effect (that is, create files).
6757 * Try "a=t >file" */
6758#if 0 /* A few cases in testsuite fail with this code. FIXME */
6759 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6760 /* Set shell variables */
6761 if (new_env) {
6762 argv = new_env;
6763 while (*argv) {
6764 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6765 /* Do we need to flag set_local_var() errors?
6766 * "assignment to readonly var" and "putenv error"
6767 */
6768 argv++;
6769 }
6770 }
6771 /* Redirect error sets $? to 1. Otherwise,
6772 * if evaluating assignment value set $?, retain it.
6773 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6774 if (rcode == 0)
6775 rcode = G.last_exitcode;
6776 /* Exit, _skipping_ variable restoring code: */
6777 goto clean_up_and_ret0;
6778
6779#else /* Older, bigger, but more correct code */
6780
6781 rcode = setup_redirects(command, squirrel);
6782 restore_redirects(squirrel);
6783 /* Set shell variables */
6784 if (G_x_mode)
6785 bb_putchar_stderr('+');
6786 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006787 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006788 if (G_x_mode)
6789 fprintf(stderr, " %s", p);
6790 debug_printf_exec("set shell var:'%s'->'%s'\n",
6791 *argv, p);
6792 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6793 /* Do we need to flag set_local_var() errors?
6794 * "assignment to readonly var" and "putenv error"
6795 */
6796 argv++;
6797 }
6798 if (G_x_mode)
6799 bb_putchar_stderr('\n');
6800 /* Redirect error sets $? to 1. Otherwise,
6801 * if evaluating assignment value set $?, retain it.
6802 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6803 if (rcode == 0)
6804 rcode = G.last_exitcode;
6805 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6806 debug_leave();
6807 debug_printf_exec("run_pipe: return %d\n", rcode);
6808 return rcode;
6809#endif
6810 }
6811
6812 /* Expand the rest into (possibly) many strings each */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006813#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006814 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006815 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006816 } else
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006817#endif
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006818 {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006819 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6820 }
6821
6822 /* if someone gives us an empty string: `cmd with empty output` */
6823 if (!argv_expanded[0]) {
6824 free(argv_expanded);
6825 debug_leave();
6826 return G.last_exitcode;
6827 }
6828
6829 x = find_builtin(argv_expanded[0]);
6830#if ENABLE_HUSH_FUNCTIONS
6831 funcp = NULL;
6832 if (!x)
6833 funcp = find_function(argv_expanded[0]);
6834#endif
6835 if (x || funcp) {
6836 if (!funcp) {
6837 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6838 debug_printf("exec with redirects only\n");
6839 rcode = setup_redirects(command, NULL);
6840 goto clean_up_and_ret1;
6841 }
6842 }
6843 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6844 if (rcode == 0) {
6845 if (!funcp) {
6846 debug_printf_exec(": builtin '%s' '%s'...\n",
6847 x->b_cmd, argv_expanded[1]);
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01006848 fflush_all();
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006849 rcode = x->b_function(argv_expanded) & 0xff;
6850 fflush_all();
6851 }
6852#if ENABLE_HUSH_FUNCTIONS
6853 else {
6854# if ENABLE_HUSH_LOCAL
6855 struct variable **sv;
6856 sv = G.shadowed_vars_pp;
6857 G.shadowed_vars_pp = &old_vars;
6858# endif
6859 debug_printf_exec(": function '%s' '%s'...\n",
6860 funcp->name, argv_expanded[1]);
6861 rcode = run_function(funcp, argv_expanded) & 0xff;
6862# if ENABLE_HUSH_LOCAL
6863 G.shadowed_vars_pp = sv;
6864# endif
6865 }
6866#endif
6867 }
6868 clean_up_and_ret:
6869 unset_vars(new_env);
6870 add_vars(old_vars);
6871/* clean_up_and_ret0: */
6872 restore_redirects(squirrel);
6873 clean_up_and_ret1:
6874 free(argv_expanded);
6875 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6876 debug_leave();
6877 debug_printf_exec("run_pipe return %d\n", rcode);
6878 return rcode;
6879 }
6880
Denys Vlasenkob72baeb2011-02-02 18:38:57 +01006881 if (ENABLE_FEATURE_SH_NOFORK) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006882 int n = find_applet_by_name(argv_expanded[0]);
6883 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6884 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6885 if (rcode == 0) {
6886 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6887 argv_expanded[0], argv_expanded[1]);
6888 rcode = run_nofork_applet(n, argv_expanded);
6889 }
6890 goto clean_up_and_ret;
6891 }
6892 }
6893 /* It is neither builtin nor applet. We must fork. */
6894 }
6895
6896 must_fork:
6897 /* NB: argv_expanded may already be created, and that
6898 * might include `cmd` runs! Do not rerun it! We *must*
6899 * use argv_expanded if it's non-NULL */
6900
6901 /* Going to fork a child per each pipe member */
6902 pi->alive_cmds = 0;
6903 next_infd = 0;
6904
6905 cmd_no = 0;
6906 while (cmd_no < pi->num_cmds) {
6907 struct fd_pair pipefds;
6908#if !BB_MMU
6909 volatile nommu_save_t nommu_save;
6910 nommu_save.new_env = NULL;
6911 nommu_save.old_vars = NULL;
6912 nommu_save.argv = NULL;
6913 nommu_save.argv_from_re_execing = NULL;
6914#endif
6915 command = &pi->cmds[cmd_no];
6916 cmd_no++;
6917 if (command->argv) {
6918 debug_printf_exec(": pipe member '%s' '%s'...\n",
6919 command->argv[0], command->argv[1]);
6920 } else {
6921 debug_printf_exec(": pipe member with no argv\n");
6922 }
6923
6924 /* pipes are inserted between pairs of commands */
6925 pipefds.rd = 0;
6926 pipefds.wr = 1;
6927 if (cmd_no < pi->num_cmds)
6928 xpiped_pair(pipefds);
6929
6930 command->pid = BB_MMU ? fork() : vfork();
6931 if (!command->pid) { /* child */
6932#if ENABLE_HUSH_JOB
6933 disable_restore_tty_pgrp_on_exit();
6934 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6935
6936 /* Every child adds itself to new process group
6937 * with pgid == pid_of_first_child_in_pipe */
6938 if (G.run_list_level == 1 && G_interactive_fd) {
6939 pid_t pgrp;
6940 pgrp = pi->pgrp;
6941 if (pgrp < 0) /* true for 1st process only */
6942 pgrp = getpid();
6943 if (setpgid(0, pgrp) == 0
6944 && pi->followup != PIPE_BG
6945 && G_saved_tty_pgrp /* we have ctty */
6946 ) {
6947 /* We do it in *every* child, not just first,
6948 * to avoid races */
6949 tcsetpgrp(G_interactive_fd, pgrp);
6950 }
6951 }
6952#endif
6953 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6954 /* 1st cmd in backgrounded pipe
6955 * should have its stdin /dev/null'ed */
6956 close(0);
6957 if (open(bb_dev_null, O_RDONLY))
6958 xopen("/", O_RDONLY);
6959 } else {
6960 xmove_fd(next_infd, 0);
6961 }
6962 xmove_fd(pipefds.wr, 1);
6963 if (pipefds.rd > 1)
6964 close(pipefds.rd);
6965 /* Like bash, explicit redirects override pipes,
6966 * and the pipe fd is available for dup'ing. */
6967 if (setup_redirects(command, NULL))
6968 _exit(1);
6969
6970 /* Restore default handlers just prior to exec */
6971 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6972
6973 /* Stores to nommu_save list of env vars putenv'ed
6974 * (NOMMU, on MMU we don't need that) */
6975 /* cast away volatility... */
6976 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6977 /* pseudo_exec() does not return */
6978 }
6979
6980 /* parent or error */
6981#if ENABLE_HUSH_FAST
6982 G.count_SIGCHLD++;
6983//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6984#endif
6985 enable_restore_tty_pgrp_on_exit();
6986#if !BB_MMU
6987 /* Clean up after vforked child */
6988 free(nommu_save.argv);
6989 free(nommu_save.argv_from_re_execing);
6990 unset_vars(nommu_save.new_env);
6991 add_vars(nommu_save.old_vars);
6992#endif
6993 free(argv_expanded);
6994 argv_expanded = NULL;
6995 if (command->pid < 0) { /* [v]fork failed */
6996 /* Clearly indicate, was it fork or vfork */
6997 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6998 } else {
6999 pi->alive_cmds++;
7000#if ENABLE_HUSH_JOB
7001 /* Second and next children need to know pid of first one */
7002 if (pi->pgrp < 0)
7003 pi->pgrp = command->pid;
7004#endif
7005 }
7006
7007 if (cmd_no > 1)
7008 close(next_infd);
7009 if (cmd_no < pi->num_cmds)
7010 close(pipefds.wr);
7011 /* Pass read (output) pipe end to next iteration */
7012 next_infd = pipefds.rd;
7013 }
7014
7015 if (!pi->alive_cmds) {
7016 debug_leave();
7017 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7018 return 1;
7019 }
7020
7021 debug_leave();
7022 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7023 return -1;
7024}
7025
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007026/* NB: called by pseudo_exec, and therefore must not modify any
7027 * global data until exec/_exit (we can be a child after vfork!) */
7028static int run_list(struct pipe *pi)
7029{
7030#if ENABLE_HUSH_CASE
7031 char *case_word = NULL;
7032#endif
7033#if ENABLE_HUSH_LOOPS
7034 struct pipe *loop_top = NULL;
7035 char **for_lcur = NULL;
7036 char **for_list = NULL;
7037#endif
7038 smallint last_followup;
7039 smalluint rcode;
7040#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7041 smalluint cond_code = 0;
7042#else
7043 enum { cond_code = 0 };
7044#endif
7045#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007046 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007047 smallint last_rword; /* ditto */
7048#endif
7049
7050 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7051 debug_enter();
7052
7053#if ENABLE_HUSH_LOOPS
7054 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007055 {
7056 struct pipe *cpipe;
7057 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7058 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7059 continue;
7060 /* current word is FOR or IN (BOLD in comments below) */
7061 if (cpipe->next == NULL) {
7062 syntax_error("malformed for");
7063 debug_leave();
7064 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7065 return 1;
7066 }
7067 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7068 if (cpipe->next->res_word == RES_DO)
7069 continue;
7070 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7071 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7072 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7073 ) {
7074 syntax_error("malformed for");
7075 debug_leave();
7076 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7077 return 1;
7078 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007079 }
7080 }
7081#endif
7082
7083 /* Past this point, all code paths should jump to ret: label
7084 * in order to return, no direct "return" statements please.
7085 * This helps to ensure that no memory is leaked. */
7086
7087#if ENABLE_HUSH_JOB
7088 G.run_list_level++;
7089#endif
7090
7091#if HAS_KEYWORDS
7092 rword = RES_NONE;
7093 last_rword = RES_XXXX;
7094#endif
7095 last_followup = PIPE_SEQ;
7096 rcode = G.last_exitcode;
7097
7098 /* Go through list of pipes, (maybe) executing them. */
7099 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7100 if (G.flag_SIGINT)
7101 break;
7102
7103 IF_HAS_KEYWORDS(rword = pi->res_word;)
7104 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7105 rword, cond_code, last_rword);
7106#if ENABLE_HUSH_LOOPS
7107 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7108 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7109 ) {
7110 /* start of a loop: remember where loop starts */
7111 loop_top = pi;
7112 G.depth_of_loop++;
7113 }
7114#endif
7115 /* Still in the same "if...", "then..." or "do..." branch? */
7116 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7117 if ((rcode == 0 && last_followup == PIPE_OR)
7118 || (rcode != 0 && last_followup == PIPE_AND)
7119 ) {
7120 /* It is "<true> || CMD" or "<false> && CMD"
7121 * and we should not execute CMD */
7122 debug_printf_exec("skipped cmd because of || or &&\n");
7123 last_followup = pi->followup;
7124 continue;
7125 }
7126 }
7127 last_followup = pi->followup;
7128 IF_HAS_KEYWORDS(last_rword = rword;)
7129#if ENABLE_HUSH_IF
7130 if (cond_code) {
7131 if (rword == RES_THEN) {
7132 /* if false; then ... fi has exitcode 0! */
7133 G.last_exitcode = rcode = EXIT_SUCCESS;
7134 /* "if <false> THEN cmd": skip cmd */
7135 continue;
7136 }
7137 } else {
7138 if (rword == RES_ELSE || rword == RES_ELIF) {
7139 /* "if <true> then ... ELSE/ELIF cmd":
7140 * skip cmd and all following ones */
7141 break;
7142 }
7143 }
7144#endif
7145#if ENABLE_HUSH_LOOPS
7146 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7147 if (!for_lcur) {
7148 /* first loop through for */
7149
7150 static const char encoded_dollar_at[] ALIGN1 = {
7151 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7152 }; /* encoded representation of "$@" */
7153 static const char *const encoded_dollar_at_argv[] = {
7154 encoded_dollar_at, NULL
7155 }; /* argv list with one element: "$@" */
7156 char **vals;
7157
7158 vals = (char**)encoded_dollar_at_argv;
7159 if (pi->next->res_word == RES_IN) {
7160 /* if no variable values after "in" we skip "for" */
7161 if (!pi->next->cmds[0].argv) {
7162 G.last_exitcode = rcode = EXIT_SUCCESS;
7163 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7164 break;
7165 }
7166 vals = pi->next->cmds[0].argv;
7167 } /* else: "for var; do..." -> assume "$@" list */
7168 /* create list of variable values */
7169 debug_print_strings("for_list made from", vals);
7170 for_list = expand_strvec_to_strvec(vals);
7171 for_lcur = for_list;
7172 debug_print_strings("for_list", for_list);
7173 }
7174 if (!*for_lcur) {
7175 /* "for" loop is over, clean up */
7176 free(for_list);
7177 for_list = NULL;
7178 for_lcur = NULL;
7179 break;
7180 }
7181 /* Insert next value from for_lcur */
7182 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7183 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7184 continue;
7185 }
7186 if (rword == RES_IN) {
7187 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7188 }
7189 if (rword == RES_DONE) {
7190 continue; /* "done" has no cmds too */
7191 }
7192#endif
7193#if ENABLE_HUSH_CASE
7194 if (rword == RES_CASE) {
7195 case_word = expand_strvec_to_string(pi->cmds->argv);
7196 continue;
7197 }
7198 if (rword == RES_MATCH) {
7199 char **argv;
7200
7201 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7202 break;
7203 /* all prev words didn't match, does this one match? */
7204 argv = pi->cmds->argv;
7205 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007206 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007207 /* TODO: which FNM_xxx flags to use? */
7208 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7209 free(pattern);
7210 if (cond_code == 0) { /* match! we will execute this branch */
7211 free(case_word); /* make future "word)" stop */
7212 case_word = NULL;
7213 break;
7214 }
7215 argv++;
7216 }
7217 continue;
7218 }
7219 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7220 if (cond_code != 0)
7221 continue; /* not matched yet, skip this pipe */
7222 }
7223#endif
7224 /* Just pressing <enter> in shell should check for jobs.
7225 * OTOH, in non-interactive shell this is useless
7226 * and only leads to extra job checks */
7227 if (pi->num_cmds == 0) {
7228 if (G_interactive_fd)
7229 goto check_jobs_and_continue;
7230 continue;
7231 }
7232
7233 /* After analyzing all keywords and conditions, we decided
7234 * to execute this pipe. NB: have to do checkjobs(NULL)
7235 * after run_pipe to collect any background children,
7236 * even if list execution is to be stopped. */
7237 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7238 {
7239 int r;
7240#if ENABLE_HUSH_LOOPS
7241 G.flag_break_continue = 0;
7242#endif
7243 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7244 if (r != -1) {
7245 /* We ran a builtin, function, or group.
7246 * rcode is already known
7247 * and we don't need to wait for anything. */
7248 G.last_exitcode = rcode;
7249 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7250 check_and_run_traps(0);
7251#if ENABLE_HUSH_LOOPS
7252 /* Was it "break" or "continue"? */
7253 if (G.flag_break_continue) {
7254 smallint fbc = G.flag_break_continue;
7255 /* We might fall into outer *loop*,
7256 * don't want to break it too */
7257 if (loop_top) {
7258 G.depth_break_continue--;
7259 if (G.depth_break_continue == 0)
7260 G.flag_break_continue = 0;
7261 /* else: e.g. "continue 2" should *break* once, *then* continue */
7262 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7263 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7264 goto check_jobs_and_break;
7265 /* "continue": simulate end of loop */
7266 rword = RES_DONE;
7267 continue;
7268 }
7269#endif
7270#if ENABLE_HUSH_FUNCTIONS
7271 if (G.flag_return_in_progress == 1) {
7272 /* same as "goto check_jobs_and_break" */
7273 checkjobs(NULL);
7274 break;
7275 }
7276#endif
7277 } else if (pi->followup == PIPE_BG) {
7278 /* What does bash do with attempts to background builtins? */
7279 /* even bash 3.2 doesn't do that well with nested bg:
7280 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7281 * I'm NOT treating inner &'s as jobs */
7282 check_and_run_traps(0);
7283#if ENABLE_HUSH_JOB
7284 if (G.run_list_level == 1)
7285 insert_bg_job(pi);
7286#endif
7287 /* Last command's pid goes to $! */
7288 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7289 G.last_exitcode = rcode = EXIT_SUCCESS;
7290 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7291 } else {
7292#if ENABLE_HUSH_JOB
7293 if (G.run_list_level == 1 && G_interactive_fd) {
7294 /* Waits for completion, then fg's main shell */
7295 rcode = checkjobs_and_fg_shell(pi);
7296 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7297 check_and_run_traps(0);
7298 } else
7299#endif
7300 { /* This one just waits for completion */
7301 rcode = checkjobs(pi);
7302 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7303 check_and_run_traps(0);
7304 }
7305 G.last_exitcode = rcode;
7306 }
7307 }
7308
7309 /* Analyze how result affects subsequent commands */
7310#if ENABLE_HUSH_IF
7311 if (rword == RES_IF || rword == RES_ELIF)
7312 cond_code = rcode;
7313#endif
7314#if ENABLE_HUSH_LOOPS
7315 /* Beware of "while false; true; do ..."! */
7316 if (pi->next && pi->next->res_word == RES_DO) {
7317 if (rword == RES_WHILE) {
7318 if (rcode) {
7319 /* "while false; do...done" - exitcode 0 */
7320 G.last_exitcode = rcode = EXIT_SUCCESS;
7321 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7322 goto check_jobs_and_break;
7323 }
7324 }
7325 if (rword == RES_UNTIL) {
7326 if (!rcode) {
7327 debug_printf_exec(": until expr is true: breaking\n");
7328 check_jobs_and_break:
7329 checkjobs(NULL);
7330 break;
7331 }
7332 }
7333 }
7334#endif
7335
7336 check_jobs_and_continue:
7337 checkjobs(NULL);
7338 } /* for (pi) */
7339
7340#if ENABLE_HUSH_JOB
7341 G.run_list_level--;
7342#endif
7343#if ENABLE_HUSH_LOOPS
7344 if (loop_top)
7345 G.depth_of_loop--;
7346 free(for_list);
7347#endif
7348#if ENABLE_HUSH_CASE
7349 free(case_word);
7350#endif
7351 debug_leave();
7352 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7353 return rcode;
7354}
7355
7356/* Select which version we will use */
7357static int run_and_free_list(struct pipe *pi)
7358{
7359 int rcode = 0;
7360 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007361 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007362 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7363 rcode = run_list(pi);
7364 }
7365 /* free_pipe_list has the side effect of clearing memory.
7366 * In the long run that function can be merged with run_list,
7367 * but doing that now would hobble the debugging effort. */
7368 free_pipe_list(pi);
7369 debug_printf_exec("run_and_free_list return %d\n", rcode);
7370 return rcode;
7371}
7372
7373
Denis Vlasenkof9375282009-04-05 19:13:39 +00007374/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007375static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007376{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007377 unsigned sig;
7378 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007379 sigset_t old_blocked_set;
7380
7381 if (!G.inherited_set_is_saved) {
7382 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7383 G.inherited_set = G.blocked_set;
7384 }
7385 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007386
Denis Vlasenkof9375282009-04-05 19:13:39 +00007387 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007388 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007389 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007390 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007391 mask |= SPECIAL_JOB_SIGS;
7392 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007393 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007394
Denis Vlasenkof9375282009-04-05 19:13:39 +00007395 sig = 0;
7396 while (mask) {
7397 if (mask & 1)
7398 sigaddset(&G.blocked_set, sig);
7399 mask >>= 1;
7400 sig++;
7401 }
7402 sigdelset(&G.blocked_set, SIGCHLD);
7403
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007404 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7405 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7406
Denis Vlasenkof9375282009-04-05 19:13:39 +00007407 /* POSIX allows shell to re-enable SIGCHLD
7408 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007409#if ENABLE_HUSH_FAST
7410 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007411 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007412 signal(SIGCHLD, SIGCHLD_handler);
7413#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007414 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007415 signal(SIGCHLD, SIG_DFL);
7416#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007417
7418 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007419}
7420
7421#if ENABLE_HUSH_JOB
7422/* helper */
7423static void maybe_set_to_sigexit(int sig)
7424{
7425 void (*handler)(int);
7426 /* non_DFL_mask'ed signals are, well, masked,
7427 * no need to set handler for them.
7428 */
7429 if (!((G.non_DFL_mask >> sig) & 1)) {
7430 handler = signal(sig, sigexit);
7431 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7432 signal(sig, handler);
7433 }
7434}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007435/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007436static void set_fatal_handlers(void)
7437{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007438 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007439 if (HUSH_DEBUG) {
7440 maybe_set_to_sigexit(SIGILL );
7441 maybe_set_to_sigexit(SIGFPE );
7442 maybe_set_to_sigexit(SIGBUS );
7443 maybe_set_to_sigexit(SIGSEGV);
7444 maybe_set_to_sigexit(SIGTRAP);
7445 } /* else: hush is perfect. what SEGV? */
7446 maybe_set_to_sigexit(SIGABRT);
7447 /* bash 3.2 seems to handle these just like 'fatal' ones */
7448 maybe_set_to_sigexit(SIGPIPE);
7449 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007450 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007451 * if we aren't interactive... but in this case
7452 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007453 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007454 /*maybe_set_to_sigexit(SIGTERM);*/
7455 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007456}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007457#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007458
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007459static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007460{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007461 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007462 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007463 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007464 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007465 break;
7466 case 'x':
7467 IF_HUSH_MODE_X(G_x_mode = state;)
7468 break;
7469 case 'o':
7470 if (!o_opt) {
7471 /* "set -+o" without parameter.
7472 * in bash, set -o produces this output:
7473 * pipefail off
7474 * and set +o:
7475 * set +o pipefail
7476 * We always use the second form.
7477 */
7478 const char *p = o_opt_strings;
7479 idx = 0;
7480 while (*p) {
7481 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7482 idx++;
7483 p += strlen(p) + 1;
7484 }
7485 break;
7486 }
7487 idx = index_in_strings(o_opt_strings, o_opt);
7488 if (idx >= 0) {
7489 G.o_opt[idx] = state;
7490 break;
7491 }
7492 default:
7493 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007494 }
7495 return EXIT_SUCCESS;
7496}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007497
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007498int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007499int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007500{
7501 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007502 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007503 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007504 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007505 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007506
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007507 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007508 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007509 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007510#if !BB_MMU
7511 G.argv0_for_re_execing = argv[0];
7512#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007513 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007514 shell_ver = xzalloc(sizeof(*shell_ver));
7515 shell_ver->flg_export = 1;
7516 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007517 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007518 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007519 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007520 /* Create shell local variables from the values
7521 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007522 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007523 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007524 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007525 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007526 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007527 if (e) while (*e) {
7528 char *value = strchr(*e, '=');
7529 if (value) { /* paranoia */
7530 cur_var->next = xzalloc(sizeof(*cur_var));
7531 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007532 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007533 cur_var->max_len = strlen(*e);
7534 cur_var->flg_export = 1;
7535 }
7536 e++;
7537 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007538 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007539 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7540 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007541
7542 /* Export PWD */
7543 set_pwd_var(/*exp:*/ 1);
7544 /* bash also exports SHLVL and _,
7545 * and sets (but doesn't export) the following variables:
7546 * BASH=/bin/bash
7547 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7548 * BASH_VERSION='3.2.0(1)-release'
7549 * HOSTTYPE=i386
7550 * MACHTYPE=i386-pc-linux-gnu
7551 * OSTYPE=linux-gnu
7552 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007553 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007554 * EUID=<NNNNN>
7555 * UID=<NNNNN>
7556 * GROUPS=()
7557 * LINES=<NNN>
7558 * COLUMNS=<NNN>
7559 * BASH_ARGC=()
7560 * BASH_ARGV=()
7561 * BASH_LINENO=()
7562 * BASH_SOURCE=()
7563 * DIRSTACK=()
7564 * PIPESTATUS=([0]="0")
7565 * HISTFILE=/<xxx>/.bash_history
7566 * HISTFILESIZE=500
7567 * HISTSIZE=500
7568 * MAILCHECK=60
7569 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7570 * SHELL=/bin/bash
7571 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7572 * TERM=dumb
7573 * OPTERR=1
7574 * OPTIND=1
7575 * IFS=$' \t\n'
7576 * PS1='\s-\v\$ '
7577 * PS2='> '
7578 * PS4='+ '
7579 */
7580
Denis Vlasenko38f63192007-01-22 09:03:07 +00007581#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007582 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007583# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7584 {
7585 const char *hp = get_local_var_value("HISTFILE");
7586 if (!hp) {
7587 hp = get_local_var_value("HOME");
7588 if (hp) {
7589 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7590 //set_local_var(xasprintf("HISTFILE=%s", ...));
7591 }
7592 }
7593 }
7594# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007595#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007596
Denis Vlasenko87a86552008-07-29 19:43:10 +00007597 G.global_argc = argc;
7598 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007599 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007600 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007601
Denis Vlasenkoed782372009-04-10 00:45:02 +00007602 if (setjmp(die_jmp)) {
7603 /* xfunc has failed! die die die */
7604 /* no EXIT traps, this is an escape hatch! */
7605 G.exiting = 1;
7606 hush_exit(xfunc_error_retval);
7607 }
7608
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007609 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007610 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007611 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007612 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007613 * in order to intercept (more) signals.
7614 */
7615
7616 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007617 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007618 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007619 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007620 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007621#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007622 "<:$:R:V:"
7623# if ENABLE_HUSH_FUNCTIONS
7624 "F:"
7625# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007626#endif
7627 );
7628 if (opt <= 0)
7629 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007630 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007631 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007632 /* Possibilities:
7633 * sh ... -c 'script'
7634 * sh ... -c 'script' ARG0 [ARG1...]
7635 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007636 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007637 * "" needs to be replaced with NULL
7638 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007639 * Note: the form without ARG0 never happens:
7640 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007641 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007642 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007643 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007644 G.root_ppid = getppid();
7645 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007646 G.global_argv = argv + optind;
7647 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007648 if (builtin_argc) {
7649 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7650 const struct built_in_command *x;
7651
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007652 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007653 x = find_builtin(optarg);
7654 if (x) { /* paranoia */
7655 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7656 G.global_argv += builtin_argc;
7657 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko8ee2ada2011-02-07 02:03:51 +01007658 fflush_all();
Denys Vlasenko17323a62010-01-28 01:57:05 +01007659 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007660 }
7661 goto final_return;
7662 }
7663 if (!G.global_argv[0]) {
7664 /* -c 'script' (no params): prevent empty $0 */
7665 G.global_argv--; /* points to argv[i] of 'script' */
7666 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007667 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007668 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007669 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007670 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007671 goto final_return;
7672 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007673 /* Well, we cannot just declare interactiveness,
7674 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007675 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007676 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007677 case 's':
7678 /* "-s" means "read from stdin", but this is how we always
7679 * operate, so simply do nothing here. */
7680 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007681#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007682 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007683 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007684 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007685 case '$': {
7686 unsigned long long empty_trap_mask;
7687
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007688 G.root_pid = bb_strtou(optarg, &optarg, 16);
7689 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007690 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7691 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007692 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7693 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007694 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007695 optarg++;
7696 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007697 optarg++;
7698 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7699 if (empty_trap_mask != 0) {
7700 int sig;
7701 init_sigmasks();
7702 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7703 for (sig = 1; sig < NSIG; sig++) {
7704 if (empty_trap_mask & (1LL << sig)) {
7705 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7706 sigaddset(&G.blocked_set, sig);
7707 }
7708 }
7709 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7710 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007711# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007712 optarg++;
7713 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007714# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007715 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007716 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007717 case 'R':
7718 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007719 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007720 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007721# if ENABLE_HUSH_FUNCTIONS
7722 case 'F': {
7723 struct function *funcp = new_function(optarg);
7724 /* funcp->name is already set to optarg */
7725 /* funcp->body is set to NULL. It's a special case. */
7726 funcp->body_as_string = argv[optind];
7727 optind++;
7728 break;
7729 }
7730# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007731#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007732 case 'n':
7733 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007734 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007735 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007736 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007737#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007738 fprintf(stderr, "Usage: sh [FILE]...\n"
7739 " or: sh -c command [args]...\n\n");
7740 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007741#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007742 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007743#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007744 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007745 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007746
Denys Vlasenkodea47882009-10-09 15:40:49 +02007747 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007748 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007749 G.root_ppid = getppid();
7750 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007751
7752 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007753 if (argv[0] && argv[0][0] == '-') {
7754 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007755 debug_printf("sourcing /etc/profile\n");
7756 input = fopen_for_read("/etc/profile");
7757 if (input != NULL) {
7758 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007759 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007760 parse_and_run_file(input);
7761 fclose(input);
7762 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007763 /* bash: after sourcing /etc/profile,
7764 * tries to source (in the given order):
7765 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007766 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007767 * bash also sources ~/.bash_logout on exit.
7768 * If called as sh, skips .bash_XXX files.
7769 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007770 }
7771
Denis Vlasenkof9375282009-04-05 19:13:39 +00007772 if (argv[optind]) {
7773 FILE *input;
7774 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007775 * "bash <script>" (which is never interactive (unless -i?))
7776 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007777 * If called as sh, does the same but with $ENV.
7778 */
7779 debug_printf("running script '%s'\n", argv[optind]);
7780 G.global_argv = argv + optind;
7781 G.global_argc = argc - optind;
7782 input = xfopen_for_read(argv[optind]);
7783 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007784 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007785 parse_and_run_file(input);
7786#if ENABLE_FEATURE_CLEAN_UP
7787 fclose(input);
7788#endif
7789 goto final_return;
7790 }
7791
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007792 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007793 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007794 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007795
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007796 /* A shell is interactive if the '-i' flag was given,
7797 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007798 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007799 * no arguments remaining or the -s flag given
7800 * standard input is a terminal
7801 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007802 * Refer to Posix.2, the description of the 'sh' utility.
7803 */
7804#if ENABLE_HUSH_JOB
7805 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007806 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7807 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7808 if (G_saved_tty_pgrp < 0)
7809 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007810
7811 /* try to dup stdin to high fd#, >= 255 */
7812 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7813 if (G_interactive_fd < 0) {
7814 /* try to dup to any fd */
7815 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007816 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007817 /* give up */
7818 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007819 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007820 }
7821 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007822// TODO: track & disallow any attempts of user
7823// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007824 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007825 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007826 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007827 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007828
Mike Frysinger38478a62009-05-20 04:48:06 -04007829 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007830 /* If we were run as 'hush &', sleep until we are
7831 * in the foreground (tty pgrp == our pgrp).
7832 * If we get started under a job aware app (like bash),
7833 * make sure we are now in charge so we don't fight over
7834 * who gets the foreground */
7835 while (1) {
7836 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007837 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7838 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007839 break;
7840 /* send TTIN to ourself (should stop us) */
7841 kill(- shell_pgrp, SIGTTIN);
7842 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007843 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007844
Denis Vlasenkof9375282009-04-05 19:13:39 +00007845 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007846 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007847
Mike Frysinger38478a62009-05-20 04:48:06 -04007848 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007849 /* Set other signals to restore saved_tty_pgrp */
7850 set_fatal_handlers();
7851 /* Put ourselves in our own process group
7852 * (bash, too, does this only if ctty is available) */
7853 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7854 /* Grab control of the terminal */
7855 tcsetpgrp(G_interactive_fd, getpid());
7856 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007857 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007858 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007859 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007860 } else {
7861 init_sigmasks();
7862 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007863#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007864 /* No job control compiled in, only prompt/line editing */
7865 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007866 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7867 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007868 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007869 G_interactive_fd = dup(STDIN_FILENO);
7870 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007871 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007872 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007873 }
7874 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007875 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007876 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007877 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007878 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007879#else
7880 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007881 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007882#endif
7883 /* bash:
7884 * if interactive but not a login shell, sources ~/.bashrc
7885 * (--norc turns this off, --rcfile <file> overrides)
7886 */
7887
7888 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007889 /* note: ash and hush share this string */
7890 printf("\n\n%s %s\n"
7891 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7892 "\n",
7893 bb_banner,
7894 "hush - the humble shell"
7895 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007896 }
7897
Denis Vlasenkof9375282009-04-05 19:13:39 +00007898 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007899
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007900 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007901 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007902}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007903
7904
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007905#if ENABLE_MSH
7906int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7907int msh_main(int argc, char **argv)
7908{
7909 //bb_error_msg("msh is deprecated, please use hush instead");
7910 return hush_main(argc, argv);
7911}
7912#endif
7913
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007914
7915/*
7916 * Built-ins
7917 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007918static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007919{
7920 return 0;
7921}
7922
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007923static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007924{
7925 int argc = 0;
7926 while (*argv) {
7927 argc++;
7928 argv++;
7929 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007930 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007931}
7932
7933static int FAST_FUNC builtin_test(char **argv)
7934{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007935 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007936}
7937
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007938static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007939{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007940 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007941}
7942
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007943#if ENABLE_PRINTF
7944static int FAST_FUNC builtin_printf(char **argv)
7945{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007946 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007947}
7948#endif
7949
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007950static char **skip_dash_dash(char **argv)
7951{
7952 argv++;
7953 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7954 argv++;
7955 return argv;
7956}
7957
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007958static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007959{
7960 int rcode = EXIT_SUCCESS;
7961
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007962 argv = skip_dash_dash(argv);
7963 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007964 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007965 /* bash:
7966 * eval "echo Hi; done" ("done" is syntax error):
7967 * "echo Hi" will not execute too.
7968 */
7969 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007970 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007971 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007972 }
7973 return rcode;
7974}
7975
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007976static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007977{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007978 const char *newdir;
7979
7980 argv = skip_dash_dash(argv);
7981 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007982 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007983 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007984 * bash says "bash: cd: HOME not set" and does nothing
7985 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007986 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007987 const char *home = get_local_var_value("HOME");
7988 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007989 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007990 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007991 /* Mimic bash message exactly */
7992 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007993 return EXIT_FAILURE;
7994 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007995 /* Read current dir (get_cwd(1) is inside) and set PWD.
7996 * Note: do not enforce exporting. If PWD was unset or unexported,
7997 * set it again, but do not export. bash does the same.
7998 */
7999 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008000 return EXIT_SUCCESS;
8001}
8002
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008003static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008004{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008005 argv = skip_dash_dash(argv);
8006 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008007 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008008
Denys Vlasenkof37eb392009-10-18 11:46:35 +02008009 /* Careful: we can end up here after [v]fork. Do not restore
8010 * tty pgrp then, only top-level shell process does that */
8011 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8012 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8013
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02008014 /* TODO: if exec fails, bash does NOT exit! We do.
8015 * We'll need to undo sigprocmask (it's inside execvp_or_die)
8016 * and tcsetpgrp, and this is inherently racy.
8017 */
8018 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008019}
8020
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008021static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008022{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00008023 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008024
8025 /* interactive bash:
8026 * # trap "echo EEE" EXIT
8027 * # exit
8028 * exit
8029 * There are stopped jobs.
8030 * (if there are _stopped_ jobs, running ones don't count)
8031 * # exit
8032 * exit
8033 # EEE (then bash exits)
8034 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008035 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008036 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008037
8038 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008039 argv = skip_dash_dash(argv);
8040 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008041 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008042 /* mimic bash: exit 123abc == exit 255 + error msg */
8043 xfunc_error_retval = 255;
8044 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008045 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008046}
8047
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008048static void print_escaped(const char *s)
8049{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008050 if (*s == '\'')
8051 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008052 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008053 const char *p = strchrnul(s, '\'');
8054 /* print 'xxxx', possibly just '' */
8055 printf("'%.*s'", (int)(p - s), s);
8056 if (*p == '\0')
8057 break;
8058 s = p;
8059 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008060 /* s points to '; print "'''...'''" */
8061 putchar('"');
8062 do putchar('\''); while (*++s == '\'');
8063 putchar('"');
8064 } while (*s);
8065}
8066
Denys Vlasenko295fef82009-06-03 12:47:26 +02008067#if !ENABLE_HUSH_LOCAL
8068#define helper_export_local(argv, exp, lvl) \
8069 helper_export_local(argv, exp)
8070#endif
8071static void helper_export_local(char **argv, int exp, int lvl)
8072{
8073 do {
8074 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008075 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008076
8077 /* So far we do not check that name is valid (TODO?) */
8078
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008079 if (*name_end == '\0') {
8080 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008081
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008082 vpp = get_ptr_to_local_var(name, name_end - name);
8083 var = vpp ? *vpp : NULL;
8084
Denys Vlasenko295fef82009-06-03 12:47:26 +02008085 if (exp == -1) { /* unexporting? */
8086 /* export -n NAME (without =VALUE) */
8087 if (var) {
8088 var->flg_export = 0;
8089 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8090 unsetenv(name);
8091 } /* else: export -n NOT_EXISTING_VAR: no-op */
8092 continue;
8093 }
8094 if (exp == 1) { /* exporting? */
8095 /* export NAME (without =VALUE) */
8096 if (var) {
8097 var->flg_export = 1;
8098 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8099 putenv(var->varstr);
8100 continue;
8101 }
8102 }
8103 /* Exporting non-existing variable.
8104 * bash does not put it in environment,
8105 * but remembers that it is exported,
8106 * and does put it in env when it is set later.
8107 * We just set it to "" and export. */
8108 /* Or, it's "local NAME" (without =VALUE).
8109 * bash sets the value to "". */
8110 name = xasprintf("%s=", name);
8111 } else {
8112 /* (Un)exporting/making local NAME=VALUE */
8113 name = xstrdup(name);
8114 }
8115 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8116 } while (*++argv);
8117}
8118
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008119static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008120{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008121 unsigned opt_unexport;
8122
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008123#if ENABLE_HUSH_EXPORT_N
8124 /* "!": do not abort on errors */
8125 opt_unexport = getopt32(argv, "!n");
8126 if (opt_unexport == (uint32_t)-1)
8127 return EXIT_FAILURE;
8128 argv += optind;
8129#else
8130 opt_unexport = 0;
8131 argv++;
8132#endif
8133
8134 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008135 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008136 if (e) {
8137 while (*e) {
8138#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008139 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008140#else
8141 /* ash emits: export VAR='VAL'
8142 * bash: declare -x VAR="VAL"
8143 * we follow ash example */
8144 const char *s = *e++;
8145 const char *p = strchr(s, '=');
8146
8147 if (!p) /* wtf? take next variable */
8148 continue;
8149 /* export var= */
8150 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008151 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008152 putchar('\n');
8153#endif
8154 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008155 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008156 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008157 return EXIT_SUCCESS;
8158 }
8159
Denys Vlasenko295fef82009-06-03 12:47:26 +02008160 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008161
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008162 return EXIT_SUCCESS;
8163}
8164
Denys Vlasenko295fef82009-06-03 12:47:26 +02008165#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008166static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008167{
8168 if (G.func_nest_level == 0) {
8169 bb_error_msg("%s: not in a function", argv[0]);
8170 return EXIT_FAILURE; /* bash compat */
8171 }
8172 helper_export_local(argv, 0, G.func_nest_level);
8173 return EXIT_SUCCESS;
8174}
8175#endif
8176
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008177static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008178{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008179 int sig;
8180 char *new_cmd;
8181
8182 if (!G.traps)
8183 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8184
8185 argv++;
8186 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008187 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008188 /* No args: print all trapped */
8189 for (i = 0; i < NSIG; ++i) {
8190 if (G.traps[i]) {
8191 printf("trap -- ");
8192 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008193 /* note: bash adds "SIG", but only if invoked
8194 * as "bash". If called as "sh", or if set -o posix,
8195 * then it prints short signal names.
8196 * We are printing short names: */
8197 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008198 }
8199 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008200 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008201 return EXIT_SUCCESS;
8202 }
8203
8204 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008205 /* If first arg is a number: reset all specified signals */
8206 sig = bb_strtou(*argv, NULL, 10);
8207 if (errno == 0) {
8208 int ret;
8209 process_sig_list:
8210 ret = EXIT_SUCCESS;
8211 while (*argv) {
8212 sig = get_signum(*argv++);
8213 if (sig < 0 || sig >= NSIG) {
8214 ret = EXIT_FAILURE;
8215 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008216 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008217 continue;
8218 }
8219
8220 free(G.traps[sig]);
8221 G.traps[sig] = xstrdup(new_cmd);
8222
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008223 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008224 get_signame(sig), sig, G.traps[sig]);
8225
8226 /* There is no signal for 0 (EXIT) */
8227 if (sig == 0)
8228 continue;
8229
8230 if (new_cmd) {
8231 sigaddset(&G.blocked_set, sig);
8232 } else {
8233 /* There was a trap handler, we are removing it
8234 * (if sig has non-DFL handling,
8235 * we don't need to do anything) */
8236 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8237 continue;
8238 sigdelset(&G.blocked_set, sig);
8239 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008240 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008241 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008242 return ret;
8243 }
8244
8245 if (!argv[1]) { /* no second arg */
8246 bb_error_msg("trap: invalid arguments");
8247 return EXIT_FAILURE;
8248 }
8249
8250 /* First arg is "-": reset all specified to default */
8251 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8252 /* Everything else: set arg as signal handler
8253 * (includes "" case, which ignores signal) */
8254 if (argv[0][0] == '-') {
8255 if (argv[0][1] == '\0') { /* "-" */
8256 /* new_cmd remains NULL: "reset these sigs" */
8257 goto reset_traps;
8258 }
8259 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8260 argv++;
8261 }
8262 /* else: "-something", no special meaning */
8263 }
8264 new_cmd = *argv;
8265 reset_traps:
8266 argv++;
8267 goto process_sig_list;
8268}
8269
Mike Frysinger93cadc22009-05-27 17:06:25 -04008270/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008271static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008272{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008273 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008274
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008275 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008276 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008277 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008278
8279 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008280 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008281 type = "an alias";*/
8282#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008283 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008284 type = "a function";
8285#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008286 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008287 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008288 else if ((path = find_in_path(*argv)) != NULL)
8289 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008290 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008291 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008292 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008293 continue;
8294 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008295
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008296 printf("%s is %s\n", *argv, type);
8297 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008298 }
8299
8300 return ret;
8301}
8302
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008303#if ENABLE_HUSH_JOB
8304/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008305static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008306{
8307 int i, jobnum;
8308 struct pipe *pi;
8309
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008310 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008311 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008312
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008313 /* If they gave us no args, assume they want the last backgrounded task */
8314 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008315 for (pi = G.job_list; pi; pi = pi->next) {
8316 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008317 goto found;
8318 }
8319 }
8320 bb_error_msg("%s: no current job", argv[0]);
8321 return EXIT_FAILURE;
8322 }
8323 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8324 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8325 return EXIT_FAILURE;
8326 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008327 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008328 if (pi->jobid == jobnum) {
8329 goto found;
8330 }
8331 }
8332 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8333 return EXIT_FAILURE;
8334 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008335 /* TODO: bash prints a string representation
8336 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008337 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008338 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008339 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008340 }
8341
8342 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008343 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8344 for (i = 0; i < pi->num_cmds; i++) {
8345 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8346 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008347 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008348 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008349
8350 i = kill(- pi->pgrp, SIGCONT);
8351 if (i < 0) {
8352 if (errno == ESRCH) {
8353 delete_finished_bg_job(pi);
8354 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008355 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008356 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008357 }
8358
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008359 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008360 remove_bg_job(pi);
8361 return checkjobs_and_fg_shell(pi);
8362 }
8363 return EXIT_SUCCESS;
8364}
8365#endif
8366
8367#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008368static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008369{
8370 const struct built_in_command *x;
8371
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008372 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008373 "Built-in commands:\n"
8374 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008375 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008376 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008377 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008378 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008379 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008380 return EXIT_SUCCESS;
8381}
8382#endif
8383
8384#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008385static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008386{
8387 struct pipe *job;
8388 const char *status_string;
8389
Denis Vlasenko87a86552008-07-29 19:43:10 +00008390 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008391 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008392 status_string = "Stopped";
8393 else
8394 status_string = "Running";
8395
8396 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8397 }
8398 return EXIT_SUCCESS;
8399}
8400#endif
8401
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008402#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008403static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008404{
8405 void *p;
8406 unsigned long l;
8407
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008408# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008409 /* Optional. Reduces probability of false positives */
8410 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008411# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008412 /* Crude attempt to find where "free memory" starts,
8413 * sans fragmentation. */
8414 p = malloc(240);
8415 l = (unsigned long)p;
8416 free(p);
8417 p = malloc(3400);
8418 if (l < (unsigned long)p) l = (unsigned long)p;
8419 free(p);
8420
8421 if (!G.memleak_value)
8422 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008423
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008424 l -= G.memleak_value;
8425 if ((long)l < 0)
8426 l = 0;
8427 l /= 1024;
8428 if (l > 127)
8429 l = 127;
8430
8431 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8432 return l;
8433}
8434#endif
8435
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008436static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008437{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008438 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008439 return EXIT_SUCCESS;
8440}
8441
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008442static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008443{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008444 const char *r;
8445 char *opt_n = NULL;
8446 char *opt_p = NULL;
8447 char *opt_t = NULL;
8448 char *opt_u = NULL;
8449 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008450
Denys Vlasenko03dad222010-01-12 23:29:57 +01008451 /* "!": do not abort on errors.
8452 * Option string must start with "sr" to match BUILTIN_READ_xxx
8453 */
8454 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8455 if (read_flags == (uint32_t)-1)
8456 return EXIT_FAILURE;
8457 argv += optind;
8458
8459 r = shell_builtin_read(set_local_var_from_halves,
8460 argv,
8461 get_local_var_value("IFS"), /* can be NULL */
8462 read_flags,
8463 opt_n,
8464 opt_p,
8465 opt_t,
8466 opt_u
8467 );
8468
8469 if ((uintptr_t)r > 1) {
8470 bb_error_msg("%s", r);
8471 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008472 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008473
Denys Vlasenko03dad222010-01-12 23:29:57 +01008474 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008475}
8476
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008477/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8478 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008479 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008480 * set [-abCefhmnuvx] [-o option] [argument...]
8481 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008482 * set -- [argument...]
8483 * set -o
8484 * set +o
8485 * Implementations shall support the options in both their hyphen and
8486 * plus-sign forms. These options can also be specified as options to sh.
8487 * Examples:
8488 * Write out all variables and their values: set
8489 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8490 * Turn on the -x and -v options: set -xv
8491 * Unset all positional parameters: set --
8492 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8493 * Set the positional parameters to the expansion of x, even if x expands
8494 * with a leading '-' or '+': set -- $x
8495 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008496 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008497 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008498static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008499{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008500 int n;
8501 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008502 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008503
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008504 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008505 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008506 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008507 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008508 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008509 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008510
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008511 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008512 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008513 ++argv;
8514 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008515 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008516 if (arg[0] != '+' && arg[0] != '-')
8517 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008518 for (n = 1; arg[n]; ++n) {
8519 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008520 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008521 if (arg[n] == 'o' && argv[1])
8522 argv++;
8523 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008524 } while ((arg = *++argv) != NULL);
8525 /* Now argv[0] is 1st argument */
8526
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008527 if (arg == NULL)
8528 return EXIT_SUCCESS;
8529 set_argv:
8530
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008531 /* NB: G.global_argv[0] ($0) is never freed/changed */
8532 g_argv = G.global_argv;
8533 if (G.global_args_malloced) {
8534 pp = g_argv;
8535 while (*++pp)
8536 free(*pp);
8537 g_argv[1] = NULL;
8538 } else {
8539 G.global_args_malloced = 1;
8540 pp = xzalloc(sizeof(pp[0]) * 2);
8541 pp[0] = g_argv[0]; /* retain $0 */
8542 g_argv = pp;
8543 }
8544 /* This realloc's G.global_argv */
8545 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8546
8547 n = 1;
8548 while (*++pp)
8549 n++;
8550 G.global_argc = n;
8551
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008552 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008553
8554 /* Nothing known, so abort */
8555 error:
8556 bb_error_msg("set: %s: invalid option", arg);
8557 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008558}
8559
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008560static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008561{
8562 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008563 argv = skip_dash_dash(argv);
8564 if (argv[0]) {
8565 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008566 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008567 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008568 if (G.global_args_malloced) {
8569 int m = 1;
8570 while (m <= n)
8571 free(G.global_argv[m++]);
8572 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008573 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008574 memmove(&G.global_argv[1], &G.global_argv[n+1],
8575 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008576 return EXIT_SUCCESS;
8577 }
8578 return EXIT_FAILURE;
8579}
8580
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008581static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008582{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008583 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008584 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008585 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008586#if ENABLE_HUSH_FUNCTIONS
8587 smallint sv_flg;
8588#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008589
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008590 argv = skip_dash_dash(argv);
8591 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008592 if (!filename) {
8593 /* bash says: "bash: .: filename argument required" */
8594 return 2; /* bash compat */
8595 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008596 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008597 if (!strchr(filename, '/')) {
8598 arg_path = find_in_path(filename);
8599 if (arg_path)
8600 filename = arg_path;
8601 }
8602 input = fopen_or_warn(filename, "r");
8603 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008604 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008605 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008606 return EXIT_FAILURE;
8607 }
8608 close_on_exec_on(fileno(input));
8609
Mike Frysinger885b6f22009-04-18 21:04:25 +00008610#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008611 sv_flg = G.flag_return_in_progress;
8612 /* "we are inside sourced file, ok to use return" */
8613 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008614#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008615 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008616
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008617 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008618 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008619
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008620 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008621#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008622 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008623#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008624
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008625 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008626}
8627
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008628static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008629{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008630 int rc;
8631 mode_t mask;
8632
8633 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008634 argv = skip_dash_dash(argv);
8635 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008636 mode_t old_mask = mask;
8637
8638 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008639 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008640 mask ^= 0777;
8641 if (rc == 0) {
8642 mask = old_mask;
8643 /* bash messages:
8644 * bash: umask: 'q': invalid symbolic mode operator
8645 * bash: umask: 999: octal number out of range
8646 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008647 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008648 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008649 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008650 rc = 1;
8651 /* Mimic bash */
8652 printf("%04o\n", (unsigned) mask);
8653 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008654 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008655 umask(mask);
8656
8657 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008658}
8659
Mike Frysingerd690f682009-03-30 06:50:54 +00008660/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008661static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008662{
Mike Frysingerd690f682009-03-30 06:50:54 +00008663 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008664 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008665
Denis Vlasenko28e67962009-04-26 23:22:40 +00008666 /* "!": do not abort on errors */
8667 /* "+": stop at 1st non-option */
8668 opts = getopt32(argv, "!+vf");
8669 if (opts == (unsigned)-1)
8670 return EXIT_FAILURE;
8671 if (opts == 3) {
8672 bb_error_msg("unset: -v and -f are exclusive");
8673 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008674 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008675 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008676
8677 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008678 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008679 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008680 if (unset_local_var(*argv)) {
8681 /* unset <nonexistent_var> doesn't fail.
8682 * Error is when one tries to unset RO var.
8683 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008684 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008685 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008686 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008687#if ENABLE_HUSH_FUNCTIONS
8688 else {
8689 unset_func(*argv);
8690 }
8691#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008692 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008693 }
8694 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008695}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008696
Mike Frysinger56bdea12009-03-28 20:01:58 +00008697/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008698static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008699{
8700 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008701 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008702
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008703 argv = skip_dash_dash(argv);
8704 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008705 /* Don't care about wait results */
8706 /* Note 1: must wait until there are no more children */
8707 /* Note 2: must be interruptible */
8708 /* Examples:
8709 * $ sleep 3 & sleep 6 & wait
8710 * [1] 30934 sleep 3
8711 * [2] 30935 sleep 6
8712 * [1] Done sleep 3
8713 * [2] Done sleep 6
8714 * $ sleep 3 & sleep 6 & wait
8715 * [1] 30936 sleep 3
8716 * [2] 30937 sleep 6
8717 * [1] Done sleep 3
8718 * ^C <-- after ~4 sec from keyboard
8719 * $
8720 */
8721 sigaddset(&G.blocked_set, SIGCHLD);
8722 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8723 while (1) {
8724 checkjobs(NULL);
8725 if (errno == ECHILD)
8726 break;
8727 /* Wait for SIGCHLD or any other signal of interest */
8728 /* sigtimedwait with infinite timeout: */
8729 sig = sigwaitinfo(&G.blocked_set, NULL);
8730 if (sig > 0) {
8731 sig = check_and_run_traps(sig);
8732 if (sig && sig != SIGCHLD) { /* see note 2 */
8733 ret = 128 + sig;
8734 break;
8735 }
8736 }
8737 }
8738 sigdelset(&G.blocked_set, SIGCHLD);
8739 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8740 return ret;
8741 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008742
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008743 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008744 while (*argv) {
8745 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008746 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008747 /* mimic bash message */
8748 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008749 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008750 }
8751 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008752 if (WIFSIGNALED(status))
8753 ret = 128 + WTERMSIG(status);
8754 else if (WIFEXITED(status))
8755 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008756 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008757 ret = EXIT_FAILURE;
8758 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008759 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008760 ret = 127;
8761 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008762 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008763 }
8764
8765 return ret;
8766}
8767
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008768#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8769static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8770{
8771 if (argv[1]) {
8772 def = bb_strtou(argv[1], NULL, 10);
8773 if (errno || def < def_min || argv[2]) {
8774 bb_error_msg("%s: bad arguments", argv[0]);
8775 def = UINT_MAX;
8776 }
8777 }
8778 return def;
8779}
8780#endif
8781
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008782#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008783static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008784{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008785 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008786 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008787 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008788 return EXIT_SUCCESS; /* bash compat */
8789 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008790 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008791
8792 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8793 if (depth == UINT_MAX)
8794 G.flag_break_continue = BC_BREAK;
8795 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008796 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008797
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008798 return EXIT_SUCCESS;
8799}
8800
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008801static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008802{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008803 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8804 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008805}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008806#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008807
8808#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008809static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008810{
8811 int rc;
8812
8813 if (G.flag_return_in_progress != -1) {
8814 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8815 return EXIT_FAILURE; /* bash compat */
8816 }
8817
8818 G.flag_return_in_progress = 1;
8819
8820 /* bash:
8821 * out of range: wraps around at 256, does not error out
8822 * non-numeric param:
8823 * f() { false; return qwe; }; f; echo $?
8824 * bash: return: qwe: numeric argument required <== we do this
8825 * 255 <== we also do this
8826 */
8827 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8828 return rc;
8829}
8830#endif