blob: a771e9cd99d8b5b2f8d614a6f5ef048f955cc213 [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 Vlasenko202a2d12010-07-16 12:36:14 +0200108//applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
109//applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200110//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))
112
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
258//usage: "[-nx] [-c SCRIPT]"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200259//usage:#define hush_full_usage ""
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100260//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200261//usage:#define msh_full_usage ""
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +0200262//usage:#define sh_trivial_usage NOUSAGE_STR
263//usage:#define sh_full_usage ""
264//usage:#define bash_trivial_usage NOUSAGE_STR
265//usage:#define bash_full_usage ""
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200266
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000267
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200268/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000269#define LEAK_HUNTING 0
270#define BUILD_AS_NOMMU 0
271/* Enable/disable sanity checks. Ok to enable in production,
272 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
273 * Keeping 1 for now even in released versions.
274 */
275#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200276/* Slightly bigger (+200 bytes), but faster hush.
277 * So far it only enables a trick with counting SIGCHLDs and forks,
278 * which allows us to do fewer waitpid's.
279 * (we can detect a case where neither forks were done nor SIGCHLDs happened
280 * and therefore waitpid will return the same result as last time)
281 */
282#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200283/* TODO: implement simplified code for users which do not need ${var%...} ops
284 * So far ${var%...} ops are always enabled:
285 */
286#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000287
288
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000289#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000290# undef BB_MMU
291# undef USE_FOR_NOMMU
292# undef USE_FOR_MMU
293# define BB_MMU 0
294# define USE_FOR_NOMMU(...) __VA_ARGS__
295# define USE_FOR_MMU(...)
296#endif
297
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200298#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100299#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000300/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000301# undef CONFIG_FEATURE_SH_STANDALONE
302# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000303# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100304# undef IF_NOT_FEATURE_SH_STANDALONE
305# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000306# define IF_FEATURE_SH_STANDALONE(...)
307# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000308#endif
309
Denis Vlasenko05743d72008-02-10 12:10:08 +0000310#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000311# undef ENABLE_FEATURE_EDITING
312# define ENABLE_FEATURE_EDITING 0
313# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
314# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000315#endif
316
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000317/* Do we support ANY keywords? */
318#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000319# define HAS_KEYWORDS 1
320# define IF_HAS_KEYWORDS(...) __VA_ARGS__
321# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000322#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000323# define HAS_KEYWORDS 0
324# define IF_HAS_KEYWORDS(...)
325# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000326#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000327
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000328/* If you comment out one of these below, it will be #defined later
329 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000330#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000331/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000332#define debug_printf_parse(...) do {} while (0)
333#define debug_print_tree(a, b) do {} while (0)
334#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000335#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000336#define debug_printf_jobs(...) do {} while (0)
337#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200338#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000339#define debug_printf_glob(...) do {} while (0)
340#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000341#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000342#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000343
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000344#define ERR_PTR ((void*)(long)1)
345
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200346#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000347
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200348#define _SPECIAL_VARS_STR "_*@$!?#"
349#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
350#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200351#if ENABLE_HUSH_BASH_COMPAT
352/* Support / and // replace ops */
353/* Note that // is stored as \ in "encoded" string representation */
354# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
355# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
356# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
357#else
358# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
359# define VAR_SUBST_OPS "%#:-=+?"
360# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
361#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200362
363#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000364
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200365struct variable;
366
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000367static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
368
369/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000370 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000371 */
372#if !BB_MMU
373typedef struct nommu_save_t {
374 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200375 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000376 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000377 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000378} nommu_save_t;
379#endif
380
Denys Vlasenko9b782552010-09-08 13:33:26 +0200381enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000382 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000383#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000384 RES_IF ,
385 RES_THEN ,
386 RES_ELIF ,
387 RES_ELSE ,
388 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000389#endif
390#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000391 RES_FOR ,
392 RES_WHILE ,
393 RES_UNTIL ,
394 RES_DO ,
395 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000396#endif
397#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000398 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000399#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000400#if ENABLE_HUSH_CASE
401 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200402 /* three pseudo-keywords support contrived "case" syntax: */
403 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
404 RES_MATCH , /* "word)" */
405 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000406 RES_ESAC ,
407#endif
408 RES_XXXX ,
409 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200410};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000411
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000412typedef struct o_string {
413 char *data;
414 int length; /* position where data is appended */
415 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200416 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000417 /* At least some part of the string was inside '' or "",
418 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200419 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000420 smallint has_empty_slot;
421 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
422} o_string;
423enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200424 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
425 EXP_FLAG_GLOB = 0x2,
426 /* Protect newly added chars against globbing
427 * by prepending \ to *, ?, [, \ */
428 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
429};
430enum {
431 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000432 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200433 NOT_ASSIGNMENT = 2,
434 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
435 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000436};
437/* Used for initialization: o_string foo = NULL_O_STRING; */
438#define NULL_O_STRING { NULL }
439
440/* I can almost use ordinary FILE*. Is open_memstream() universally
441 * available? Where is it documented? */
442typedef struct in_str {
443 const char *p;
444 /* eof_flag=1: last char in ->p is really an EOF */
445 char eof_flag; /* meaningless if ->p == NULL */
446 char peek_buf[2];
447#if ENABLE_HUSH_INTERACTIVE
448 smallint promptme;
449 smallint promptmode; /* 0: PS1, 1: PS2 */
450#endif
451 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200452 int (*get) (struct in_str *) FAST_FUNC;
453 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000454} in_str;
455#define i_getch(input) ((input)->get(input))
456#define i_peek(input) ((input)->peek(input))
457
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200458/* The descrip member of this structure is only used to make
459 * debugging output pretty */
460static const struct {
461 int mode;
462 signed char default_fd;
463 char descrip[3];
464} redir_table[] = {
465 { O_RDONLY, 0, "<" },
466 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
467 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
468 { O_CREAT|O_RDWR, 1, "<>" },
469 { O_RDONLY, 0, "<<" },
470/* Should not be needed. Bogus default_fd helps in debugging */
471/* { O_RDONLY, 77, "<<" }, */
472};
473
Eric Andersen25f27032001-04-26 23:22:31 +0000474struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000475 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000476 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000477 int rd_fd; /* fd to redirect */
478 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
479 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000480 smallint rd_type; /* (enum redir_type) */
481 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000482 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200483 * bit 0: do we need to trim leading tabs?
484 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000485 */
Eric Andersen25f27032001-04-26 23:22:31 +0000486};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000487typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200488 REDIRECT_INPUT = 0,
489 REDIRECT_OVERWRITE = 1,
490 REDIRECT_APPEND = 2,
491 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000492 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200493 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000494
495 REDIRFD_CLOSE = -3,
496 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000497 REDIRFD_TO_FILE = -1,
498 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000499
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000500 HEREDOC_SKIPTABS = 1,
501 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000502} redir_type;
503
Eric Andersen25f27032001-04-26 23:22:31 +0000504
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000505struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000506 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000507 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000508 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200509 smallint cmd_type; /* CMD_xxx */
510#define CMD_NORMAL 0
511#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200512#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200513/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200514# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000515#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200516#if ENABLE_HUSH_FUNCTIONS
517# define CMD_FUNCDEF 3
518#endif
519
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100520 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200521 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
522 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000523#if !BB_MMU
524 char *group_as_string;
525#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000526#if ENABLE_HUSH_FUNCTIONS
527 struct function *child_func;
528/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200529 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000530 * When we execute "f1() {a;}" cmd, we create new function and clear
531 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200532 * When we execute "f1() {b;}", we notice that f1 exists,
533 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000534 * we put those fields back into cmd->xxx
535 * (struct function has ->parent_cmd ptr to facilitate that).
536 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
537 * Without this trick, loop would execute a;b;b;b;...
538 * instead of correct sequence a;b;a;b;...
539 * When command is freed, it severs the link
540 * (sets ->child_func->parent_cmd to NULL).
541 */
542#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000543 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000544/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
545 * and on execution these are substituted with their values.
546 * Substitution can make _several_ words out of one argv[n]!
547 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000548 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000549 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000550 struct redir_struct *redirects; /* I/O redirections */
551};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000552/* Is there anything in this command at all? */
553#define IS_NULL_CMD(cmd) \
554 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
555
Eric Andersen25f27032001-04-26 23:22:31 +0000556struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000557 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000558 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000559 int alive_cmds; /* number of commands running (not exited) */
560 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000561#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000562 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000563 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000564 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000565#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000566 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000567 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000568 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
569 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000570};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000571typedef enum pipe_style {
572 PIPE_SEQ = 1,
573 PIPE_AND = 2,
574 PIPE_OR = 3,
575 PIPE_BG = 4,
576} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000577/* Is there anything in this pipe at all? */
578#define IS_NULL_PIPE(pi) \
579 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000580
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000581/* This holds pointers to the various results of parsing */
582struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000583 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000584 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000585 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000586 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000587 /* last command in pipe (being constructed right now) */
588 struct command *command;
589 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000590 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000591#if !BB_MMU
592 o_string as_string;
593#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000594#if HAS_KEYWORDS
595 smallint ctx_res_w;
596 smallint ctx_inverted; /* "! cmd | cmd" */
597#if ENABLE_HUSH_CASE
598 smallint ctx_dsemicolon; /* ";;" seen */
599#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000600 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
601 int old_flag;
602 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000603 * example: "if pipe1; pipe2; then pipe3; fi"
604 * when we see "if" or "then", we malloc and copy current context,
605 * and make ->stack point to it. then we parse pipeN.
606 * when closing "then" / fi" / whatever is found,
607 * we move list_head into ->stack->command->group,
608 * copy ->stack into current context, and delete ->stack.
609 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000610 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000611 struct parse_context *stack;
612#endif
613};
614
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000615/* On program start, environ points to initial environment.
616 * putenv adds new pointers into it, unsetenv removes them.
617 * Neither of these (de)allocates the strings.
618 * setenv allocates new strings in malloc space and does putenv,
619 * and thus setenv is unusable (leaky) for shell's purposes */
620#define setenv(...) setenv_is_leaky_dont_use()
621struct variable {
622 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000623 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200624#if ENABLE_HUSH_LOCAL
625 unsigned func_nest_level;
626#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000627 int max_len; /* if > 0, name is part of initial env; else name is malloced */
628 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000629 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000630};
631
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000632enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000633 BC_BREAK = 1,
634 BC_CONTINUE = 2,
635};
636
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000637#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000638struct function {
639 struct function *next;
640 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000641 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000642 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200643# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000644 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200645# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000646};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000647#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000648
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000649
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100650/* set -/+o OPT support. (TODO: make it optional)
651 * bash supports the following opts:
652 * allexport off
653 * braceexpand on
654 * emacs on
655 * errexit off
656 * errtrace off
657 * functrace off
658 * hashall on
659 * histexpand off
660 * history on
661 * ignoreeof off
662 * interactive-comments on
663 * keyword off
664 * monitor on
665 * noclobber off
666 * noexec off
667 * noglob off
668 * nolog off
669 * notify off
670 * nounset off
671 * onecmd off
672 * physical off
673 * pipefail off
674 * posix off
675 * privileged off
676 * verbose off
677 * vi off
678 * xtrace off
679 */
Dan Fandrich85c62472010-11-20 13:05:17 -0800680static const char o_opt_strings[] ALIGN1 =
681 "pipefail\0"
682 "noexec\0"
683#if ENABLE_HUSH_MODE_X
684 "xtrace\0"
685#endif
686 ;
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100687enum {
688 OPT_O_PIPEFAIL,
Dan Fandrich85c62472010-11-20 13:05:17 -0800689 OPT_O_NOEXEC,
690#if ENABLE_HUSH_MODE_X
691 OPT_O_XTRACE,
692#endif
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100693 NUM_OPT_O
694};
695
696
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000697/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000698/* Sorted roughly by size (smaller offsets == smaller code) */
699struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000700 /* interactive_fd != 0 means we are an interactive shell.
701 * If we are, then saved_tty_pgrp can also be != 0, meaning
702 * that controlling tty is available. With saved_tty_pgrp == 0,
703 * job control still works, but terminal signals
704 * (^C, ^Z, ^Y, ^\) won't work at all, and background
705 * process groups can only be created with "cmd &".
706 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
707 * to give tty to the foreground process group,
708 * and will take it back when the group is stopped (^Z)
709 * or killed (^C).
710 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000711#if ENABLE_HUSH_INTERACTIVE
712 /* 'interactive_fd' is a fd# open to ctty, if we have one
713 * _AND_ if we decided to act interactively */
714 int interactive_fd;
715 const char *PS1;
716 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000717# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000718#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000719# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000720#endif
721#if ENABLE_FEATURE_EDITING
722 line_input_t *line_input_state;
723#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000724 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200725 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000726 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200727#if ENABLE_HUSH_RANDOM_SUPPORT
728 random_t random_gen;
729#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000730#if ENABLE_HUSH_JOB
731 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000732 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000733 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000734 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400735# define G_saved_tty_pgrp (G.saved_tty_pgrp)
736#else
737# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000738#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100739 char o_opt[NUM_OPT_O];
Denys Vlasenko57542eb2010-11-28 03:59:30 +0100740#if ENABLE_HUSH_MODE_X
741# define G_x_mode (G.o_opt[OPT_O_XTRACE])
742#else
743# define G_x_mode 0
744#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000745 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000746#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000747 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000748#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000749#if ENABLE_HUSH_FUNCTIONS
750 /* 0: outside of a function (or sourced file)
751 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000752 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000753 */
754 smallint flag_return_in_progress;
755#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000756 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000757 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000758 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000759 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000760 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100761 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000762 /* how many non-NULL argv's we have. NB: $# + 1 */
763 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000764 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000765#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000766 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000767#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000768#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000769 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000770 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000771#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000772 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000773 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200774 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200775 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000776#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000777 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200778# if ENABLE_HUSH_LOCAL
779 struct variable **shadowed_vars_pp;
780 unsigned func_nest_level;
781# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000782#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000783 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200784#if ENABLE_HUSH_FAST
785 unsigned count_SIGCHLD;
786 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200787 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200788#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000789 /* which signals have non-DFL handler (even with no traps set)? */
790 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000791 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000792 sigset_t blocked_set;
793 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000794#if HUSH_DEBUG
795 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000796 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000797#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200798 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000799};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000800#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000801/* Not #defining name to G.name - this quickly gets unwieldy
802 * (too many defines). Also, I actually prefer to see when a variable
803 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000804#define INIT_G() do { \
805 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
806} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000807
808
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000809/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200810static int builtin_cd(char **argv) FAST_FUNC;
811static int builtin_echo(char **argv) FAST_FUNC;
812static int builtin_eval(char **argv) FAST_FUNC;
813static int builtin_exec(char **argv) FAST_FUNC;
814static int builtin_exit(char **argv) FAST_FUNC;
815static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000816#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200817static int builtin_fg_bg(char **argv) FAST_FUNC;
818static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000819#endif
820#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200821static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000822#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200823#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200824static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200825#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000826#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200827static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000828#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400829#if ENABLE_PRINTF
830static int builtin_printf(char **argv) FAST_FUNC;
831#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200832static int builtin_pwd(char **argv) FAST_FUNC;
833static int builtin_read(char **argv) FAST_FUNC;
834static int builtin_set(char **argv) FAST_FUNC;
835static int builtin_shift(char **argv) FAST_FUNC;
836static int builtin_source(char **argv) FAST_FUNC;
837static int builtin_test(char **argv) FAST_FUNC;
838static int builtin_trap(char **argv) FAST_FUNC;
839static int builtin_type(char **argv) FAST_FUNC;
840static int builtin_true(char **argv) FAST_FUNC;
841static int builtin_umask(char **argv) FAST_FUNC;
842static int builtin_unset(char **argv) FAST_FUNC;
843static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000844#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200845static int builtin_break(char **argv) FAST_FUNC;
846static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000847#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000848#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200849static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000850#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000851
852/* Table of built-in functions. They can be forked or not, depending on
853 * context: within pipes, they fork. As simple commands, they do not.
854 * When used in non-forking context, they can change global variables
855 * in the parent shell process. If forked, of course they cannot.
856 * For example, 'unset foo | whatever' will parse and run, but foo will
857 * still be set at the end. */
858struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100859 const char *b_cmd;
860 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000861#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100862 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200863# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000864#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200865# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000866#endif
867};
868
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200869static const struct built_in_command bltins1[] = {
870 BLTIN("." , builtin_source , "Run commands in a file"),
871 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000872#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200873 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000874#endif
875#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200876 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000877#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200878 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000879#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200880 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000881#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200882 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
883 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
884 BLTIN("exit" , builtin_exit , "Exit"),
885 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000886#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200887 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000888#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000889#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200890 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000891#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000892#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200893 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000894#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200895#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200896 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200897#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000898#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200899 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000900#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200901 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000902#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200903 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000904#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200905 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
906 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200907#if ENABLE_HUSH_BASH_COMPAT
908 BLTIN("source" , builtin_source , "Run commands in a file"),
909#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200910 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100911 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100912 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200913 BLTIN("umask" , builtin_umask , "Set file creation mask"),
914 BLTIN("unset" , builtin_unset , "Unset variables"),
915 BLTIN("wait" , builtin_wait , "Wait for process"),
916};
917/* For now, echo and test are unconditionally enabled.
918 * Maybe make it configurable? */
919static const struct built_in_command bltins2[] = {
920 BLTIN("[" , builtin_test , NULL),
921 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400922#if ENABLE_PRINTF
923 BLTIN("printf" , builtin_printf , NULL),
924#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200925 BLTIN("pwd" , builtin_pwd , NULL),
926 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000927};
928
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000929
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000930/* Debug printouts.
931 */
932#if HUSH_DEBUG
933/* prevent disasters with G.debug_indent < 0 */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100934# define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000935# define debug_enter() (G.debug_indent++)
936# define debug_leave() (G.debug_indent--)
937#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200938# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000939# define debug_enter() ((void)0)
940# define debug_leave() ((void)0)
941#endif
942
943#ifndef debug_printf
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100944# define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000945#endif
946
947#ifndef debug_printf_parse
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100948# define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000949#endif
950
951#ifndef debug_printf_exec
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100952#define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000953#endif
954
955#ifndef debug_printf_env
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100956# define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000957#endif
958
959#ifndef debug_printf_jobs
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100960# define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000961# define DEBUG_JOBS 1
962#else
963# define DEBUG_JOBS 0
964#endif
965
966#ifndef debug_printf_expand
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100967# define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000968# define DEBUG_EXPAND 1
969#else
970# define DEBUG_EXPAND 0
971#endif
972
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200973#ifndef debug_printf_varexp
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100974# define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200975#endif
976
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000977#ifndef debug_printf_glob
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100978# define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000979# define DEBUG_GLOB 1
980#else
981# define DEBUG_GLOB 0
982#endif
983
984#ifndef debug_printf_list
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100985# define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000986#endif
987
988#ifndef debug_printf_subst
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100989# define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000990#endif
991
992#ifndef debug_printf_clean
Denys Vlasenko75eb9d22010-12-21 21:18:12 +0100993# define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000994# define DEBUG_CLEAN 1
995#else
996# define DEBUG_CLEAN 0
997#endif
998
999#if DEBUG_EXPAND
1000static void debug_print_strings(const char *prefix, char **vv)
1001{
1002 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001003 fdprintf(2, "%s:\n", prefix);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001004 while (*vv)
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001005 fdprintf(2, " '%s'\n", *vv++);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001006}
1007#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001008# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001009#endif
1010
1011
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001012/* Leak hunting. Use hush_leaktool.sh for post-processing.
1013 */
1014#if LEAK_HUNTING
1015static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001016{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001017 void *ptr = xmalloc((size + 0xff) & ~0xff);
1018 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1019 return ptr;
1020}
1021static void *xxrealloc(int lineno, void *ptr, size_t size)
1022{
1023 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1024 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1025 return ptr;
1026}
1027static char *xxstrdup(int lineno, const char *str)
1028{
1029 char *ptr = xstrdup(str);
1030 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1031 return ptr;
1032}
1033static void xxfree(void *ptr)
1034{
1035 fdprintf(2, "free %p\n", ptr);
1036 free(ptr);
1037}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001038# define xmalloc(s) xxmalloc(__LINE__, s)
1039# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1040# define xstrdup(s) xxstrdup(__LINE__, s)
1041# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001042#endif
1043
1044
1045/* Syntax and runtime errors. They always abort scripts.
1046 * In interactive use they usually discard unparsed and/or unexecuted commands
1047 * and return to the prompt.
1048 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1049 */
1050#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001051# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001052# define syntax_error(lineno, msg) syntax_error(msg)
1053# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1054# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1055# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1056# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001057#endif
1058
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001059static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001060{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001061 va_list p;
1062
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001063#if HUSH_DEBUG >= 2
1064 bb_error_msg("hush.c:%u", lineno);
1065#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001066 va_start(p, fmt);
1067 bb_verror_msg(fmt, p, NULL);
1068 va_end(p);
1069 if (!G_interactive_fd)
1070 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001071}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001072
1073static void syntax_error(unsigned lineno, const char *msg)
1074{
1075 if (msg)
1076 die_if_script(lineno, "syntax error: %s", msg);
1077 else
1078 die_if_script(lineno, "syntax error", NULL);
1079}
1080
1081static void syntax_error_at(unsigned lineno, const char *msg)
1082{
1083 die_if_script(lineno, "syntax error at '%s'", msg);
1084}
1085
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001086static void syntax_error_unterm_str(unsigned lineno, const char *s)
1087{
1088 die_if_script(lineno, "syntax error: unterminated %s", s);
1089}
1090
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001091/* It so happens that all such cases are totally fatal
1092 * even if shell is interactive: EOF while looking for closing
1093 * delimiter. There is nowhere to read stuff from after that,
1094 * it's EOF! The only choice is to terminate.
1095 */
1096static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001097static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001098{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001099 char msg[2] = { ch, '\0' };
1100 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001101 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001102}
1103
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001104static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001105{
1106 char msg[2];
1107 msg[0] = ch;
1108 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001109 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001110}
1111
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001112#if HUSH_DEBUG < 2
1113# undef die_if_script
1114# undef syntax_error
1115# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001116# undef syntax_error_unterm_ch
1117# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001118# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001119#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001120# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001121# define syntax_error(msg) syntax_error(__LINE__, msg)
1122# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1123# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1124# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1125# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001126#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001127
Denis Vlasenko552433b2009-04-04 19:29:21 +00001128
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001129#if ENABLE_HUSH_INTERACTIVE
1130static void cmdedit_update_prompt(void);
1131#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001132# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001133#endif
1134
1135
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001136/* Utility functions
1137 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001138/* Replace each \x with x in place, return ptr past NUL. */
1139static char *unbackslash(char *src)
1140{
Denys Vlasenko71885402009-09-24 01:44:13 +02001141 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001142 while (1) {
1143 if (*src == '\\')
1144 src++;
1145 if ((*dst++ = *src++) == '\0')
1146 break;
1147 }
1148 return dst;
1149}
1150
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001151static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001152{
1153 int i;
1154 unsigned count1;
1155 unsigned count2;
1156 char **v;
1157
1158 v = strings;
1159 count1 = 0;
1160 if (v) {
1161 while (*v) {
1162 count1++;
1163 v++;
1164 }
1165 }
1166 count2 = 0;
1167 v = add;
1168 while (*v) {
1169 count2++;
1170 v++;
1171 }
1172 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1173 v[count1 + count2] = NULL;
1174 i = count2;
1175 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001176 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001177 return v;
1178}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001179#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001180static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1181{
1182 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1183 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1184 return ptr;
1185}
1186#define add_strings_to_strings(strings, add, need_to_dup) \
1187 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1188#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001189
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001190/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001191static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001192{
1193 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001194 v[0] = add;
1195 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001196 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001197}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001198#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001199static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1200{
1201 char **ptr = add_string_to_strings(strings, add);
1202 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1203 return ptr;
1204}
1205#define add_string_to_strings(strings, add) \
1206 xx_add_string_to_strings(__LINE__, strings, add)
1207#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001208
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001209static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001210{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001211 char **v;
1212
1213 if (!strings)
1214 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001215 v = strings;
1216 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001217 free(*v);
1218 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001219 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001220 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001221}
1222
Denis Vlasenko76d50412008-06-10 16:19:39 +00001223
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001224/* Helpers for setting new $n and restoring them back
1225 */
1226typedef struct save_arg_t {
1227 char *sv_argv0;
1228 char **sv_g_argv;
1229 int sv_g_argc;
1230 smallint sv_g_malloced;
1231} save_arg_t;
1232
1233static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1234{
1235 int n;
1236
1237 sv->sv_argv0 = argv[0];
1238 sv->sv_g_argv = G.global_argv;
1239 sv->sv_g_argc = G.global_argc;
1240 sv->sv_g_malloced = G.global_args_malloced;
1241
1242 argv[0] = G.global_argv[0]; /* retain $0 */
1243 G.global_argv = argv;
1244 G.global_args_malloced = 0;
1245
1246 n = 1;
1247 while (*++argv)
1248 n++;
1249 G.global_argc = n;
1250}
1251
1252static void restore_G_args(save_arg_t *sv, char **argv)
1253{
1254 char **pp;
1255
1256 if (G.global_args_malloced) {
1257 /* someone ran "set -- arg1 arg2 ...", undo */
1258 pp = G.global_argv;
1259 while (*++pp) /* note: does not free $0 */
1260 free(*pp);
1261 free(G.global_argv);
1262 }
1263 argv[0] = sv->sv_argv0;
1264 G.global_argv = sv->sv_g_argv;
1265 G.global_argc = sv->sv_g_argc;
1266 G.global_args_malloced = sv->sv_g_malloced;
1267}
1268
1269
Denis Vlasenkod5762932009-03-31 11:22:57 +00001270/* Basic theory of signal handling in shell
1271 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001272 * This does not describe what hush does, rather, it is current understanding
1273 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001274 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1275 *
1276 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1277 * is finished or backgrounded. It is the same in interactive and
1278 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001279 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001280 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001281 * backgrounds (i.e. stops) or kills all members of currently running
1282 * pipe.
1283 *
1284 * Wait builtin in interruptible by signals for which user trap is set
1285 * or by SIGINT in interactive shell.
1286 *
1287 * Trap handlers will execute even within trap handlers. (right?)
1288 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001289 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1290 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001291 *
1292 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001293 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001294 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001295 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001296 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001297 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001298 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001299 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001300 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001301 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001302 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001303 *
1304 * SIGQUIT: ignore
1305 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001306 * SIGHUP (interactive):
1307 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001308 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001309 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1310 * that all pipe members are stopped. Try this in bash:
1311 * while :; do :; done - ^Z does not background it
1312 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001313 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001314 * of the command line, show prompt. NB: ^C does not send SIGINT
1315 * to interactive shell while shell is waiting for a pipe,
1316 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001317 * Example 1: this waits 5 sec, but does not execute ls:
1318 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1319 * Example 2: this does not wait and does not execute ls:
1320 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1321 * Example 3: this does not wait 5 sec, but executes ls:
1322 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001323 *
1324 * (What happens to signals which are IGN on shell start?)
1325 * (What happens with signal mask on shell start?)
1326 *
1327 * Implementation in hush
1328 * ======================
1329 * We use in-kernel pending signal mask to determine which signals were sent.
1330 * We block all signals which we don't want to take action immediately,
1331 * i.e. we block all signals which need to have special handling as described
1332 * above, and all signals which have traps set.
1333 * After each pipe execution, we extract any pending signals via sigtimedwait()
1334 * and act on them.
1335 *
1336 * unsigned non_DFL_mask: a mask of such "special" signals
1337 * sigset_t blocked_set: current blocked signal set
1338 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001339 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001340 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001341 * "trap 'cmd' SIGxxx":
1342 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001343 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001344 * unblock signals with special interactive handling
1345 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001346 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001347 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001348 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001349 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001350 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001351 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001352 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001353 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001354 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001355 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001356 * Standard says "When a subshell is entered, traps that are not being ignored
1357 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001358 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001359 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001360enum {
1361 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001362 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001363 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001364 | (1 << SIGHUP)
1365 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001366 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001367#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001368 | (1 << SIGTTIN)
1369 | (1 << SIGTTOU)
1370 | (1 << SIGTSTP)
1371#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001372};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001373
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001374#if ENABLE_HUSH_FAST
1375static void SIGCHLD_handler(int sig UNUSED_PARAM)
1376{
1377 G.count_SIGCHLD++;
1378//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1379}
1380#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001381
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001382#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001383
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001384/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001385# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001386/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001387# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001388
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001389/* Restores tty foreground process group, and exits.
1390 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001391 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001392 * or called directly with -EXITCODE.
1393 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001394static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001395static void sigexit(int sig)
1396{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001397 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001398 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001399
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001400 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001401 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001402 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1403 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001404
1405 /* Not a signal, just exit */
1406 if (sig <= 0)
1407 _exit(- sig);
1408
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001409 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001410}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001411#else
1412
Denys Vlasenko8391c482010-05-22 17:50:43 +02001413# define disable_restore_tty_pgrp_on_exit() ((void)0)
1414# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001415
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001416#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001417
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001418/* Restores tty foreground process group, and exits. */
1419static void hush_exit(int exitcode) NORETURN;
1420static void hush_exit(int exitcode)
1421{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001422 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1423 /* Prevent recursion:
1424 * trap "echo Hi; exit" EXIT; exit
1425 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001426 char *argv[3];
1427 /* argv[0] is unused */
1428 argv[1] = G.traps[0];
1429 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001430 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001431 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001432 * "trap" will still show it, if executed
1433 * in the handler */
1434 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001435 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001436
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01001437#if ENABLE_FEATURE_CLEAN_UP
1438 {
1439 struct variable *cur_var;
1440 if (G.cwd != bb_msg_unknown)
1441 free((char*)G.cwd);
1442 cur_var = G.top_var;
1443 while (cur_var) {
1444 struct variable *tmp = cur_var;
1445 if (!cur_var->max_len)
1446 free(cur_var->varstr);
1447 cur_var = cur_var->next;
1448 free(tmp);
1449 }
1450 }
1451#endif
1452
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001453#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001454 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001455 sigexit(- (exitcode & 0xff));
1456#else
1457 exit(exitcode);
1458#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001459}
1460
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001461
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001462static int check_and_run_traps(int sig)
1463{
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001464 /* I want it in rodata, not in bss.
1465 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1466 * initializer. But other compilers may still use bss.
1467 * TODO: find more portable solution.
1468 */
1469 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001470 smalluint save_rcode;
1471 int last_sig = 0;
1472
1473 if (sig)
1474 goto jump_in;
1475 while (1) {
1476 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1477 if (sig <= 0)
1478 break;
1479 jump_in:
1480 last_sig = sig;
1481 if (G.traps && G.traps[sig]) {
1482 if (G.traps[sig][0]) {
1483 /* We have user-defined handler */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001484 char *argv[3];
1485 /* argv[0] is unused */
1486 argv[1] = G.traps[sig];
1487 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001488 save_rcode = G.last_exitcode;
1489 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001490 G.last_exitcode = save_rcode;
1491 } /* else: "" trap, ignoring signal */
1492 continue;
1493 }
1494 /* not a trap: special action */
1495 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001496#if ENABLE_HUSH_FAST
1497 case SIGCHLD:
1498 G.count_SIGCHLD++;
1499//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1500 break;
1501#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001502 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001503 /* Builtin was ^C'ed, make it look prettier: */
1504 bb_putchar('\n');
1505 G.flag_SIGINT = 1;
1506 break;
1507#if ENABLE_HUSH_JOB
1508 case SIGHUP: {
1509 struct pipe *job;
1510 /* bash is observed to signal whole process groups,
1511 * not individual processes */
1512 for (job = G.job_list; job; job = job->next) {
1513 if (job->pgrp <= 0)
1514 continue;
1515 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1516 if (kill(- job->pgrp, SIGHUP) == 0)
1517 kill(- job->pgrp, SIGCONT);
1518 }
1519 sigexit(SIGHUP);
1520 }
1521#endif
1522 default: /* ignored: */
1523 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1524 break;
1525 }
1526 }
1527 return last_sig;
1528}
1529
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001530
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001531static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001532{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001533 if (force || G.cwd == NULL) {
1534 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1535 * we must not try to free(bb_msg_unknown) */
1536 if (G.cwd == bb_msg_unknown)
1537 G.cwd = NULL;
1538 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1539 if (!G.cwd)
1540 G.cwd = bb_msg_unknown;
1541 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001542 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001543}
1544
Denis Vlasenko83506862007-11-23 13:11:42 +00001545
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001546/*
1547 * Shell and environment variable support
1548 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001549static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001550{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001551 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001552 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001553
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001554 pp = &G.top_var;
1555 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001556 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001557 return pp;
1558 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001559 }
1560 return NULL;
1561}
1562
Denys Vlasenko03dad222010-01-12 23:29:57 +01001563static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001564{
Denys Vlasenko29082232010-07-16 13:52:32 +02001565 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001566 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001567
1568 if (G.expanded_assignments) {
1569 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001570 while (*cpp) {
1571 char *cp = *cpp;
1572 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1573 return cp + len + 1;
1574 cpp++;
1575 }
1576 }
1577
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001578 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001579 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001580 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001581
Denys Vlasenkodea47882009-10-09 15:40:49 +02001582 if (strcmp(name, "PPID") == 0)
1583 return utoa(G.root_ppid);
1584 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001585#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001586 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001587 return utoa(next_random(&G.random_gen));
1588#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001589 return NULL;
1590}
1591
1592/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001593 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001594 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001595 * 0: do not change export flag
1596 * (if creating new variable, flag will be 0)
1597 * 1: set export flag and putenv the variable
1598 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001599 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001600 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001601#if !BB_MMU && ENABLE_HUSH_LOCAL
1602/* all params are used */
1603#elif BB_MMU && ENABLE_HUSH_LOCAL
1604#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1605 set_local_var(str, flg_export, local_lvl)
1606#elif BB_MMU && !ENABLE_HUSH_LOCAL
1607#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001608 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001609#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1610#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1611 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001612#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001613static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001614{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001615 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001616 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001617 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001618 int name_len;
1619
Denis Vlasenko950bd722009-04-21 11:23:56 +00001620 eq_sign = strchr(str, '=');
1621 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001622 free(str);
1623 return -1;
1624 }
1625
Denis Vlasenko950bd722009-04-21 11:23:56 +00001626 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001627 var_pp = &G.top_var;
1628 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001629 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001630 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001631 continue;
1632 }
1633 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001634 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001635#if !BB_MMU
1636 if (!flg_read_only)
1637#endif
1638 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001639 free(str);
1640 return -1;
1641 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001642 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001643 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1644 *eq_sign = '\0';
1645 unsetenv(str);
1646 *eq_sign = '=';
1647 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001648#if ENABLE_HUSH_LOCAL
1649 if (cur->func_nest_level < local_lvl) {
1650 /* New variable is declared as local,
1651 * and existing one is global, or local
1652 * from enclosing function.
1653 * Remove and save old one: */
1654 *var_pp = cur->next;
1655 cur->next = *G.shadowed_vars_pp;
1656 *G.shadowed_vars_pp = cur;
1657 /* bash 3.2.33(1) and exported vars:
1658 * # export z=z
1659 * # f() { local z=a; env | grep ^z; }
1660 * # f
1661 * z=a
1662 * # env | grep ^z
1663 * z=z
1664 */
1665 if (cur->flg_export)
1666 flg_export = 1;
1667 break;
1668 }
1669#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001670 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001671 free_and_exp:
1672 free(str);
1673 goto exp;
1674 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001675 if (cur->max_len != 0) {
1676 if (cur->max_len >= strlen(str)) {
1677 /* This one is from startup env, reuse space */
1678 strcpy(cur->varstr, str);
1679 goto free_and_exp;
1680 }
1681 } else {
1682 /* max_len == 0 signifies "malloced" var, which we can
1683 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001684 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001685 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001686 cur->max_len = 0;
1687 goto set_str_and_exp;
1688 }
1689
Denys Vlasenko295fef82009-06-03 12:47:26 +02001690 /* Not found - create new variable struct */
1691 cur = xzalloc(sizeof(*cur));
1692#if ENABLE_HUSH_LOCAL
1693 cur->func_nest_level = local_lvl;
1694#endif
1695 cur->next = *var_pp;
1696 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001697
1698 set_str_and_exp:
1699 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001700#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001701 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001702#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001703 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001704 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001705 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001706 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1707 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001708 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001709 if (flg_export == -1) {
1710 cur->flg_export = 0;
1711 /* unsetenv was already done */
1712 } else {
1713 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1714 return putenv(cur->varstr);
1715 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001716 }
1717 return 0;
1718}
1719
Denys Vlasenko6db47842009-09-05 20:15:17 +02001720/* Used at startup and after each cd */
1721static void set_pwd_var(int exp)
1722{
1723 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1724 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1725}
1726
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001727static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001728{
1729 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001730 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001731
1732 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001733 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001734 var_pp = &G.top_var;
1735 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001736 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1737 if (cur->flg_read_only) {
1738 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001739 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001740 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001741 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001742 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1743 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001744 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1745 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001746 if (!cur->max_len)
1747 free(cur->varstr);
1748 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001749 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001750 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001751 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001752 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001753 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001754}
1755
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001756static int unset_local_var(const char *name)
1757{
1758 return unset_local_var_len(name, strlen(name));
1759}
1760
1761static void unset_vars(char **strings)
1762{
1763 char **v;
1764
1765 if (!strings)
1766 return;
1767 v = strings;
1768 while (*v) {
1769 const char *eq = strchrnul(*v, '=');
1770 unset_local_var_len(*v, (int)(eq - *v));
1771 v++;
1772 }
1773 free(strings);
1774}
1775
Denys Vlasenko03dad222010-01-12 23:29:57 +01001776static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001777{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001778 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001779 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001780}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001781
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001782
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001783/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001784 * Helpers for "var1=val1 var2=val2 cmd" feature
1785 */
1786static void add_vars(struct variable *var)
1787{
1788 struct variable *next;
1789
1790 while (var) {
1791 next = var->next;
1792 var->next = G.top_var;
1793 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001794 if (var->flg_export) {
1795 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001796 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001797 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001798 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001799 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001800 var = next;
1801 }
1802}
1803
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001804static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001805{
1806 char **s;
1807 struct variable *old = NULL;
1808
1809 if (!strings)
1810 return old;
1811 s = strings;
1812 while (*s) {
1813 struct variable *var_p;
1814 struct variable **var_pp;
1815 char *eq;
1816
1817 eq = strchr(*s, '=');
1818 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001819 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001820 if (var_pp) {
1821 /* Remove variable from global linked list */
1822 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001823 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001824 *var_pp = var_p->next;
1825 /* Add it to returned list */
1826 var_p->next = old;
1827 old = var_p;
1828 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001829 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001830 }
1831 s++;
1832 }
1833 return old;
1834}
1835
1836
1837/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001838 * in_str support
1839 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001840static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001841{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001842 int ch = *i->p;
1843 if (ch != '\0') {
1844 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001845 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001846 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001847 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001848}
1849
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001850static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001851{
1852 return *i->p;
1853}
1854
1855#if ENABLE_HUSH_INTERACTIVE
1856
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001857static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001858{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001859 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001860 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001861 if (G.PS1 == NULL)
1862 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001863 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001864 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001865 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001866 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001867 if (G.PS2 == NULL)
1868 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001869}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001870
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001871static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001872{
1873 const char *prompt_str;
1874 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001875 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1876 /* Set up the prompt */
1877 if (promptmode == 0) { /* PS1 */
1878 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001879 /* bash uses $PWD value, even if it is set by user.
1880 * It uses current dir only if PWD is unset.
1881 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001882 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001883 prompt_str = G.PS1;
1884 } else
1885 prompt_str = G.PS2;
1886 } else
1887 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001888 debug_printf("result '%s'\n", prompt_str);
1889 return prompt_str;
1890}
1891
1892static void get_user_input(struct in_str *i)
1893{
1894 int r;
1895 const char *prompt_str;
1896
1897 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001898# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001899 /* Enable command line editing only while a command line
1900 * is actually being read */
1901 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001902 G.flag_SIGINT = 0;
1903 /* buglet: SIGINT will not make new prompt to appear _at once_,
1904 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001905 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001906 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001907 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001908 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001909 i->eof_flag = (r < 0);
1910 if (i->eof_flag) { /* EOF/error detected */
1911 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1912 G.user_input_buf[1] = '\0';
1913 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001914# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001915 do {
1916 G.flag_SIGINT = 0;
1917 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001918 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001919 G.user_input_buf[0] = r = fgetc(i->file);
1920 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001921//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001922 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001923 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001924# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001925 i->p = G.user_input_buf;
1926}
1927
1928#endif /* INTERACTIVE */
1929
1930/* This is the magic location that prints prompts
1931 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001932static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001933{
1934 int ch;
1935
1936 /* If there is data waiting, eat it up */
1937 if (i->p && *i->p) {
1938#if ENABLE_HUSH_INTERACTIVE
1939 take_cached:
1940#endif
1941 ch = *i->p++;
1942 if (i->eof_flag && !*i->p)
1943 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001944 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001945 } else {
1946 /* need to double check i->file because we might be doing something
1947 * more complicated by now, like sourcing or substituting. */
1948#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001949 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001950 do {
1951 get_user_input(i);
1952 } while (!*i->p); /* need non-empty line */
1953 i->promptmode = 1; /* PS2 */
1954 i->promptme = 0;
1955 goto take_cached;
1956 }
1957#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001958 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001959 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001960 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001961#if ENABLE_HUSH_INTERACTIVE
1962 if (ch == '\n')
1963 i->promptme = 1;
1964#endif
1965 return ch;
1966}
1967
Denis Vlasenko913a2012009-04-05 22:17:04 +00001968/* All callers guarantee this routine will never
1969 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001970 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001971static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001972{
1973 int ch;
1974 if (i->p && *i->p) {
1975 if (i->eof_flag && !i->p[1])
1976 return EOF;
1977 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001978 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001979 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001980 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001981 i->eof_flag = (ch == EOF);
1982 i->peek_buf[0] = ch;
1983 i->peek_buf[1] = '\0';
1984 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001985 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001986 return ch;
1987}
1988
1989static void setup_file_in_str(struct in_str *i, FILE *f)
1990{
1991 i->peek = file_peek;
1992 i->get = file_get;
1993#if ENABLE_HUSH_INTERACTIVE
1994 i->promptme = 1;
1995 i->promptmode = 0; /* PS1 */
1996#endif
1997 i->file = f;
1998 i->p = NULL;
1999}
2000
2001static void setup_string_in_str(struct in_str *i, const char *s)
2002{
2003 i->peek = static_peek;
2004 i->get = static_get;
2005#if ENABLE_HUSH_INTERACTIVE
2006 i->promptme = 1;
2007 i->promptmode = 0; /* PS1 */
2008#endif
2009 i->p = s;
2010 i->eof_flag = 0;
2011}
2012
2013
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002014/*
2015 * o_string support
2016 */
2017#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00002018
Denis Vlasenko0b677d82009-04-10 13:49:10 +00002019static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002020{
2021 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02002022 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002023 if (o->data)
2024 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002025}
2026
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002027static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002028{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002029 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002030 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002031}
2032
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002033static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2034{
2035 free(o->data);
2036}
2037
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002038static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002039{
2040 if (o->length + len > o->maxlen) {
2041 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2042 o->data = xrealloc(o->data, 1 + o->maxlen);
2043 }
2044}
2045
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002046static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002047{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002048 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2049 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002050 o->data[o->length] = ch;
2051 o->length++;
2052 o->data[o->length] = '\0';
2053}
2054
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002055static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002056{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002057 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002058 memcpy(&o->data[o->length], str, len);
2059 o->length += len;
2060 o->data[o->length] = '\0';
2061}
2062
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002063static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002064{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002065 o_addblock(o, str, strlen(str));
2066}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002067
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002068#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002069static void nommu_addchr(o_string *o, int ch)
2070{
2071 if (o)
2072 o_addchr(o, ch);
2073}
2074#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002075# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002076#endif
2077
2078static void o_addstr_with_NUL(o_string *o, const char *str)
2079{
2080 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002081}
2082
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002083/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002084 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002085 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2086 * Apparently, on unquoted $v bash still does globbing
2087 * ("v='*.txt'; echo $v" prints all .txt files),
2088 * but NOT brace expansion! Thus, there should be TWO independent
2089 * quoting mechanisms on $v expansion side: one protects
2090 * $v from brace expansion, and other additionally protects "$v" against globbing.
2091 * We have only second one.
2092 */
2093
Denys Vlasenko9e800222010-10-03 14:28:04 +02002094#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002095# define MAYBE_BRACES "{}"
2096#else
2097# define MAYBE_BRACES ""
2098#endif
2099
Eric Andersen25f27032001-04-26 23:22:31 +00002100/* My analysis of quoting semantics tells me that state information
2101 * is associated with a destination, not a source.
2102 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002103static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002104{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002105 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002106 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002107 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002108 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002109 o_grow_by(o, sz);
2110 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002111 o->data[o->length] = '\\';
2112 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002113 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002114 o->data[o->length] = ch;
2115 o->length++;
2116 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002117}
2118
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002119static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002120{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002121 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002122 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2123 && strchr("*?[\\" MAYBE_BRACES, ch)
2124 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002125 sz++;
2126 o->data[o->length] = '\\';
2127 o->length++;
2128 }
2129 o_grow_by(o, sz);
2130 o->data[o->length] = ch;
2131 o->length++;
2132 o->data[o->length] = '\0';
2133}
2134
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002135static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002136{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002137 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002138 char ch;
2139 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002140 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002141 if (ordinary_cnt > len) /* paranoia */
2142 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002143 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002144 if (ordinary_cnt == len)
2145 return;
2146 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002147 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002148
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002149 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002150 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002151 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002152 sz++;
2153 o->data[o->length] = '\\';
2154 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002155 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002156 o_grow_by(o, sz);
2157 o->data[o->length] = ch;
2158 o->length++;
2159 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002160 }
2161}
2162
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002163static void o_addQblock(o_string *o, const char *str, int len)
2164{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002165 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002166 o_addblock(o, str, len);
2167 return;
2168 }
2169 o_addqblock(o, str, len);
2170}
2171
Denys Vlasenko38292b62010-09-05 14:49:40 +02002172static void o_addQstr(o_string *o, const char *str)
2173{
2174 o_addQblock(o, str, strlen(str));
2175}
2176
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002177/* A special kind of o_string for $VAR and `cmd` expansion.
2178 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002179 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002180 * list[i] contains an INDEX (int!) into this string data.
2181 * It means that if list[] needs to grow, data needs to be moved higher up
2182 * but list[i]'s need not be modified.
2183 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002184 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002185 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2186 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002187#if DEBUG_EXPAND || DEBUG_GLOB
2188static void debug_print_list(const char *prefix, o_string *o, int n)
2189{
2190 char **list = (char**)o->data;
2191 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2192 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002193
2194 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002195 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 +02002196 prefix, list, n, string_start, o->length, o->maxlen,
2197 !!(o->o_expflags & EXP_FLAG_GLOB),
2198 o->has_quoted_part,
2199 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002200 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002201 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002202 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2203 o->data + (int)(uintptr_t)list[i] + string_start,
2204 o->data + (int)(uintptr_t)list[i] + string_start);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002205 i++;
2206 }
2207 if (n) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002208 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002209 indent();
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002210 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002211 }
2212}
2213#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002214# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002215#endif
2216
2217/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2218 * in list[n] so that it points past last stored byte so far.
2219 * It returns n+1. */
2220static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002221{
2222 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002223 int string_start;
2224 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002225
2226 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002227 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2228 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002229 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002230 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002231 /* list[n] points to string_start, make space for 16 more pointers */
2232 o->maxlen += 0x10 * sizeof(list[0]);
2233 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002234 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002235 memmove(list + n + 0x10, list + n, string_len);
2236 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002237 } else {
2238 debug_printf_list("list[%d]=%d string_start=%d\n",
2239 n, string_len, string_start);
2240 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002241 } else {
2242 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002243 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2244 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002245 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2246 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002247 o->has_empty_slot = 0;
2248 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002249 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002250 return n + 1;
2251}
2252
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002253/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002254static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002255{
2256 char **list = (char**)o->data;
2257 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2258
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002259 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002260}
2261
Denys Vlasenko9e800222010-10-03 14:28:04 +02002262#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002263/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2264 * first, it processes even {a} (no commas), second,
2265 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002266 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002267 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002268
2269/* Helper */
2270static int glob_needed(const char *s)
2271{
2272 while (*s) {
2273 if (*s == '\\') {
2274 if (!s[1])
2275 return 0;
2276 s += 2;
2277 continue;
2278 }
2279 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2280 return 1;
2281 s++;
2282 }
2283 return 0;
2284}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002285/* Return pointer to next closing brace or to comma */
2286static const char *next_brace_sub(const char *cp)
2287{
2288 unsigned depth = 0;
2289 cp++;
2290 while (*cp != '\0') {
2291 if (*cp == '\\') {
2292 if (*++cp == '\0')
2293 break;
2294 cp++;
2295 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002296 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002297 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002298 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002299 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002300 depth++;
2301 }
2302
2303 return *cp != '\0' ? cp : NULL;
2304}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002305/* Recursive brace globber. Note: may garble pattern[]. */
2306static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002307{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002308 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002309 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002310 const char *next;
2311 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002312 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002313 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002314
2315 debug_printf_glob("glob_brace('%s')\n", pattern);
2316
2317 begin = pattern;
2318 while (1) {
2319 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002320 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002321 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002322 /* Find the first sub-pattern and at the same time
2323 * find the rest after the closing brace */
2324 next = next_brace_sub(begin);
2325 if (next == NULL) {
2326 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002327 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002328 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002329 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002330 /* "{abc}" with no commas - illegal
2331 * brace expr, disregard and skip it */
2332 begin = next + 1;
2333 continue;
2334 }
2335 break;
2336 }
2337 if (*begin == '\\' && begin[1] != '\0')
2338 begin++;
2339 begin++;
2340 }
2341 debug_printf_glob("begin:%s\n", begin);
2342 debug_printf_glob("next:%s\n", next);
2343
2344 /* Now find the end of the whole brace expression */
2345 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002346 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002347 rest = next_brace_sub(rest);
2348 if (rest == NULL) {
2349 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002350 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002351 }
2352 debug_printf_glob("rest:%s\n", rest);
2353 }
2354 rest_len = strlen(++rest) + 1;
2355
2356 /* We are sure the brace expression is well-formed */
2357
2358 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002359 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002360
2361 /* We have a brace expression. BEGIN points to the opening {,
2362 * NEXT points past the terminator of the first element, and REST
2363 * points past the final }. We will accumulate result names from
2364 * recursive runs for each brace alternative in the buffer using
2365 * GLOB_APPEND. */
2366
2367 p = begin + 1;
2368 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002369 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002370 memcpy(
2371 mempcpy(
2372 mempcpy(new_pattern_buf,
2373 /* We know the prefix for all sub-patterns */
2374 pattern, begin - pattern),
2375 p, next - p),
2376 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002377
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002378 /* Note: glob_brace() may garble new_pattern_buf[].
2379 * That's why we re-copy prefix every time (1st memcpy above).
2380 */
2381 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002382 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002383 /* We saw the last entry */
2384 break;
2385 }
2386 p = next + 1;
2387 next = next_brace_sub(next);
2388 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002389 free(new_pattern_buf);
2390 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002391
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002392 simple_glob:
2393 {
2394 int gr;
2395 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002396
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002397 memset(&globdata, 0, sizeof(globdata));
2398 gr = glob(pattern, 0, NULL, &globdata);
2399 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2400 if (gr != 0) {
2401 if (gr == GLOB_NOMATCH) {
2402 globfree(&globdata);
2403 /* NB: garbles parameter */
2404 unbackslash(pattern);
2405 o_addstr_with_NUL(o, pattern);
2406 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2407 return o_save_ptr_helper(o, n);
2408 }
2409 if (gr == GLOB_NOSPACE)
2410 bb_error_msg_and_die(bb_msg_memory_exhausted);
2411 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2412 * but we didn't specify it. Paranoia again. */
2413 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2414 }
2415 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2416 char **argv = globdata.gl_pathv;
2417 while (1) {
2418 o_addstr_with_NUL(o, *argv);
2419 n = o_save_ptr_helper(o, n);
2420 argv++;
2421 if (!*argv)
2422 break;
2423 }
2424 }
2425 globfree(&globdata);
2426 }
2427 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002428}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002429/* Performs globbing on last list[],
2430 * saving each result as a new list[].
2431 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002432static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002433{
2434 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002435
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002436 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002437 if (!o->data)
2438 return o_save_ptr_helper(o, n);
2439 pattern = o->data + o_get_last_ptr(o, n);
2440 debug_printf_glob("glob pattern '%s'\n", pattern);
2441 if (!glob_needed(pattern)) {
2442 /* unbackslash last string in o in place, fix length */
2443 o->length = unbackslash(pattern) - o->data;
2444 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2445 return o_save_ptr_helper(o, n);
2446 }
2447
2448 copy = xstrdup(pattern);
2449 /* "forget" pattern in o */
2450 o->length = pattern - o->data;
2451 n = glob_brace(copy, o, n);
2452 free(copy);
2453 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002454 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002455 return n;
2456}
2457
Denys Vlasenko238081f2010-10-03 14:26:26 +02002458#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002459
2460/* Helper */
2461static int glob_needed(const char *s)
2462{
2463 while (*s) {
2464 if (*s == '\\') {
2465 if (!s[1])
2466 return 0;
2467 s += 2;
2468 continue;
2469 }
2470 if (*s == '*' || *s == '[' || *s == '?')
2471 return 1;
2472 s++;
2473 }
2474 return 0;
2475}
2476/* Performs globbing on last list[],
2477 * saving each result as a new list[].
2478 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002479static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002480{
2481 glob_t globdata;
2482 int gr;
2483 char *pattern;
2484
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002485 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002486 if (!o->data)
2487 return o_save_ptr_helper(o, n);
2488 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002489 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002490 if (!glob_needed(pattern)) {
2491 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002492 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002493 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002494 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002495 return o_save_ptr_helper(o, n);
2496 }
2497
2498 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002499 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2500 * If we glob "*.\*" and don't find anything, we need
2501 * to fall back to using literal "*.*", but GLOB_NOCHECK
2502 * will return "*.\*"!
2503 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002504 gr = glob(pattern, 0, NULL, &globdata);
2505 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002506 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002507 if (gr == GLOB_NOMATCH) {
2508 globfree(&globdata);
2509 goto literal;
2510 }
2511 if (gr == GLOB_NOSPACE)
2512 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002513 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2514 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002515 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002516 }
2517 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2518 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002519 /* "forget" pattern in o */
2520 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002521 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002522 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002523 n = o_save_ptr_helper(o, n);
2524 argv++;
2525 if (!*argv)
2526 break;
2527 }
2528 }
2529 globfree(&globdata);
2530 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002531 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002532 return n;
2533}
2534
Denys Vlasenko238081f2010-10-03 14:26:26 +02002535#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002536
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002537/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002538 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002539static int o_save_ptr(o_string *o, int n)
2540{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002541 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002542 /* If o->has_empty_slot, list[n] was already globbed
2543 * (if it was requested back then when it was filled)
2544 * so don't do that again! */
2545 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002546 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002547 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002548 return o_save_ptr_helper(o, n);
2549}
2550
2551/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002552static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002553{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002554 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002555 int string_start;
2556
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002557 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2558 if (DEBUG_EXPAND)
2559 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002560 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002561 list = (char**)o->data;
2562 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2563 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002564 while (n) {
2565 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002566 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002567 }
2568 return list;
2569}
2570
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002571static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002572
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002573/* Returns pi->next - next pipe in the list */
2574static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002575{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002576 struct pipe *next;
2577 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002578
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002579 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002580 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002581 struct command *command;
2582 struct redir_struct *r, *rnext;
2583
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002584 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002585 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002586 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002587 if (DEBUG_CLEAN) {
2588 int a;
2589 char **p;
2590 for (a = 0, p = command->argv; *p; a++, p++) {
2591 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2592 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002593 }
2594 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002595 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002596 }
2597 /* not "else if": on syntax error, we may have both! */
2598 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002599 debug_printf_clean(" begin group (cmd_type:%d)\n",
2600 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002601 free_pipe_list(command->group);
2602 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002603 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002604 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002605 /* else is crucial here.
2606 * If group != NULL, child_func is meaningless */
2607#if ENABLE_HUSH_FUNCTIONS
2608 else if (command->child_func) {
2609 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2610 command->child_func->parent_cmd = NULL;
2611 }
2612#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002613#if !BB_MMU
2614 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002615 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002616#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002617 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002618 debug_printf_clean(" redirect %d%s",
2619 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002620 /* guard against the case >$FOO, where foo is unset or blank */
2621 if (r->rd_filename) {
2622 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2623 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002624 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002625 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002626 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002627 rnext = r->next;
2628 free(r);
2629 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002630 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002631 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002632 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002633 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002634#if ENABLE_HUSH_JOB
2635 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002636 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002637#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002638
2639 next = pi->next;
2640 free(pi);
2641 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002642}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002643
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002644static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002645{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002646 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002647#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002648 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002649#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002650 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002651 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002652 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002653}
2654
2655
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002656/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002657
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002658#ifndef debug_print_tree
2659static void debug_print_tree(struct pipe *pi, int lvl)
2660{
2661 static const char *const PIPE[] = {
2662 [PIPE_SEQ] = "SEQ",
2663 [PIPE_AND] = "AND",
2664 [PIPE_OR ] = "OR" ,
2665 [PIPE_BG ] = "BG" ,
2666 };
2667 static const char *RES[] = {
2668 [RES_NONE ] = "NONE" ,
2669# if ENABLE_HUSH_IF
2670 [RES_IF ] = "IF" ,
2671 [RES_THEN ] = "THEN" ,
2672 [RES_ELIF ] = "ELIF" ,
2673 [RES_ELSE ] = "ELSE" ,
2674 [RES_FI ] = "FI" ,
2675# endif
2676# if ENABLE_HUSH_LOOPS
2677 [RES_FOR ] = "FOR" ,
2678 [RES_WHILE] = "WHILE",
2679 [RES_UNTIL] = "UNTIL",
2680 [RES_DO ] = "DO" ,
2681 [RES_DONE ] = "DONE" ,
2682# endif
2683# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2684 [RES_IN ] = "IN" ,
2685# endif
2686# if ENABLE_HUSH_CASE
2687 [RES_CASE ] = "CASE" ,
2688 [RES_CASE_IN ] = "CASE_IN" ,
2689 [RES_MATCH] = "MATCH",
2690 [RES_CASE_BODY] = "CASE_BODY",
2691 [RES_ESAC ] = "ESAC" ,
2692# endif
2693 [RES_XXXX ] = "XXXX" ,
2694 [RES_SNTX ] = "SNTX" ,
2695 };
2696 static const char *const CMDTYPE[] = {
2697 "{}",
2698 "()",
2699 "[noglob]",
2700# if ENABLE_HUSH_FUNCTIONS
2701 "func()",
2702# endif
2703 };
2704
2705 int pin, prn;
2706
2707 pin = 0;
2708 while (pi) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002709 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002710 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2711 prn = 0;
2712 while (prn < pi->num_cmds) {
2713 struct command *command = &pi->cmds[prn];
2714 char **argv = command->argv;
2715
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002716 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002717 lvl*2, "", prn,
2718 command->assignment_cnt);
2719 if (command->group) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002720 fdprintf(2, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002721 CMDTYPE[command->cmd_type],
2722 argv
2723# if !BB_MMU
2724 , " group_as_string:", command->group_as_string
2725# else
2726 , "", ""
2727# endif
2728 );
2729 debug_print_tree(command->group, lvl+1);
2730 prn++;
2731 continue;
2732 }
2733 if (argv) while (*argv) {
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002734 fdprintf(2, " '%s'", *argv);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002735 argv++;
2736 }
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01002737 fdprintf(2, "\n");
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002738 prn++;
2739 }
2740 pi = pi->next;
2741 pin++;
2742 }
2743}
2744#endif /* debug_print_tree */
2745
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002746static struct pipe *new_pipe(void)
2747{
Eric Andersen25f27032001-04-26 23:22:31 +00002748 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002749 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002750 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002751 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002752 return pi;
2753}
2754
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002755/* Command (member of a pipe) is complete, or we start a new pipe
2756 * if ctx->command is NULL.
2757 * No errors possible here.
2758 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002759static int done_command(struct parse_context *ctx)
2760{
2761 /* The command is really already in the pipe structure, so
2762 * advance the pipe counter and make a new, null command. */
2763 struct pipe *pi = ctx->pipe;
2764 struct command *command = ctx->command;
2765
2766 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002767 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002768 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002769 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002770 }
2771 pi->num_cmds++;
2772 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002773 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002774 } else {
2775 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2776 }
2777
2778 /* Only real trickiness here is that the uncommitted
2779 * command structure is not counted in pi->num_cmds. */
2780 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002781 ctx->command = command = &pi->cmds[pi->num_cmds];
2782 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002783 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002784 return pi->num_cmds; /* used only for 0/nonzero check */
2785}
2786
2787static void done_pipe(struct parse_context *ctx, pipe_style type)
2788{
2789 int not_null;
2790
2791 debug_printf_parse("done_pipe entered, followup %d\n", type);
2792 /* Close previous command */
2793 not_null = done_command(ctx);
2794 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002795#if HAS_KEYWORDS
2796 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2797 ctx->ctx_inverted = 0;
2798 ctx->pipe->res_word = ctx->ctx_res_w;
2799#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002800
2801 /* Without this check, even just <enter> on command line generates
2802 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002803 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002804 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002805#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002806 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002807#endif
2808#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002809 || ctx->ctx_res_w == RES_DONE
2810 || ctx->ctx_res_w == RES_FOR
2811 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002812#endif
2813#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002814 || ctx->ctx_res_w == RES_ESAC
2815#endif
2816 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002817 struct pipe *new_p;
2818 debug_printf_parse("done_pipe: adding new pipe: "
2819 "not_null:%d ctx->ctx_res_w:%d\n",
2820 not_null, ctx->ctx_res_w);
2821 new_p = new_pipe();
2822 ctx->pipe->next = new_p;
2823 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002824 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002825 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002826 * This is used to control execution.
2827 * RES_FOR and RES_IN are NOT sticky (needed to support
2828 * cases where variable or value happens to match a keyword):
2829 */
2830#if ENABLE_HUSH_LOOPS
2831 if (ctx->ctx_res_w == RES_FOR
2832 || ctx->ctx_res_w == RES_IN)
2833 ctx->ctx_res_w = RES_NONE;
2834#endif
2835#if ENABLE_HUSH_CASE
2836 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002837 ctx->ctx_res_w = RES_CASE_BODY;
2838 if (ctx->ctx_res_w == RES_CASE)
2839 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002840#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002841 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002842 /* Create the memory for command, roughly:
2843 * ctx->pipe->cmds = new struct command;
2844 * ctx->command = &ctx->pipe->cmds[0];
2845 */
2846 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002847 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002848 }
2849 debug_printf_parse("done_pipe return\n");
2850}
2851
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002852static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002853{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002854 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002855 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002856 /* Create the memory for command, roughly:
2857 * ctx->pipe->cmds = new struct command;
2858 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002859 */
2860 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002861}
2862
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002863/* If a reserved word is found and processed, parse context is modified
2864 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002865 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002866#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002867struct reserved_combo {
2868 char literal[6];
2869 unsigned char res;
2870 unsigned char assignment_flag;
2871 int flag;
2872};
2873enum {
2874 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002875# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002876 FLAG_IF = (1 << RES_IF ),
2877 FLAG_THEN = (1 << RES_THEN ),
2878 FLAG_ELIF = (1 << RES_ELIF ),
2879 FLAG_ELSE = (1 << RES_ELSE ),
2880 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002881# endif
2882# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002883 FLAG_FOR = (1 << RES_FOR ),
2884 FLAG_WHILE = (1 << RES_WHILE),
2885 FLAG_UNTIL = (1 << RES_UNTIL),
2886 FLAG_DO = (1 << RES_DO ),
2887 FLAG_DONE = (1 << RES_DONE ),
2888 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002889# endif
2890# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002891 FLAG_MATCH = (1 << RES_MATCH),
2892 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002893# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002894 FLAG_START = (1 << RES_XXXX ),
2895};
2896
2897static const struct reserved_combo* match_reserved_word(o_string *word)
2898{
Eric Andersen25f27032001-04-26 23:22:31 +00002899 /* Mostly a list of accepted follow-up reserved words.
2900 * FLAG_END means we are done with the sequence, and are ready
2901 * to turn the compound list into a command.
2902 * FLAG_START means the word must start a new compound list.
2903 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002904 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002905# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002906 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2907 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2908 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2909 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2910 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2911 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002912# endif
2913# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002914 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2915 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2916 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2917 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2918 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2919 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002920# endif
2921# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002922 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2923 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002924# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002925 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002926 const struct reserved_combo *r;
2927
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02002928 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002929 if (strcmp(word->data, r->literal) == 0)
2930 return r;
2931 }
2932 return NULL;
2933}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002934/* Return 0: not a keyword, 1: keyword
2935 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002936static int reserved_word(o_string *word, struct parse_context *ctx)
2937{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002938# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002939 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002940 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002941 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002942# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002943 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002944
Denys Vlasenko38292b62010-09-05 14:49:40 +02002945 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002946 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002947 r = match_reserved_word(word);
2948 if (!r)
2949 return 0;
2950
2951 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002952# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002953 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2954 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002955 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002956 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002957# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002958 if (r->flag == 0) { /* '!' */
2959 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002960 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002961 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002962 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002963 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002964 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002965 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002966 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002967 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002968
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002969 old = xmalloc(sizeof(*old));
2970 debug_printf_parse("push stack %p\n", old);
2971 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002972 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002973 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002974 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002975 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002976 ctx->ctx_res_w = RES_SNTX;
2977 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002978 } else {
2979 /* "{...} fi" is ok. "{...} if" is not
2980 * Example:
2981 * if { echo foo; } then { echo bar; } fi */
2982 if (ctx->command->group)
2983 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002984 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002985
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002986 ctx->ctx_res_w = r->res;
2987 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002988 word->o_assignment = r->assignment_flag;
2989
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002990 if (ctx->old_flag & FLAG_END) {
2991 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002992
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002993 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002994 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002995 old = ctx->stack;
2996 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002997 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002998# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002999 o_addstr(&old->as_string, ctx->as_string.data);
3000 o_free_unsafe(&ctx->as_string);
3001 old->command->group_as_string = xstrdup(old->as_string.data);
3002 debug_printf_parse("pop, remembering as:'%s'\n",
3003 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003004# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003005 *ctx = *old; /* physical copy */
3006 free(old);
3007 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003008 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003009}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003010#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00003011
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003012/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003013 * Normal return is 0. Syntax errors return 1.
3014 * Note: on return, word is reset, but not o_free'd!
3015 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003016static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003017{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003018 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003019
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003020 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02003021 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003022 debug_printf_parse("done_word return 0: true null, ignored\n");
3023 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003024 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003025
Eric Andersen25f27032001-04-26 23:22:31 +00003026 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003027 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3028 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003029 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3030 * "2.7 Redirection
3031 * ...the word that follows the redirection operator
3032 * shall be subjected to tilde expansion, parameter expansion,
3033 * command substitution, arithmetic expansion, and quote
3034 * removal. Pathname expansion shall not be performed
3035 * on the word by a non-interactive shell; an interactive
3036 * shell may perform it, but shall do so only when
3037 * the expansion would result in one word."
3038 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003039 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003040 /* Cater for >\file case:
3041 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3042 * Same with heredocs:
3043 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3044 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003045 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3046 unbackslash(ctx->pending_redirect->rd_filename);
3047 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003048 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003049 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3050 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003051 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003052 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003053 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003054 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003055 /* If this word wasn't an assignment, next ones definitely
3056 * can't be assignments. Even if they look like ones. */
3057 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3058 && word->o_assignment != WORD_IS_KEYWORD
3059 ) {
3060 word->o_assignment = NOT_ASSIGNMENT;
3061 } else {
3062 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3063 command->assignment_cnt++;
3064 word->o_assignment = MAYBE_ASSIGNMENT;
3065 }
3066
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003067#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003068# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003069 if (ctx->ctx_dsemicolon
3070 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3071 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003072 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003073 /* ctx->ctx_res_w = RES_MATCH; */
3074 ctx->ctx_dsemicolon = 0;
3075 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003076# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003077 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003078# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003079 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3080 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003081# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003082# if ENABLE_HUSH_CASE
3083 && ctx->ctx_res_w != RES_CASE
3084# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003085 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003086 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003087 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003088 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003089 debug_printf_parse("done_word return %d\n",
3090 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003091 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003092 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003093# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003094 if (strcmp(word->data, "[[") == 0) {
3095 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3096 }
3097 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003098# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003099 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003100#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003101 if (command->group) {
3102 /* "{ echo foo; } echo bar" - bad */
3103 syntax_error_at(word->data);
3104 debug_printf_parse("done_word return 1: syntax error, "
3105 "groups and arglists don't mix\n");
3106 return 1;
3107 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02003108 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003109 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3110 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003111 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003112 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003113 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003114 char *p = word->data;
3115 while (p[0] == SPECIAL_VAR_SYMBOL
3116 && (p[1] & 0x7f) == '@'
3117 && p[2] == SPECIAL_VAR_SYMBOL
3118 ) {
3119 p += 3;
3120 }
3121 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003122 /* saw no "$@", or not only "$@" but some
3123 * real text is there too */
3124 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003125 * e.g. "", $empty"" etc to not disappear */
3126 o_addchr(word, SPECIAL_VAR_SYMBOL);
3127 o_addchr(word, SPECIAL_VAR_SYMBOL);
3128 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003129 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003130 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003131 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003132 }
Eric Andersen25f27032001-04-26 23:22:31 +00003133
Denis Vlasenko06810332007-05-21 23:30:54 +00003134#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003135 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003136 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003137 || !is_well_formed_var_name(command->argv[0], '\0')
3138 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003139 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003140 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003141 return 1;
3142 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003143 /* Force FOR to have just one word (variable name) */
3144 /* NB: basically, this makes hush see "for v in ..."
3145 * syntax as if it is "for v; in ...". FOR and IN become
3146 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003147 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003148 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003149#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003150#if ENABLE_HUSH_CASE
3151 /* Force CASE to have just one word */
3152 if (ctx->ctx_res_w == RES_CASE) {
3153 done_pipe(ctx, PIPE_SEQ);
3154 }
3155#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003156
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003157 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003158
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003159 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003160 return 0;
3161}
3162
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003163
3164/* Peek ahead in the input to find out if we have a "&n" construct,
3165 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003166 * Return:
3167 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3168 * REDIRFD_SYNTAX_ERR if syntax error,
3169 * REDIRFD_TO_FILE if no & was seen,
3170 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003171 */
3172#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003173#define parse_redir_right_fd(as_string, input) \
3174 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003175#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003176static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003177{
3178 int ch, d, ok;
3179
3180 ch = i_peek(input);
3181 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003182 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003183
3184 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003185 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003186 ch = i_peek(input);
3187 if (ch == '-') {
3188 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003189 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003190 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003191 }
3192 d = 0;
3193 ok = 0;
3194 while (ch != EOF && isdigit(ch)) {
3195 d = d*10 + (ch-'0');
3196 ok = 1;
3197 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003198 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003199 ch = i_peek(input);
3200 }
3201 if (ok) return d;
3202
3203//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3204
3205 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003206 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003207}
3208
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003209/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003210 */
3211static int parse_redirect(struct parse_context *ctx,
3212 int fd,
3213 redir_type style,
3214 struct in_str *input)
3215{
3216 struct command *command = ctx->command;
3217 struct redir_struct *redir;
3218 struct redir_struct **redirp;
3219 int dup_num;
3220
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003221 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003222 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003223 /* Check for a '>&1' type redirect */
3224 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3225 if (dup_num == REDIRFD_SYNTAX_ERR)
3226 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003227 } else {
3228 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003229 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003230 if (dup_num) { /* <<-... */
3231 ch = i_getch(input);
3232 nommu_addchr(&ctx->as_string, ch);
3233 ch = i_peek(input);
3234 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003235 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003236
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003237 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003238 int ch = i_peek(input);
3239 if (ch == '|') {
3240 /* >|FILE redirect ("clobbering" >).
3241 * Since we do not support "set -o noclobber" yet,
3242 * >| and > are the same for now. Just eat |.
3243 */
3244 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003245 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003246 }
3247 }
3248
3249 /* Create a new redir_struct and append it to the linked list */
3250 redirp = &command->redirects;
3251 while ((redir = *redirp) != NULL) {
3252 redirp = &(redir->next);
3253 }
3254 *redirp = redir = xzalloc(sizeof(*redir));
3255 /* redir->next = NULL; */
3256 /* redir->rd_filename = NULL; */
3257 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003258 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003259
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003260 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3261 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003262
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003263 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003264 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003265 /* Erik had a check here that the file descriptor in question
3266 * is legit; I postpone that to "run time"
3267 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003268 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3269 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003270 } else {
3271 /* Set ctx->pending_redirect, so we know what to do at the
3272 * end of the next parsed word. */
3273 ctx->pending_redirect = redir;
3274 }
3275 return 0;
3276}
3277
Eric Andersen25f27032001-04-26 23:22:31 +00003278/* If a redirect is immediately preceded by a number, that number is
3279 * supposed to tell which file descriptor to redirect. This routine
3280 * looks for such preceding numbers. In an ideal world this routine
3281 * needs to handle all the following classes of redirects...
3282 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3283 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3284 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3285 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003286 *
3287 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3288 * "2.7 Redirection
3289 * ... If n is quoted, the number shall not be recognized as part of
3290 * the redirection expression. For example:
3291 * echo \2>a
3292 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003293 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003294 *
3295 * A -1 return means no valid number was found,
3296 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003297 */
3298static int redirect_opt_num(o_string *o)
3299{
3300 int num;
3301
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003302 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003303 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003304 num = bb_strtou(o->data, NULL, 10);
3305 if (errno || num < 0)
3306 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003307 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003308 return num;
3309}
3310
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003311#if BB_MMU
3312#define fetch_till_str(as_string, input, word, skip_tabs) \
3313 fetch_till_str(input, word, skip_tabs)
3314#endif
3315static char *fetch_till_str(o_string *as_string,
3316 struct in_str *input,
3317 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003318 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003319{
3320 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003321 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003322 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003323 int ch;
3324
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003325 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003326 while (1) {
3327 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003328 if (ch != EOF)
3329 nommu_addchr(as_string, ch);
3330 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003331 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3332 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003333 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3334 heredoc.data[past_EOL] = '\0';
3335 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3336 return heredoc.data;
3337 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003338 while (ch == '\n') {
3339 o_addchr(&heredoc, ch);
3340 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003341 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003342 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003343 do {
3344 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003345 if (ch != EOF)
3346 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003347 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003348 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003349 }
3350 if (ch == EOF) {
3351 o_free_unsafe(&heredoc);
3352 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003353 }
3354 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003355 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003356 if (prev == '\\' && ch == '\\')
3357 /* Correctly handle foo\\<eol> (not a line cont.) */
3358 prev = 0; /* not \ */
3359 else
3360 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003361 }
3362}
3363
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003364/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3365 * and load them all. There should be exactly heredoc_cnt of them.
3366 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003367static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3368{
3369 struct pipe *pi = ctx->list_head;
3370
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003371 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003372 int i;
3373 struct command *cmd = pi->cmds;
3374
3375 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3376 pi->num_cmds,
3377 cmd->argv ? cmd->argv[0] : "NONE");
3378 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003379 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003380
3381 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3382 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003383 while (redir) {
3384 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003385 char *p;
3386
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003387 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003388 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003389 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003390 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003391 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003392 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003393 return 1;
3394 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003395 free(redir->rd_filename);
3396 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003397 heredoc_cnt--;
3398 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003399 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003400 }
3401 cmd++;
3402 }
3403 pi = pi->next;
3404 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003405#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003406 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003407 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003408 bb_error_msg_and_die("heredoc BUG 2");
3409#endif
3410 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003411}
3412
3413
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003414static int run_list(struct pipe *pi);
3415#if BB_MMU
3416#define parse_stream(pstring, input, end_trigger) \
3417 parse_stream(input, end_trigger)
3418#endif
3419static struct pipe *parse_stream(char **pstring,
3420 struct in_str *input,
3421 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003422
Eric Andersen25f27032001-04-26 23:22:31 +00003423
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003424#if !ENABLE_HUSH_FUNCTIONS
3425#define parse_group(dest, ctx, input, ch) \
3426 parse_group(ctx, input, ch)
3427#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003428static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003429 struct in_str *input, int ch)
3430{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003431 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003432 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003433 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003434 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003435 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003436 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003437
3438 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003439#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003440 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003441 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003442 if (done_word(dest, ctx))
3443 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003444 if (!command->argv)
3445 goto skip; /* (... */
3446 if (command->argv[1]) { /* word word ... (... */
3447 syntax_error_unexpected_ch('(');
3448 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003449 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003450 /* it is "word(..." or "word (..." */
3451 do
3452 ch = i_getch(input);
3453 while (ch == ' ' || ch == '\t');
3454 if (ch != ')') {
3455 syntax_error_unexpected_ch(ch);
3456 return 1;
3457 }
3458 nommu_addchr(&ctx->as_string, ch);
3459 do
3460 ch = i_getch(input);
3461 while (ch == ' ' || ch == '\t' || ch == '\n');
3462 if (ch != '{') {
3463 syntax_error_unexpected_ch(ch);
3464 return 1;
3465 }
3466 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003467 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003468 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003469 }
3470#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003471
3472#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003473 if (command->argv /* word [word]{... */
3474 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003475 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003476 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003477 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003478 debug_printf_parse("parse_group return 1: "
3479 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003480 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003481 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003482#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003483
3484#if ENABLE_HUSH_FUNCTIONS
3485 skip:
3486#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003487 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003488 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003489 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003490 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003491 } else {
3492 /* bash does not allow "{echo...", requires whitespace */
3493 ch = i_getch(input);
3494 if (ch != ' ' && ch != '\t' && ch != '\n') {
3495 syntax_error_unexpected_ch(ch);
3496 return 1;
3497 }
3498 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003499 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003500
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003501 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003502#if BB_MMU
3503# define as_string NULL
3504#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003505 char *as_string = NULL;
3506#endif
3507 pipe_list = parse_stream(&as_string, input, endch);
3508#if !BB_MMU
3509 if (as_string)
3510 o_addstr(&ctx->as_string, as_string);
3511#endif
3512 /* empty ()/{} or parse error? */
3513 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003514 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003515 if (!BB_MMU)
3516 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003517 debug_printf_parse("parse_group return 1: "
3518 "parse_stream returned %p\n", pipe_list);
3519 return 1;
3520 }
3521 command->group = pipe_list;
3522#if !BB_MMU
3523 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3524 command->group_as_string = as_string;
3525 debug_printf_parse("end of group, remembering as:'%s'\n",
3526 command->group_as_string);
3527#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003528#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003529 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003530 debug_printf_parse("parse_group return 0\n");
3531 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003532 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003533}
3534
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003535#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003536/* Subroutines for copying $(...) and `...` things */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003537static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003538/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003539static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003540{
3541 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003542 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003543 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003544 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003545 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003546 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003547 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003548 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003549 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003550 }
3551}
3552/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003553static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003554{
3555 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003556 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003557 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003558 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003559 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003560 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003561 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003562 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003563 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003564 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003565 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003566 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003567 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003568 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003569 add_till_backquote(dest, input, /*in_dquote:*/ 1);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003570 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003571 continue;
3572 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003573 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003574 }
3575}
3576/* Process `cmd` - copy contents until "`" is seen. Complicated by
3577 * \` quoting.
3578 * "Within the backquoted style of command substitution, backslash
3579 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3580 * The search for the matching backquote shall be satisfied by the first
3581 * backquote found without a preceding backslash; during this search,
3582 * if a non-escaped backquote is encountered within a shell comment,
3583 * a here-document, an embedded command substitution of the $(command)
3584 * form, or a quoted string, undefined results occur. A single-quoted
3585 * or double-quoted string that begins, but does not end, within the
3586 * "`...`" sequence produces undefined results."
3587 * Example Output
3588 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3589 */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003590static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003591{
3592 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003593 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003594 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003595 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003596 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003597 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3598 ch = i_getch(input);
3599 if (ch != '`'
3600 && ch != '$'
3601 && ch != '\\'
3602 && (!in_dquote || ch != '"')
3603 ) {
3604 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003605 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003606 }
3607 if (ch == EOF) {
3608 syntax_error_unterm_ch('`');
3609 /*xfunc_die(); - redundant */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003610 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003611 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003612 }
3613}
3614/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3615 * quoting and nested ()s.
3616 * "With the $(command) style of command substitution, all characters
3617 * following the open parenthesis to the matching closing parenthesis
3618 * constitute the command. Any valid shell script can be used for command,
3619 * except a script consisting solely of redirections which produces
3620 * unspecified results."
3621 * Example Output
3622 * echo $(echo '(TEST)' BEST) (TEST) BEST
3623 * echo $(echo 'TEST)' BEST) TEST) BEST
3624 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003625 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003626 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003627 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003628 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3629 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003630 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003631#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003632static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003633{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003634 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003635 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003636# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003637 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003638# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003639 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3640
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003641 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003642 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003643 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003644 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003645 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003646 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003647 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003648 if (!dbl)
3649 break;
3650 /* we look for closing )) of $((EXPR)) */
3651 if (i_peek(input) == end_ch) {
3652 i_getch(input); /* eat second ')' */
3653 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003654 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003655 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003656 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003657 if (ch == '(' || ch == '{') {
3658 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003659 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003660 o_addchr(dest, ch);
3661 continue;
3662 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003663 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003664 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003665 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003666 continue;
3667 }
3668 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003669 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003670 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003671 continue;
3672 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003673 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003674 add_till_backquote(dest, input, /*in_dquote:*/ 0);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003675 o_addchr(dest, ch);
3676 continue;
3677 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003678 if (ch == '\\') {
3679 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003680 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003681 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003682 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003683 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003684 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003685 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003686 continue;
3687 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003688 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003689 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003690}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003691#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003692
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003693/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003694#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003695#define parse_dollar(as_string, dest, input, quote_mask) \
3696 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003697#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003698#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003699static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003700 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003701 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003702{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003703 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003704
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003705 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003706 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003707 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003708 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003709 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003710 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003711 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003712 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003713 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003714 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003715 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003716 if (!isalnum(ch) && ch != '_')
3717 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003718 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003719 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003720 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003721 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003722 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003723 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003724 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003725 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003726 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003727 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003728 o_addchr(dest, ch | quote_mask);
3729 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003730 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003731 case '$': /* pid */
3732 case '!': /* last bg pid */
3733 case '?': /* last exit code */
3734 case '#': /* number of args */
3735 case '*': /* args */
3736 case '@': /* args */
3737 goto make_one_char_var;
3738 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003739 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3740
Denys Vlasenko74369502010-05-21 19:52:01 +02003741 ch = i_getch(input); /* eat '{' */
3742 nommu_addchr(as_string, ch);
3743
3744 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003745 /* It should be ${?}, or ${#var},
3746 * or even ${?+subst} - operator acting on a special variable,
3747 * or the beginning of variable name.
3748 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003749 if (ch == EOF
3750 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3751 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003752 bad_dollar_syntax:
3753 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003754 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02003755 return 1;
3756 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003757 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003758 ch |= quote_mask;
3759
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003760 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003761 * However, this regresses some of our testsuite cases
3762 * which check invalid constructs like ${%}.
3763 * Oh well... let's check that the var name part is fine... */
3764
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003765 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003766 unsigned pos;
3767
Denys Vlasenko74369502010-05-21 19:52:01 +02003768 o_addchr(dest, ch);
3769 debug_printf_parse(": '%c'\n", ch);
3770
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003771 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003772 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003773 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003774 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003775
Denys Vlasenko74369502010-05-21 19:52:01 +02003776 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003777 unsigned end_ch;
3778 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003779 /* handle parameter expansions
3780 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3781 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003782 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003783 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003784
3785 /* Eat everything until closing '}' (or ':') */
3786 end_ch = '}';
3787 if (ENABLE_HUSH_BASH_COMPAT
3788 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003789 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003790 ) {
3791 /* It's ${var:N[:M]} thing */
3792 end_ch = '}' * 0x100 + ':';
3793 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003794 if (ENABLE_HUSH_BASH_COMPAT
3795 && ch == '/'
3796 ) {
3797 /* It's ${var/[/]pattern[/repl]} thing */
3798 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3799 i_getch(input);
3800 nommu_addchr(as_string, '/');
3801 ch = '\\';
3802 }
3803 end_ch = '}' * 0x100 + '/';
3804 }
3805 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003806 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003807 if (!BB_MMU)
3808 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003809#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003810 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003811#else
3812#error Simple code to only allow ${var} is not implemented
3813#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003814 if (as_string) {
3815 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003816 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003817 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003818
3819 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3820 /* close the first block: */
3821 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003822 /* while parsing N from ${var:N[:M]}
3823 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003824 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003825 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003826 end_ch = '}';
3827 goto again;
3828 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003829 /* got '}' */
3830 if (end_ch == '}' * 0x100 + ':') {
3831 /* it's ${var:N} - emulate :999999999 */
3832 o_addstr(dest, "999999999");
3833 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003834 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003835 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003836 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003837 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003838 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3839 break;
3840 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003841#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003842 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003843 unsigned pos;
3844
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003845 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003846 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003847# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003848 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003849 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003850 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003851 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3852 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003853 if (!BB_MMU)
3854 pos = dest->length;
3855 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003856 if (as_string) {
3857 o_addstr(as_string, dest->data + pos);
3858 o_addchr(as_string, ')');
3859 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003860 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003861 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003862 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003863 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003864# endif
3865# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003866 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3867 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003868 if (!BB_MMU)
3869 pos = dest->length;
3870 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003871 if (as_string) {
3872 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003873 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003874 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003875 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003876# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003877 break;
3878 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003879#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003880 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003881 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003882 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003883 ch = i_peek(input);
3884 if (isalnum(ch)) { /* it's $_name or $_123 */
3885 ch = '_';
3886 goto make_var;
3887 }
3888 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003889 /* TODO: $_ and $-: */
3890 /* $_ Shell or shell script name; or last argument of last command
3891 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3892 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003893 /* $- Option flags set by set builtin or shell options (-i etc) */
3894 default:
3895 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003896 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003897 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003898 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003899#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003900}
3901
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003902#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003903# if ENABLE_HUSH_BASH_COMPAT
3904#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3905 encode_string(dest, input, dquote_end, process_bkslash)
3906# else
3907/* only ${var/pattern/repl} (its pattern part) needs additional mode */
3908#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3909 encode_string(dest, input, dquote_end)
3910# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003911#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003912
3913#else /* !MMU */
3914
3915# if ENABLE_HUSH_BASH_COMPAT
3916/* all parameters are needed, no macro tricks */
3917# else
3918#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3919 encode_string(as_string, dest, input, dquote_end)
3920# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003921#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003922static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003923 o_string *dest,
3924 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02003925 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003926 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003927{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003928#if !ENABLE_HUSH_BASH_COMPAT
3929 const int process_bkslash = 1;
3930#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003931 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003932 int next;
3933
3934 again:
3935 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003936 if (ch != EOF)
3937 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003938 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003939 debug_printf_parse("encode_string return 0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003940 return 0;
3941 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003942 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003943 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003944 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003945 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003946 }
3947 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003948 if (ch != '\n') {
3949 next = i_peek(input);
3950 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003951 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003952 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003953 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003954 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003955 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003956 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003957 }
3958 /* bash:
3959 * "The backslash retains its special meaning [in "..."]
3960 * only when followed by one of the following characters:
3961 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003962 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003963 * NB: in (unquoted) heredoc, above does not apply to ",
3964 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003965 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003966 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003967 ch = i_getch(input); /* eat next */
3968 if (ch == '\n')
3969 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02003970 } /* else: ch remains == '\\', and we double it below: */
3971 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003972 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003973 goto again;
3974 }
3975 if (ch == '$') {
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003976 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003977 debug_printf_parse("encode_string return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003978 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003979 return 1;
3980 }
3981 goto again;
3982 }
3983#if ENABLE_HUSH_TICK
3984 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003985 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003986 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3987 o_addchr(dest, 0x80 | '`');
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003988 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003989 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3990 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003991 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003992 }
3993#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00003994 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003995 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003996#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003997}
3998
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003999/*
4000 * Scan input until EOF or end_trigger char.
4001 * Return a list of pipes to execute, or NULL on EOF
4002 * or if end_trigger character is met.
4003 * On syntax error, exit is shell is not interactive,
4004 * reset parsing machinery and start parsing anew,
4005 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004006 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004007static struct pipe *parse_stream(char **pstring,
4008 struct in_str *input,
4009 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004010{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004011 struct parse_context ctx;
4012 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004013 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004014
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004015 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004016 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004017 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004018 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02004019 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004020 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004021
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004022 /* If very first arg is "" or '', dest.data may end up NULL.
4023 * Preventing this: */
4024 o_addchr(&dest, '\0');
4025 dest.length = 0;
4026
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004027 /* We used to separate words on $IFS here. This was wrong.
4028 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004029 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004030 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004031
4032 reset: /* we come back here only on syntax errors in interactive shell */
4033
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004034#if ENABLE_HUSH_INTERACTIVE
4035 input->promptmode = 0; /* PS1 */
4036#endif
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004037 if (MAYBE_ASSIGNMENT != 0)
4038 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004039 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004040 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004041 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004042 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004043 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004044 int ch;
4045 int next;
4046 int redir_fd;
4047 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004048
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004049 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004050 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004051 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004052 if (ch == EOF) {
4053 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004054
4055 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004056 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004057 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004058 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004059 /* end_trigger == '}' case errors out earlier,
4060 * checking only ')' */
4061 if (end_trigger == ')') {
4062 syntax_error_unterm_ch('('); /* exits */
4063 /* goto parse_error; */
4064 }
4065
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004066 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004067 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004068 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004069 o_free(&dest);
4070 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004071 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004072 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004073 /* (this makes bare "&" cmd a no-op.
4074 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004075 if (pi->num_cmds == 0
4076 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4077 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004078 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004079 pi = NULL;
4080 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004081#if !BB_MMU
4082 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4083 if (pstring)
4084 *pstring = ctx.as_string.data;
4085 else
4086 o_free_unsafe(&ctx.as_string);
4087#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004088 debug_leave();
4089 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004090 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004091 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004092 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004093
4094 next = '\0';
4095 if (ch != '\n')
4096 next = i_peek(input);
4097
4098 is_special = "{}<>;&|()#'" /* special outside of "str" */
4099 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4100 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004101 if (ctx.command->argv /* word [word]{... - non-special */
4102 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004103 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004104 || (next != ';' /* }; - special */
4105 && next != ')' /* }) - special */
4106 && next != '&' /* }& and }&& ... - special */
4107 && next != '|' /* }|| ... - special */
4108 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004109 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004110 ) {
4111 /* They are not special, skip "{}" */
4112 is_special += 2;
4113 }
4114 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004115 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004116
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004117 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004118 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004119 o_addQchr(&dest, ch);
4120 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4121 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004122 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004123 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004124 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004125 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004126 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004127 continue;
4128 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004129
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004130 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004131 if (done_word(&dest, &ctx)) {
4132 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004133 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004134 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004135 /* Is this a case when newline is simply ignored?
4136 * Some examples:
4137 * "cmd | <newline> cmd ..."
4138 * "case ... in <newline> word) ..."
4139 */
4140 if (IS_NULL_CMD(ctx.command)
4141 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004142 ) {
4143 continue;
4144 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004145 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004146 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004147 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4148 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004149 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004150 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004151 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004152 heredoc_cnt = 0;
4153 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004154 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004155 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004156 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004157 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004158 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004159 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004160
4161 /* "cmd}" or "cmd }..." without semicolon or &:
4162 * } is an ordinary char in this case, even inside { cmd; }
4163 * Pathological example: { ""}; } should exec "}" cmd
4164 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004165 if (ch == '}') {
4166 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4167 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004168 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004169 ) {
4170 goto ordinary_char;
4171 }
4172 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4173 goto skip_end_trigger;
4174 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004175 }
4176
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004177 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004178 && (ch != ';' || heredoc_cnt == 0)
4179#if ENABLE_HUSH_CASE
4180 && (ch != ')'
4181 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004182 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004183 )
4184#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004185 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004186 if (heredoc_cnt) {
4187 /* This is technically valid:
4188 * { cat <<HERE; }; echo Ok
4189 * heredoc
4190 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004191 * HERE
4192 * but we don't support this.
4193 * We require heredoc to be in enclosing {}/(),
4194 * if any.
4195 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004196 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004197 goto parse_error;
4198 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004199 if (done_word(&dest, &ctx)) {
4200 goto parse_error;
4201 }
4202 done_pipe(&ctx, PIPE_SEQ);
4203 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004204 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004205 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004206 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004207 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004208 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004209#if !BB_MMU
4210 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4211 if (pstring)
4212 *pstring = ctx.as_string.data;
4213 else
4214 o_free_unsafe(&ctx.as_string);
4215#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004216 debug_leave();
4217 debug_printf_parse("parse_stream return %p: "
4218 "end_trigger char found\n",
4219 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004220 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004221 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004222 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004223 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004224 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004225 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004226
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004227 /* Catch <, > before deciding whether this word is
4228 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4229 switch (ch) {
4230 case '>':
4231 redir_fd = redirect_opt_num(&dest);
4232 if (done_word(&dest, &ctx)) {
4233 goto parse_error;
4234 }
4235 redir_style = REDIRECT_OVERWRITE;
4236 if (next == '>') {
4237 redir_style = REDIRECT_APPEND;
4238 ch = i_getch(input);
4239 nommu_addchr(&ctx.as_string, ch);
4240 }
4241#if 0
4242 else if (next == '(') {
4243 syntax_error(">(process) not supported");
4244 goto parse_error;
4245 }
4246#endif
4247 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4248 goto parse_error;
4249 continue; /* back to top of while (1) */
4250 case '<':
4251 redir_fd = redirect_opt_num(&dest);
4252 if (done_word(&dest, &ctx)) {
4253 goto parse_error;
4254 }
4255 redir_style = REDIRECT_INPUT;
4256 if (next == '<') {
4257 redir_style = REDIRECT_HEREDOC;
4258 heredoc_cnt++;
4259 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4260 ch = i_getch(input);
4261 nommu_addchr(&ctx.as_string, ch);
4262 } else if (next == '>') {
4263 redir_style = REDIRECT_IO;
4264 ch = i_getch(input);
4265 nommu_addchr(&ctx.as_string, ch);
4266 }
4267#if 0
4268 else if (next == '(') {
4269 syntax_error("<(process) not supported");
4270 goto parse_error;
4271 }
4272#endif
4273 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4274 goto parse_error;
4275 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004276 case '#':
4277 if (dest.length == 0 && !dest.has_quoted_part) {
4278 /* skip "#comment" */
4279 while (1) {
4280 ch = i_peek(input);
4281 if (ch == EOF || ch == '\n')
4282 break;
4283 i_getch(input);
4284 /* note: we do not add it to &ctx.as_string */
4285 }
4286 nommu_addchr(&ctx.as_string, '\n');
4287 continue; /* back to top of while (1) */
4288 }
4289 break;
4290 case '\\':
4291 if (next == '\n') {
4292 /* It's "\<newline>" */
4293#if !BB_MMU
4294 /* Remove trailing '\' from ctx.as_string */
4295 ctx.as_string.data[--ctx.as_string.length] = '\0';
4296#endif
4297 ch = i_getch(input); /* eat it */
4298 continue; /* back to top of while (1) */
4299 }
4300 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004301 }
4302
4303 if (dest.o_assignment == MAYBE_ASSIGNMENT
4304 /* check that we are not in word in "a=1 2>word b=1": */
4305 && !ctx.pending_redirect
4306 ) {
4307 /* ch is a special char and thus this word
4308 * cannot be an assignment */
4309 dest.o_assignment = NOT_ASSIGNMENT;
4310 }
4311
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004312 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4313
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004314 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004315 case '#': /* non-comment #: "echo a#b" etc */
4316 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004317 break;
4318 case '\\':
4319 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004320 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004321 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004322 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004323 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004324 /* note: ch != '\n' (that case does not reach this place) */
4325 o_addchr(&dest, '\\');
4326 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4327 o_addchr(&dest, ch);
4328 nommu_addchr(&ctx.as_string, ch);
4329 /* Example: echo Hello \2>file
4330 * we need to know that word 2 is quoted */
4331 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004332 break;
4333 case '$':
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004334 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004335 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004336 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004337 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004338 }
Eric Andersen25f27032001-04-26 23:22:31 +00004339 break;
4340 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004341 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004342 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004343 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004344 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004345 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004346 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004347 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004348 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004349 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004350 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004351 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004352 }
Eric Andersen25f27032001-04-26 23:22:31 +00004353 break;
4354 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004355 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004356 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004357 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004358 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004359 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004360 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004361 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004362#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004363 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004364 unsigned pos;
4365
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004366 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4367 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004368 pos = dest.length;
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004369 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004370# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004371 o_addstr(&ctx.as_string, dest.data + pos);
4372 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004373# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004374 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4375 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004376 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004377 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004378#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004379 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004380#if ENABLE_HUSH_CASE
4381 case_semi:
4382#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004383 if (done_word(&dest, &ctx)) {
4384 goto parse_error;
4385 }
4386 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004387#if ENABLE_HUSH_CASE
4388 /* Eat multiple semicolons, detect
4389 * whether it means something special */
4390 while (1) {
4391 ch = i_peek(input);
4392 if (ch != ';')
4393 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004394 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004395 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004396 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004397 ctx.ctx_dsemicolon = 1;
4398 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004399 break;
4400 }
4401 }
4402#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004403 new_cmd:
4404 /* We just finished a cmd. New one may start
4405 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004406 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004407 break;
4408 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004409 if (done_word(&dest, &ctx)) {
4410 goto parse_error;
4411 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004412 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004413 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004414 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004415 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004416 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004417 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004418 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004419 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004420 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004421 if (done_word(&dest, &ctx)) {
4422 goto parse_error;
4423 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004424#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004425 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004426 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004427#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004428 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004429 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004430 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004431 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004432 } else {
4433 /* we could pick up a file descriptor choice here
4434 * with redirect_opt_num(), but bash doesn't do it.
4435 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004436 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004437#if !BB_MMU
4438 o_reset_to_empty_unquoted(&ctx.as_string);
4439#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004440 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004441 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004442 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004443#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004444 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004445 if (ctx.ctx_res_w == RES_MATCH
4446 && ctx.command->argv == NULL /* not (word|(... */
4447 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004448 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004449 ) {
4450 continue;
4451 }
4452#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004453 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004454 if (parse_group(&dest, &ctx, input, ch) != 0) {
4455 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004456 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004457 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004458 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004459#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004460 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004461 goto case_semi;
4462#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004463 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004464 /* proper use of this character is caught by end_trigger:
4465 * if we see {, we call parse_group(..., end_trigger='}')
4466 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004467 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004468 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004469 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004470 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004471 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004472 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004473 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004474
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004475 parse_error:
4476 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004477 struct parse_context *pctx;
4478 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004479
4480 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004481 * Sample for finding leaks on syntax error recovery path.
4482 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004483 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004484 * Samples to catch leaks at execution:
4485 * while if (true | {true;}); then echo ok; fi; do break; done
4486 * 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 +00004487 */
4488 pctx = &ctx;
4489 do {
4490 /* Update pipe/command counts,
4491 * otherwise freeing may miss some */
4492 done_pipe(pctx, PIPE_SEQ);
4493 debug_printf_clean("freeing list %p from ctx %p\n",
4494 pctx->list_head, pctx);
4495 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004496 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004497 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004498#if !BB_MMU
4499 o_free_unsafe(&pctx->as_string);
4500#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004501 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004502 if (pctx != &ctx) {
4503 free(pctx);
4504 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004505 IF_HAS_KEYWORDS(pctx = p2;)
4506 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004507 /* Free text, clear all dest fields */
4508 o_free(&dest);
4509 /* If we are not in top-level parse, we return,
4510 * our caller will propagate error.
4511 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004512 if (end_trigger != ';') {
4513#if !BB_MMU
4514 if (pstring)
4515 *pstring = NULL;
4516#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004517 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004518 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004519 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004520 /* Discard cached input, force prompt */
4521 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004522 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004523 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004524 }
Eric Andersen25f27032001-04-26 23:22:31 +00004525}
4526
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004527
4528/*** Execution routines ***/
4529
4530/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004531#if !ENABLE_HUSH_BASH_COMPAT
4532/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4533#define expand_string_to_string(str, do_unbackslash) \
4534 expand_string_to_string(str)
4535#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004536static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004537#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004538static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004539#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004540
4541/* expand_strvec_to_strvec() takes a list of strings, expands
4542 * all variable references within and returns a pointer to
4543 * a list of expanded strings, possibly with larger number
4544 * of strings. (Think VAR="a b"; echo $VAR).
4545 * This new list is allocated as a single malloc block.
4546 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004547 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004548 * Caller can deallocate entire list by single free(list). */
4549
Denys Vlasenko238081f2010-10-03 14:26:26 +02004550/* A horde of its helpers come first: */
4551
4552static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4553{
4554 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004555 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004556
Denys Vlasenko9e800222010-10-03 14:28:04 +02004557#if ENABLE_HUSH_BRACE_EXPANSION
4558 if (c == '{' || c == '}') {
4559 /* { -> \{, } -> \} */
4560 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004561 /* And now we want to add { or } and continue:
4562 * o_addchr(o, c);
4563 * continue;
4564 * luckily, just falling throught achieves this.
4565 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004566 }
4567#endif
4568 o_addchr(o, c);
4569 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004570 /* \z -> \\\z; \<eol> -> \\<eol> */
4571 o_addchr(o, '\\');
4572 if (len) {
4573 len--;
4574 o_addchr(o, '\\');
4575 o_addchr(o, *str++);
4576 }
4577 }
4578 }
4579}
4580
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004581/* Store given string, finalizing the word and starting new one whenever
4582 * we encounter IFS char(s). This is used for expanding variable values.
4583 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4584static int expand_on_ifs(o_string *output, int n, const char *str)
4585{
4586 while (1) {
4587 int word_len = strcspn(str, G.ifs);
4588 if (word_len) {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004589 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004590 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004591 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004592 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004593 * Example: "v='\*'; echo b$v" prints "b\*"
4594 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004595 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004596 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004597 /*/ Why can't we do it easier? */
4598 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4599 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4600 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004601 str += word_len;
4602 }
4603 if (!*str) /* EOL - do not finalize word */
4604 break;
4605 o_addchr(output, '\0');
4606 debug_print_list("expand_on_ifs", output, n);
4607 n = o_save_ptr(output, n);
4608 str += strspn(str, G.ifs); /* skip ifs chars */
4609 }
4610 debug_print_list("expand_on_ifs[1]", output, n);
4611 return n;
4612}
4613
4614/* Helper to expand $((...)) and heredoc body. These act as if
4615 * they are in double quotes, with the exception that they are not :).
4616 * Just the rules are similar: "expand only $var and `cmd`"
4617 *
4618 * Returns malloced string.
4619 * As an optimization, we return NULL if expansion is not needed.
4620 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004621#if !ENABLE_HUSH_BASH_COMPAT
4622/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4623#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4624 encode_then_expand_string(str)
4625#endif
4626static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004627{
4628 char *exp_str;
4629 struct in_str input;
4630 o_string dest = NULL_O_STRING;
4631
4632 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004633 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004634#if ENABLE_HUSH_TICK
4635 && !strchr(str, '`')
4636#endif
4637 ) {
4638 return NULL;
4639 }
4640
4641 /* We need to expand. Example:
4642 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4643 */
4644 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004645 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004646 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004647 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004648 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4649 o_free_unsafe(&dest);
4650 return exp_str;
4651}
4652
4653#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004654static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004655{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004656 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004657 arith_t res;
4658 char *exp_str;
4659
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004660 math_state.lookupvar = get_local_var_value;
4661 math_state.setvar = set_local_var_from_halves;
4662 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004663 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004664 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004665 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004666 if (errmsg_p)
4667 *errmsg_p = math_state.errmsg;
4668 if (math_state.errmsg)
4669 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004670 return res;
4671}
4672#endif
4673
4674#if ENABLE_HUSH_BASH_COMPAT
4675/* ${var/[/]pattern[/repl]} helpers */
4676static char *strstr_pattern(char *val, const char *pattern, int *size)
4677{
4678 while (1) {
4679 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4680 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4681 if (end) {
4682 *size = end - val;
4683 return val;
4684 }
4685 if (*val == '\0')
4686 return NULL;
4687 /* Optimization: if "*pat" did not match the start of "string",
4688 * we know that "tring", "ring" etc will not match too:
4689 */
4690 if (pattern[0] == '*')
4691 return NULL;
4692 val++;
4693 }
4694}
4695static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4696{
4697 char *result = NULL;
4698 unsigned res_len = 0;
4699 unsigned repl_len = strlen(repl);
4700
4701 while (1) {
4702 int size;
4703 char *s = strstr_pattern(val, pattern, &size);
4704 if (!s)
4705 break;
4706
4707 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4708 memcpy(result + res_len, val, s - val);
4709 res_len += s - val;
4710 strcpy(result + res_len, repl);
4711 res_len += repl_len;
4712 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4713
4714 val = s + size;
4715 if (exp_op == '/')
4716 break;
4717 }
4718 if (val[0] && result) {
4719 result = xrealloc(result, res_len + strlen(val) + 1);
4720 strcpy(result + res_len, val);
4721 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4722 }
4723 debug_printf_varexp("result:'%s'\n", result);
4724 return result;
4725}
4726#endif
4727
4728/* Helper:
4729 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4730 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004731static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004732{
4733 const char *val = NULL;
4734 char *to_be_freed = NULL;
4735 char *p = *pp;
4736 char *var;
4737 char first_char;
4738 char exp_op;
4739 char exp_save = exp_save; /* for compiler */
4740 char *exp_saveptr; /* points to expansion operator */
4741 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004742 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004743
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004744 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004745 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004746 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004747 arg0 = arg[0];
4748 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004749 exp_op = 0;
4750
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004751 if (first_char == '#' /* ${#... */
4752 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4753 ) {
4754 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004755 var++;
4756 exp_op = 'L';
4757 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004758 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004759 if (exp_saveptr /* if 2nd char is one of expansion operators */
4760 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4761 ) {
4762 /* ${?:0}, ${#[:]%0} etc */
4763 exp_saveptr = var + 1;
4764 } else {
4765 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4766 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4767 }
4768 exp_op = exp_save = *exp_saveptr;
4769 if (exp_op) {
4770 exp_word = exp_saveptr + 1;
4771 if (exp_op == ':') {
4772 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004773//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004774 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004775 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004776 ) {
4777 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4778 exp_op = ':';
4779 exp_word--;
4780 }
4781 }
4782 *exp_saveptr = '\0';
4783 } /* else: it's not an expansion op, but bare ${var} */
4784 }
4785
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004786 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004787 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004788 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004789 int n = xatoi_positive(var);
4790 if (n < G.global_argc)
4791 val = G.global_argv[n];
4792 /* else val remains NULL: $N with too big N */
4793 } else {
4794 switch (var[0]) {
4795 case '$': /* pid */
4796 val = utoa(G.root_pid);
4797 break;
4798 case '!': /* bg pid */
4799 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4800 break;
4801 case '?': /* exitcode */
4802 val = utoa(G.last_exitcode);
4803 break;
4804 case '#': /* argc */
4805 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4806 break;
4807 default:
4808 val = get_local_var_value(var);
4809 }
4810 }
4811
4812 /* Handle any expansions */
4813 if (exp_op == 'L') {
4814 debug_printf_expand("expand: length(%s)=", val);
4815 val = utoa(val ? strlen(val) : 0);
4816 debug_printf_expand("%s\n", val);
4817 } else if (exp_op) {
4818 if (exp_op == '%' || exp_op == '#') {
4819 /* Standard-mandated substring removal ops:
4820 * ${parameter%word} - remove smallest suffix pattern
4821 * ${parameter%%word} - remove largest suffix pattern
4822 * ${parameter#word} - remove smallest prefix pattern
4823 * ${parameter##word} - remove largest prefix pattern
4824 *
4825 * Word is expanded to produce a glob pattern.
4826 * Then var's value is matched to it and matching part removed.
4827 */
4828 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004829 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004830 char *exp_exp_word;
4831 char *loc;
4832 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02004833 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004834 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004835 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004836 if (exp_exp_word)
4837 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02004838 /* HACK ALERT. We depend here on the fact that
4839 * G.global_argv and results of utoa and get_local_var_value
4840 * are actually in writable memory:
4841 * scan_and_match momentarily stores NULs there. */
4842 t = (char*)val;
4843 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004844 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02004845 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004846 free(exp_exp_word);
4847 if (loc) { /* match was found */
4848 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004849 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004850 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004851 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004852 }
4853 }
4854 }
4855#if ENABLE_HUSH_BASH_COMPAT
4856 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004857 /* It's ${var/[/]pattern[/repl]} thing.
4858 * Note that in encoded form it has TWO parts:
4859 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02004860 * and if // is used, it is encoded as \:
4861 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004862 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004863 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004864 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004865 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004866 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004867 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004868 * by the usual expansion rules:
4869 * >az; >bz;
4870 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4871 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4872 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4873 * v='a bz'; echo ${v/a*z/\z} prints "z"
4874 * (note that a*z _pattern_ is never globbed!)
4875 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004876 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004877 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004878 if (!pattern)
4879 pattern = xstrdup(exp_word);
4880 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4881 *p++ = SPECIAL_VAR_SYMBOL;
4882 exp_word = p;
4883 p = strchr(p, SPECIAL_VAR_SYMBOL);
4884 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004885 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004886 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4887 /* HACK ALERT. We depend here on the fact that
4888 * G.global_argv and results of utoa and get_local_var_value
4889 * are actually in writable memory:
4890 * replace_pattern momentarily stores NULs there. */
4891 t = (char*)val;
4892 to_be_freed = replace_pattern(t,
4893 pattern,
4894 (repl ? repl : exp_word),
4895 exp_op);
4896 if (to_be_freed) /* at least one replace happened */
4897 val = to_be_freed;
4898 free(pattern);
4899 free(repl);
4900 }
4901 }
4902#endif
4903 else if (exp_op == ':') {
4904#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4905 /* It's ${var:N[:M]} bashism.
4906 * Note that in encoded form it has TWO parts:
4907 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4908 */
4909 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02004910 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004911
Denys Vlasenko063847d2010-09-15 13:33:02 +02004912 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4913 if (errmsg)
4914 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004915 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4916 *p++ = SPECIAL_VAR_SYMBOL;
4917 exp_word = p;
4918 p = strchr(p, SPECIAL_VAR_SYMBOL);
4919 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02004920 len = expand_and_evaluate_arith(exp_word, &errmsg);
4921 if (errmsg)
4922 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004923 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004924 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004925 if (beg < 0) /* bash compat */
4926 beg = 0;
4927 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004928 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02004929 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02004930 val = NULL;
4931 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004932 /* Paranoia. What if user entered 9999999999999
4933 * which fits in arith_t but not int? */
4934 if (len >= INT_MAX)
4935 len = INT_MAX;
4936 val = to_be_freed = xstrndup(val + beg, len);
4937 }
4938 debug_printf_varexp("val:'%s'\n", val);
4939 } else
4940#endif
4941 {
4942 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004943 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004944 }
4945 } else { /* one of "-=+?" */
4946 /* Standard-mandated substitution ops:
4947 * ${var?word} - indicate error if unset
4948 * If var is unset, word (or a message indicating it is unset
4949 * if word is null) is written to standard error
4950 * and the shell exits with a non-zero exit status.
4951 * Otherwise, the value of var is substituted.
4952 * ${var-word} - use default value
4953 * If var is unset, word is substituted.
4954 * ${var=word} - assign and use default value
4955 * If var is unset, word is assigned to var.
4956 * In all cases, final value of var is substituted.
4957 * ${var+word} - use alternative value
4958 * If var is unset, null is substituted.
4959 * Otherwise, word is substituted.
4960 *
4961 * Word is subjected to tilde expansion, parameter expansion,
4962 * command substitution, and arithmetic expansion.
4963 * If word is not needed, it is not expanded.
4964 *
4965 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4966 * but also treat null var as if it is unset.
4967 */
4968 int use_word = (!val || ((exp_save == ':') && !val[0]));
4969 if (exp_op == '+')
4970 use_word = !use_word;
4971 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4972 (exp_save == ':') ? "true" : "false", use_word);
4973 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004974 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004975 if (to_be_freed)
4976 exp_word = to_be_freed;
4977 if (exp_op == '?') {
4978 /* mimic bash message */
4979 die_if_script("%s: %s",
4980 var,
4981 exp_word[0] ? exp_word : "parameter null or not set"
4982 );
4983//TODO: how interactive bash aborts expansion mid-command?
4984 } else {
4985 val = exp_word;
4986 }
4987
4988 if (exp_op == '=') {
4989 /* ${var=[word]} or ${var:=[word]} */
4990 if (isdigit(var[0]) || var[0] == '#') {
4991 /* mimic bash message */
4992 die_if_script("$%s: cannot assign in this way", var);
4993 val = NULL;
4994 } else {
4995 char *new_var = xasprintf("%s=%s", var, val);
4996 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4997 }
4998 }
4999 }
5000 } /* one of "-=+?" */
5001
5002 *exp_saveptr = exp_save;
5003 } /* if (exp_op) */
5004
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005005 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005006
5007 *pp = p;
5008 *to_be_freed_pp = to_be_freed;
5009 return val;
5010}
5011
5012/* Expand all variable references in given string, adding words to list[]
5013 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5014 * to be filled). This routine is extremely tricky: has to deal with
5015 * variables/parameters with whitespace, $* and $@, and constructs like
5016 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005017static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005018{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005019 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005020 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005021 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005022 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005023 char *p;
5024
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005025 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5026 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005027 debug_print_list("expand_vars_to_list", output, n);
5028 n = o_save_ptr(output, n);
5029 debug_print_list("expand_vars_to_list[0]", output, n);
5030
5031 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5032 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005033 char *to_be_freed = NULL;
5034 const char *val = NULL;
5035#if ENABLE_HUSH_TICK
5036 o_string subst_result = NULL_O_STRING;
5037#endif
5038#if ENABLE_SH_MATH_SUPPORT
5039 char arith_buf[sizeof(arith_t)*3 + 2];
5040#endif
5041 o_addblock(output, arg, p - arg);
5042 debug_print_list("expand_vars_to_list[1]", output, n);
5043 arg = ++p;
5044 p = strchr(p, SPECIAL_VAR_SYMBOL);
5045
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005046 /* Fetch special var name (if it is indeed one of them)
5047 * and quote bit, force the bit on if singleword expansion -
5048 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005049 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005050
5051 /* Is this variable quoted and thus expansion can't be null?
5052 * "$@" is special. Even if quoted, it can still
5053 * expand to nothing (not even an empty string),
5054 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005055 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005056 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005057
5058 switch (first_ch & 0x7f) {
5059 /* Highest bit in first_ch indicates that var is double-quoted */
5060 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005061 case '@': {
5062 int i;
5063 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005064 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005065 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005066 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005067 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005068 while (G.global_argv[i]) {
5069 n = expand_on_ifs(output, n, G.global_argv[i]);
5070 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5071 if (G.global_argv[i++][0] && G.global_argv[i]) {
5072 /* this argv[] is not empty and not last:
5073 * put terminating NUL, start new word */
5074 o_addchr(output, '\0');
5075 debug_print_list("expand_vars_to_list[2]", output, n);
5076 n = o_save_ptr(output, n);
5077 debug_print_list("expand_vars_to_list[3]", output, n);
5078 }
5079 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005080 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005081 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005082 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005083 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005084 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005085 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005086 while (1) {
5087 o_addQstr(output, G.global_argv[i]);
5088 if (++i >= G.global_argc)
5089 break;
5090 o_addchr(output, '\0');
5091 debug_print_list("expand_vars_to_list[4]", output, n);
5092 n = o_save_ptr(output, n);
5093 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005094 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005095 while (1) {
5096 o_addQstr(output, G.global_argv[i]);
5097 if (!G.global_argv[++i])
5098 break;
5099 if (G.ifs[0])
5100 o_addchr(output, G.ifs[0]);
5101 }
5102 }
5103 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005104 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005105 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5106 /* "Empty variable", used to make "" etc to not disappear */
5107 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005108 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005109 break;
5110#if ENABLE_HUSH_TICK
5111 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005112 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005113 arg++;
5114 /* Can't just stuff it into output o_string,
5115 * expanded result may need to be globbed
5116 * and $IFS-splitted */
5117 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5118 G.last_exitcode = process_command_subs(&subst_result, arg);
5119 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5120 val = subst_result.data;
5121 goto store_val;
5122#endif
5123#if ENABLE_SH_MATH_SUPPORT
5124 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5125 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005126
5127 arg++; /* skip '+' */
5128 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5129 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005130 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005131 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5132 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005133 val = arith_buf;
5134 break;
5135 }
5136#endif
5137 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005138 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005139 IF_HUSH_TICK(store_val:)
5140 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005141 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5142 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005143 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005144 n = expand_on_ifs(output, n, val);
5145 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005146 }
5147 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005148 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5149 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005150 }
5151 break;
5152
5153 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5154
5155 if (val && val[0]) {
5156 o_addQstr(output, val);
5157 }
5158 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005159
5160 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5161 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005162 if (*p != SPECIAL_VAR_SYMBOL)
5163 *p = SPECIAL_VAR_SYMBOL;
5164
5165#if ENABLE_HUSH_TICK
5166 o_free(&subst_result);
5167#endif
5168 arg = ++p;
5169 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5170
5171 if (arg[0]) {
5172 debug_print_list("expand_vars_to_list[a]", output, n);
5173 /* this part is literal, and it was already pre-quoted
5174 * if needed (much earlier), do not use o_addQstr here! */
5175 o_addstr_with_NUL(output, arg);
5176 debug_print_list("expand_vars_to_list[b]", output, n);
5177 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005178 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005179 ) {
5180 n--;
5181 /* allow to reuse list[n] later without re-growth */
5182 output->has_empty_slot = 1;
5183 } else {
5184 o_addchr(output, '\0');
5185 }
5186
5187 return n;
5188}
5189
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005190static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005191{
5192 int n;
5193 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005194 o_string output = NULL_O_STRING;
5195
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005196 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005197
5198 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005199 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005200 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005201 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005202 }
5203 debug_print_list("expand_variables", &output, n);
5204
5205 /* output.data (malloced in one block) gets returned in "list" */
5206 list = o_finalize_list(&output, n);
5207 debug_print_strings("expand_variables[1]", list);
5208 return list;
5209}
5210
5211static char **expand_strvec_to_strvec(char **argv)
5212{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005213 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005214}
5215
5216#if ENABLE_HUSH_BASH_COMPAT
5217static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5218{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005219 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005220}
5221#endif
5222
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005223/* Used for expansion of right hand of assignments,
5224 * $((...)), heredocs, variable espansion parts.
5225 *
5226 * NB: should NOT do globbing!
5227 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5228 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005229static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005230{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005231#if !ENABLE_HUSH_BASH_COMPAT
5232 const int do_unbackslash = 1;
5233#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005234 char *argv[2], **list;
5235
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005236 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005237 /* This is generally an optimization, but it also
5238 * handles "", which otherwise trips over !list[0] check below.
5239 * (is this ever happens that we actually get str="" here?)
5240 */
5241 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5242 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005243 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005244 return xstrdup(str);
5245 }
5246
5247 argv[0] = (char*)str;
5248 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005249 list = expand_variables(argv, do_unbackslash
5250 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5251 : EXP_FLAG_SINGLEWORD
5252 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005253 if (HUSH_DEBUG)
5254 if (!list[0] || list[1])
5255 bb_error_msg_and_die("BUG in varexp2");
5256 /* actually, just move string 2*sizeof(char*) bytes back */
5257 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005258 if (do_unbackslash)
5259 unbackslash((char*)list);
5260 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005261 return (char*)list;
5262}
5263
5264/* Used for "eval" builtin */
5265static char* expand_strvec_to_string(char **argv)
5266{
5267 char **list;
5268
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005269 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005270 /* Convert all NULs to spaces */
5271 if (list[0]) {
5272 int n = 1;
5273 while (list[n]) {
5274 if (HUSH_DEBUG)
5275 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5276 bb_error_msg_and_die("BUG in varexp3");
5277 /* bash uses ' ' regardless of $IFS contents */
5278 list[n][-1] = ' ';
5279 n++;
5280 }
5281 }
5282 overlapping_strcpy((char*)list, list[0]);
5283 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5284 return (char*)list;
5285}
5286
5287static char **expand_assignments(char **argv, int count)
5288{
5289 int i;
5290 char **p;
5291
5292 G.expanded_assignments = p = NULL;
5293 /* Expand assignments into one string each */
5294 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005295 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005296 }
5297 G.expanded_assignments = NULL;
5298 return p;
5299}
5300
5301
5302#if BB_MMU
5303/* never called */
5304void re_execute_shell(char ***to_free, const char *s,
5305 char *g_argv0, char **g_argv,
5306 char **builtin_argv) NORETURN;
5307
5308static void reset_traps_to_defaults(void)
5309{
5310 /* This function is always called in a child shell
5311 * after fork (not vfork, NOMMU doesn't use this function).
5312 */
5313 unsigned sig;
5314 unsigned mask;
5315
5316 /* Child shells are not interactive.
5317 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5318 * Testcase: (while :; do :; done) + ^Z should background.
5319 * Same goes for SIGTERM, SIGHUP, SIGINT.
5320 */
5321 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5322 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5323
5324 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5325 * Stupid. It can be done with *single* &= op, but we can't use
5326 * the fact that G.blocked_set is implemented as a bitmask
5327 * in libc... */
5328 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5329 sig = 1;
5330 while (1) {
5331 if (mask & 1) {
5332 /* Careful. Only if no trap or trap is not "" */
5333 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5334 sigdelset(&G.blocked_set, sig);
5335 }
5336 mask >>= 1;
5337 if (!mask)
5338 break;
5339 sig++;
5340 }
5341 /* Our homegrown sig mask is saner to work with :) */
5342 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5343
5344 /* Resetting all traps to default except empty ones */
5345 mask = G.non_DFL_mask;
5346 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5347 if (!G.traps[sig] || !G.traps[sig][0])
5348 continue;
5349 free(G.traps[sig]);
5350 G.traps[sig] = NULL;
5351 /* There is no signal for 0 (EXIT) */
5352 if (sig == 0)
5353 continue;
5354 /* There was a trap handler, we just removed it.
5355 * But if sig still has non-DFL handling,
5356 * we should not unblock the sig. */
5357 if (mask & 1)
5358 continue;
5359 sigdelset(&G.blocked_set, sig);
5360 }
5361 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5362}
5363
5364#else /* !BB_MMU */
5365
5366static void re_execute_shell(char ***to_free, const char *s,
5367 char *g_argv0, char **g_argv,
5368 char **builtin_argv) NORETURN;
5369static void re_execute_shell(char ***to_free, const char *s,
5370 char *g_argv0, char **g_argv,
5371 char **builtin_argv)
5372{
5373# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5374 /* delims + 2 * (number of bytes in printed hex numbers) */
5375 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5376 char *heredoc_argv[4];
5377 struct variable *cur;
5378# if ENABLE_HUSH_FUNCTIONS
5379 struct function *funcp;
5380# endif
5381 char **argv, **pp;
5382 unsigned cnt;
5383 unsigned long long empty_trap_mask;
5384
5385 if (!g_argv0) { /* heredoc */
5386 argv = heredoc_argv;
5387 argv[0] = (char *) G.argv0_for_re_execing;
5388 argv[1] = (char *) "-<";
5389 argv[2] = (char *) s;
5390 argv[3] = NULL;
5391 pp = &argv[3]; /* used as pointer to empty environment */
5392 goto do_exec;
5393 }
5394
5395 cnt = 0;
5396 pp = builtin_argv;
5397 if (pp) while (*pp++)
5398 cnt++;
5399
5400 empty_trap_mask = 0;
5401 if (G.traps) {
5402 int sig;
5403 for (sig = 1; sig < NSIG; sig++) {
5404 if (G.traps[sig] && !G.traps[sig][0])
5405 empty_trap_mask |= 1LL << sig;
5406 }
5407 }
5408
5409 sprintf(param_buf, NOMMU_HACK_FMT
5410 , (unsigned) G.root_pid
5411 , (unsigned) G.root_ppid
5412 , (unsigned) G.last_bg_pid
5413 , (unsigned) G.last_exitcode
5414 , cnt
5415 , empty_trap_mask
5416 IF_HUSH_LOOPS(, G.depth_of_loop)
5417 );
5418# undef NOMMU_HACK_FMT
5419 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5420 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5421 */
5422 cnt += 6;
5423 for (cur = G.top_var; cur; cur = cur->next) {
5424 if (!cur->flg_export || cur->flg_read_only)
5425 cnt += 2;
5426 }
5427# if ENABLE_HUSH_FUNCTIONS
5428 for (funcp = G.top_func; funcp; funcp = funcp->next)
5429 cnt += 3;
5430# endif
5431 pp = g_argv;
5432 while (*pp++)
5433 cnt++;
5434 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5435 *pp++ = (char *) G.argv0_for_re_execing;
5436 *pp++ = param_buf;
5437 for (cur = G.top_var; cur; cur = cur->next) {
5438 if (strcmp(cur->varstr, hush_version_str) == 0)
5439 continue;
5440 if (cur->flg_read_only) {
5441 *pp++ = (char *) "-R";
5442 *pp++ = cur->varstr;
5443 } else if (!cur->flg_export) {
5444 *pp++ = (char *) "-V";
5445 *pp++ = cur->varstr;
5446 }
5447 }
5448# if ENABLE_HUSH_FUNCTIONS
5449 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5450 *pp++ = (char *) "-F";
5451 *pp++ = funcp->name;
5452 *pp++ = funcp->body_as_string;
5453 }
5454# endif
5455 /* We can pass activated traps here. Say, -Tnn:trap_string
5456 *
5457 * However, POSIX says that subshells reset signals with traps
5458 * to SIG_DFL.
5459 * I tested bash-3.2 and it not only does that with true subshells
5460 * of the form ( list ), but with any forked children shells.
5461 * I set trap "echo W" WINCH; and then tried:
5462 *
5463 * { echo 1; sleep 20; echo 2; } &
5464 * while true; do echo 1; sleep 20; echo 2; break; done &
5465 * true | { echo 1; sleep 20; echo 2; } | cat
5466 *
5467 * In all these cases sending SIGWINCH to the child shell
5468 * did not run the trap. If I add trap "echo V" WINCH;
5469 * _inside_ group (just before echo 1), it works.
5470 *
5471 * I conclude it means we don't need to pass active traps here.
5472 * Even if we would use signal handlers instead of signal masking
5473 * in order to implement trap handling,
5474 * exec syscall below resets signals to SIG_DFL for us.
5475 */
5476 *pp++ = (char *) "-c";
5477 *pp++ = (char *) s;
5478 if (builtin_argv) {
5479 while (*++builtin_argv)
5480 *pp++ = *builtin_argv;
5481 *pp++ = (char *) "";
5482 }
5483 *pp++ = g_argv0;
5484 while (*g_argv)
5485 *pp++ = *g_argv++;
5486 /* *pp = NULL; - is already there */
5487 pp = environ;
5488
5489 do_exec:
5490 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5491 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5492 execve(bb_busybox_exec_path, argv, pp);
5493 /* Fallback. Useful for init=/bin/hush usage etc */
5494 if (argv[0][0] == '/')
5495 execve(argv[0], argv, pp);
5496 xfunc_error_retval = 127;
5497 bb_error_msg_and_die("can't re-execute the shell");
5498}
5499#endif /* !BB_MMU */
5500
5501
5502static int run_and_free_list(struct pipe *pi);
5503
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005504/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005505 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5506 * end_trigger controls how often we stop parsing
5507 * NUL: parse all, execute, return
5508 * ';': parse till ';' or newline, execute, repeat till EOF
5509 */
5510static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005511{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005512 /* Why we need empty flag?
5513 * An obscure corner case "false; ``; echo $?":
5514 * empty command in `` should still set $? to 0.
5515 * But we can't just set $? to 0 at the start,
5516 * this breaks "false; echo `echo $?`" case.
5517 */
5518 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005519 while (1) {
5520 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005521
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005522 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005523 if (!pipe_list) { /* EOF */
5524 if (empty)
5525 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005526 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005527 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005528 debug_print_tree(pipe_list, 0);
5529 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5530 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005531 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005532 }
Eric Andersen25f27032001-04-26 23:22:31 +00005533}
5534
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005535static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005536{
5537 struct in_str input;
5538 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005539 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005540}
5541
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005542static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005543{
Eric Andersen25f27032001-04-26 23:22:31 +00005544 struct in_str input;
5545 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005546 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005547}
5548
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005549#if ENABLE_HUSH_TICK
5550static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5551{
5552 pid_t pid;
5553 int channel[2];
5554# if !BB_MMU
5555 char **to_free = NULL;
5556# endif
5557
5558 xpipe(channel);
5559 pid = BB_MMU ? xfork() : xvfork();
5560 if (pid == 0) { /* child */
5561 disable_restore_tty_pgrp_on_exit();
5562 /* Process substitution is not considered to be usual
5563 * 'command execution'.
5564 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5565 */
5566 bb_signals(0
5567 + (1 << SIGTSTP)
5568 + (1 << SIGTTIN)
5569 + (1 << SIGTTOU)
5570 , SIG_IGN);
5571 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5572 close(channel[0]); /* NB: close _first_, then move fd! */
5573 xmove_fd(channel[1], 1);
5574 /* Prevent it from trying to handle ctrl-z etc */
5575 IF_HUSH_JOB(G.run_list_level = 1;)
5576 /* Awful hack for `trap` or $(trap).
5577 *
5578 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5579 * contains an example where "trap" is executed in a subshell:
5580 *
5581 * save_traps=$(trap)
5582 * ...
5583 * eval "$save_traps"
5584 *
5585 * Standard does not say that "trap" in subshell shall print
5586 * parent shell's traps. It only says that its output
5587 * must have suitable form, but then, in the above example
5588 * (which is not supposed to be normative), it implies that.
5589 *
5590 * bash (and probably other shell) does implement it
5591 * (traps are reset to defaults, but "trap" still shows them),
5592 * but as a result, "trap" logic is hopelessly messed up:
5593 *
5594 * # trap
5595 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5596 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5597 * # true | trap <--- trap is in subshell - no output (ditto)
5598 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5599 * trap -- 'echo Ho' SIGWINCH
5600 * # echo `(trap)` <--- in subshell in subshell - output
5601 * trap -- 'echo Ho' SIGWINCH
5602 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5603 * trap -- 'echo Ho' SIGWINCH
5604 *
5605 * The rules when to forget and when to not forget traps
5606 * get really complex and nonsensical.
5607 *
5608 * Our solution: ONLY bare $(trap) or `trap` is special.
5609 */
5610 s = skip_whitespace(s);
5611 if (strncmp(s, "trap", 4) == 0
5612 && skip_whitespace(s + 4)[0] == '\0'
5613 ) {
5614 static const char *const argv[] = { NULL, NULL };
5615 builtin_trap((char**)argv);
5616 exit(0); /* not _exit() - we need to fflush */
5617 }
5618# if BB_MMU
5619 reset_traps_to_defaults();
5620 parse_and_run_string(s);
5621 _exit(G.last_exitcode);
5622# else
5623 /* We re-execute after vfork on NOMMU. This makes this script safe:
5624 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5625 * huge=`cat BIG` # was blocking here forever
5626 * echo OK
5627 */
5628 re_execute_shell(&to_free,
5629 s,
5630 G.global_argv[0],
5631 G.global_argv + 1,
5632 NULL);
5633# endif
5634 }
5635
5636 /* parent */
5637 *pid_p = pid;
5638# if ENABLE_HUSH_FAST
5639 G.count_SIGCHLD++;
5640//bb_error_msg("[%d] fork in generate_stream_from_string:"
5641// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5642// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5643# endif
5644 enable_restore_tty_pgrp_on_exit();
5645# if !BB_MMU
5646 free(to_free);
5647# endif
5648 close(channel[1]);
5649 close_on_exec_on(channel[0]);
5650 return xfdopen_for_read(channel[0]);
5651}
5652
5653/* Return code is exit status of the process that is run. */
5654static int process_command_subs(o_string *dest, const char *s)
5655{
5656 FILE *fp;
5657 struct in_str pipe_str;
5658 pid_t pid;
5659 int status, ch, eol_cnt;
5660
5661 fp = generate_stream_from_string(s, &pid);
5662
5663 /* Now send results of command back into original context */
5664 setup_file_in_str(&pipe_str, fp);
5665 eol_cnt = 0;
5666 while ((ch = i_getch(&pipe_str)) != EOF) {
5667 if (ch == '\n') {
5668 eol_cnt++;
5669 continue;
5670 }
5671 while (eol_cnt) {
5672 o_addchr(dest, '\n');
5673 eol_cnt--;
5674 }
5675 o_addQchr(dest, ch);
5676 }
5677
5678 debug_printf("done reading from `cmd` pipe, closing it\n");
5679 fclose(fp);
5680 /* We need to extract exitcode. Test case
5681 * "true; echo `sleep 1; false` $?"
5682 * should print 1 */
5683 safe_waitpid(pid, &status, 0);
5684 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5685 return WEXITSTATUS(status);
5686}
5687#endif /* ENABLE_HUSH_TICK */
5688
5689
5690static void setup_heredoc(struct redir_struct *redir)
5691{
5692 struct fd_pair pair;
5693 pid_t pid;
5694 int len, written;
5695 /* the _body_ of heredoc (misleading field name) */
5696 const char *heredoc = redir->rd_filename;
5697 char *expanded;
5698#if !BB_MMU
5699 char **to_free;
5700#endif
5701
5702 expanded = NULL;
5703 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005704 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005705 if (expanded)
5706 heredoc = expanded;
5707 }
5708 len = strlen(heredoc);
5709
5710 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5711 xpiped_pair(pair);
5712 xmove_fd(pair.rd, redir->rd_fd);
5713
5714 /* Try writing without forking. Newer kernels have
5715 * dynamically growing pipes. Must use non-blocking write! */
5716 ndelay_on(pair.wr);
5717 while (1) {
5718 written = write(pair.wr, heredoc, len);
5719 if (written <= 0)
5720 break;
5721 len -= written;
5722 if (len == 0) {
5723 close(pair.wr);
5724 free(expanded);
5725 return;
5726 }
5727 heredoc += written;
5728 }
5729 ndelay_off(pair.wr);
5730
5731 /* Okay, pipe buffer was not big enough */
5732 /* Note: we must not create a stray child (bastard? :)
5733 * for the unsuspecting parent process. Child creates a grandchild
5734 * and exits before parent execs the process which consumes heredoc
5735 * (that exec happens after we return from this function) */
5736#if !BB_MMU
5737 to_free = NULL;
5738#endif
5739 pid = xvfork();
5740 if (pid == 0) {
5741 /* child */
5742 disable_restore_tty_pgrp_on_exit();
5743 pid = BB_MMU ? xfork() : xvfork();
5744 if (pid != 0)
5745 _exit(0);
5746 /* grandchild */
5747 close(redir->rd_fd); /* read side of the pipe */
5748#if BB_MMU
5749 full_write(pair.wr, heredoc, len); /* may loop or block */
5750 _exit(0);
5751#else
5752 /* Delegate blocking writes to another process */
5753 xmove_fd(pair.wr, STDOUT_FILENO);
5754 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5755#endif
5756 }
5757 /* parent */
5758#if ENABLE_HUSH_FAST
5759 G.count_SIGCHLD++;
5760//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5761#endif
5762 enable_restore_tty_pgrp_on_exit();
5763#if !BB_MMU
5764 free(to_free);
5765#endif
5766 close(pair.wr);
5767 free(expanded);
5768 wait(NULL); /* wait till child has died */
5769}
5770
5771/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5772 * and stderr if they are redirected. */
5773static int setup_redirects(struct command *prog, int squirrel[])
5774{
5775 int openfd, mode;
5776 struct redir_struct *redir;
5777
5778 for (redir = prog->redirects; redir; redir = redir->next) {
5779 if (redir->rd_type == REDIRECT_HEREDOC2) {
5780 /* rd_fd<<HERE case */
5781 if (squirrel && redir->rd_fd < 3
5782 && squirrel[redir->rd_fd] < 0
5783 ) {
5784 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5785 }
5786 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5787 * of the heredoc */
5788 debug_printf_parse("set heredoc '%s'\n",
5789 redir->rd_filename);
5790 setup_heredoc(redir);
5791 continue;
5792 }
5793
5794 if (redir->rd_dup == REDIRFD_TO_FILE) {
5795 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5796 char *p;
5797 if (redir->rd_filename == NULL) {
5798 /* Something went wrong in the parse.
5799 * Pretend it didn't happen */
5800 bb_error_msg("bug in redirect parse");
5801 continue;
5802 }
5803 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005804 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005805 openfd = open_or_warn(p, mode);
5806 free(p);
5807 if (openfd < 0) {
5808 /* this could get lost if stderr has been redirected, but
5809 * bash and ash both lose it as well (though zsh doesn't!) */
5810//what the above comment tries to say?
5811 return 1;
5812 }
5813 } else {
5814 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5815 openfd = redir->rd_dup;
5816 }
5817
5818 if (openfd != redir->rd_fd) {
5819 if (squirrel && redir->rd_fd < 3
5820 && squirrel[redir->rd_fd] < 0
5821 ) {
5822 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5823 }
5824 if (openfd == REDIRFD_CLOSE) {
5825 /* "n>-" means "close me" */
5826 close(redir->rd_fd);
5827 } else {
5828 xdup2(openfd, redir->rd_fd);
5829 if (redir->rd_dup == REDIRFD_TO_FILE)
5830 close(openfd);
5831 }
5832 }
5833 }
5834 return 0;
5835}
5836
5837static void restore_redirects(int squirrel[])
5838{
5839 int i, fd;
5840 for (i = 0; i < 3; i++) {
5841 fd = squirrel[i];
5842 if (fd != -1) {
5843 /* We simply die on error */
5844 xmove_fd(fd, i);
5845 }
5846 }
5847}
5848
5849static char *find_in_path(const char *arg)
5850{
5851 char *ret = NULL;
5852 const char *PATH = get_local_var_value("PATH");
5853
5854 if (!PATH)
5855 return NULL;
5856
5857 while (1) {
5858 const char *end = strchrnul(PATH, ':');
5859 int sz = end - PATH; /* must be int! */
5860
5861 free(ret);
5862 if (sz != 0) {
5863 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5864 } else {
5865 /* We have xxx::yyyy in $PATH,
5866 * it means "use current dir" */
5867 ret = xstrdup(arg);
5868 }
5869 if (access(ret, F_OK) == 0)
5870 break;
5871
5872 if (*end == '\0') {
5873 free(ret);
5874 return NULL;
5875 }
5876 PATH = end + 1;
5877 }
5878
5879 return ret;
5880}
5881
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005882static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005883 const struct built_in_command *x,
5884 const struct built_in_command *end)
5885{
5886 while (x != end) {
5887 if (strcmp(name, x->b_cmd) != 0) {
5888 x++;
5889 continue;
5890 }
5891 debug_printf_exec("found builtin '%s'\n", name);
5892 return x;
5893 }
5894 return NULL;
5895}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005896static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005897{
5898 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5899}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005900static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005901{
5902 const struct built_in_command *x = find_builtin1(name);
5903 if (x)
5904 return x;
5905 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5906}
5907
5908#if ENABLE_HUSH_FUNCTIONS
5909static struct function **find_function_slot(const char *name)
5910{
5911 struct function **funcpp = &G.top_func;
5912 while (*funcpp) {
5913 if (strcmp(name, (*funcpp)->name) == 0) {
5914 break;
5915 }
5916 funcpp = &(*funcpp)->next;
5917 }
5918 return funcpp;
5919}
5920
5921static const struct function *find_function(const char *name)
5922{
5923 const struct function *funcp = *find_function_slot(name);
5924 if (funcp)
5925 debug_printf_exec("found function '%s'\n", name);
5926 return funcp;
5927}
5928
5929/* Note: takes ownership on name ptr */
5930static struct function *new_function(char *name)
5931{
5932 struct function **funcpp = find_function_slot(name);
5933 struct function *funcp = *funcpp;
5934
5935 if (funcp != NULL) {
5936 struct command *cmd = funcp->parent_cmd;
5937 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5938 if (!cmd) {
5939 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5940 free(funcp->name);
5941 /* Note: if !funcp->body, do not free body_as_string!
5942 * This is a special case of "-F name body" function:
5943 * body_as_string was not malloced! */
5944 if (funcp->body) {
5945 free_pipe_list(funcp->body);
5946# if !BB_MMU
5947 free(funcp->body_as_string);
5948# endif
5949 }
5950 } else {
5951 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5952 cmd->argv[0] = funcp->name;
5953 cmd->group = funcp->body;
5954# if !BB_MMU
5955 cmd->group_as_string = funcp->body_as_string;
5956# endif
5957 }
5958 } else {
5959 debug_printf_exec("remembering new function '%s'\n", name);
5960 funcp = *funcpp = xzalloc(sizeof(*funcp));
5961 /*funcp->next = NULL;*/
5962 }
5963
5964 funcp->name = name;
5965 return funcp;
5966}
5967
5968static void unset_func(const char *name)
5969{
5970 struct function **funcpp = find_function_slot(name);
5971 struct function *funcp = *funcpp;
5972
5973 if (funcp != NULL) {
5974 debug_printf_exec("freeing function '%s'\n", funcp->name);
5975 *funcpp = funcp->next;
5976 /* funcp is unlinked now, deleting it.
5977 * Note: if !funcp->body, the function was created by
5978 * "-F name body", do not free ->body_as_string
5979 * and ->name as they were not malloced. */
5980 if (funcp->body) {
5981 free_pipe_list(funcp->body);
5982 free(funcp->name);
5983# if !BB_MMU
5984 free(funcp->body_as_string);
5985# endif
5986 }
5987 free(funcp);
5988 }
5989}
5990
5991# if BB_MMU
5992#define exec_function(to_free, funcp, argv) \
5993 exec_function(funcp, argv)
5994# endif
5995static void exec_function(char ***to_free,
5996 const struct function *funcp,
5997 char **argv) NORETURN;
5998static void exec_function(char ***to_free,
5999 const struct function *funcp,
6000 char **argv)
6001{
6002# if BB_MMU
6003 int n = 1;
6004
6005 argv[0] = G.global_argv[0];
6006 G.global_argv = argv;
6007 while (*++argv)
6008 n++;
6009 G.global_argc = n;
6010 /* On MMU, funcp->body is always non-NULL */
6011 n = run_list(funcp->body);
6012 fflush_all();
6013 _exit(n);
6014# else
6015 re_execute_shell(to_free,
6016 funcp->body_as_string,
6017 G.global_argv[0],
6018 argv + 1,
6019 NULL);
6020# endif
6021}
6022
6023static int run_function(const struct function *funcp, char **argv)
6024{
6025 int rc;
6026 save_arg_t sv;
6027 smallint sv_flg;
6028
6029 save_and_replace_G_args(&sv, argv);
6030
6031 /* "we are in function, ok to use return" */
6032 sv_flg = G.flag_return_in_progress;
6033 G.flag_return_in_progress = -1;
6034# if ENABLE_HUSH_LOCAL
6035 G.func_nest_level++;
6036# endif
6037
6038 /* On MMU, funcp->body is always non-NULL */
6039# if !BB_MMU
6040 if (!funcp->body) {
6041 /* Function defined by -F */
6042 parse_and_run_string(funcp->body_as_string);
6043 rc = G.last_exitcode;
6044 } else
6045# endif
6046 {
6047 rc = run_list(funcp->body);
6048 }
6049
6050# if ENABLE_HUSH_LOCAL
6051 {
6052 struct variable *var;
6053 struct variable **var_pp;
6054
6055 var_pp = &G.top_var;
6056 while ((var = *var_pp) != NULL) {
6057 if (var->func_nest_level < G.func_nest_level) {
6058 var_pp = &var->next;
6059 continue;
6060 }
6061 /* Unexport */
6062 if (var->flg_export)
6063 bb_unsetenv(var->varstr);
6064 /* Remove from global list */
6065 *var_pp = var->next;
6066 /* Free */
6067 if (!var->max_len)
6068 free(var->varstr);
6069 free(var);
6070 }
6071 G.func_nest_level--;
6072 }
6073# endif
6074 G.flag_return_in_progress = sv_flg;
6075
6076 restore_G_args(&sv, argv);
6077
6078 return rc;
6079}
6080#endif /* ENABLE_HUSH_FUNCTIONS */
6081
6082
6083#if BB_MMU
6084#define exec_builtin(to_free, x, argv) \
6085 exec_builtin(x, argv)
6086#else
6087#define exec_builtin(to_free, x, argv) \
6088 exec_builtin(to_free, argv)
6089#endif
6090static void exec_builtin(char ***to_free,
6091 const struct built_in_command *x,
6092 char **argv) NORETURN;
6093static void exec_builtin(char ***to_free,
6094 const struct built_in_command *x,
6095 char **argv)
6096{
6097#if BB_MMU
6098 int rcode = x->b_function(argv);
6099 fflush_all();
6100 _exit(rcode);
6101#else
6102 /* On NOMMU, we must never block!
6103 * Example: { sleep 99 | read line; } & echo Ok
6104 */
6105 re_execute_shell(to_free,
6106 argv[0],
6107 G.global_argv[0],
6108 G.global_argv + 1,
6109 argv);
6110#endif
6111}
6112
6113
6114static void execvp_or_die(char **argv) NORETURN;
6115static void execvp_or_die(char **argv)
6116{
6117 debug_printf_exec("execing '%s'\n", argv[0]);
6118 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6119 execvp(argv[0], argv);
6120 bb_perror_msg("can't execute '%s'", argv[0]);
6121 _exit(127); /* bash compat */
6122}
6123
6124#if ENABLE_HUSH_MODE_X
6125static void dump_cmd_in_x_mode(char **argv)
6126{
6127 if (G_x_mode && argv) {
6128 /* We want to output the line in one write op */
6129 char *buf, *p;
6130 int len;
6131 int n;
6132
6133 len = 3;
6134 n = 0;
6135 while (argv[n])
6136 len += strlen(argv[n++]) + 1;
6137 buf = xmalloc(len);
6138 buf[0] = '+';
6139 p = buf + 1;
6140 n = 0;
6141 while (argv[n])
6142 p += sprintf(p, " %s", argv[n++]);
6143 *p++ = '\n';
6144 *p = '\0';
6145 fputs(buf, stderr);
6146 free(buf);
6147 }
6148}
6149#else
6150# define dump_cmd_in_x_mode(argv) ((void)0)
6151#endif
6152
6153#if BB_MMU
6154#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6155 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6156#define pseudo_exec(nommu_save, command, argv_expanded) \
6157 pseudo_exec(command, argv_expanded)
6158#endif
6159
6160/* Called after [v]fork() in run_pipe, or from builtin_exec.
6161 * Never returns.
6162 * Don't exit() here. If you don't exec, use _exit instead.
6163 * The at_exit handlers apparently confuse the calling process,
6164 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6165static void pseudo_exec_argv(nommu_save_t *nommu_save,
6166 char **argv, int assignment_cnt,
6167 char **argv_expanded) NORETURN;
6168static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6169 char **argv, int assignment_cnt,
6170 char **argv_expanded)
6171{
6172 char **new_env;
6173
6174 new_env = expand_assignments(argv, assignment_cnt);
6175 dump_cmd_in_x_mode(new_env);
6176
6177 if (!argv[assignment_cnt]) {
6178 /* Case when we are here: ... | var=val | ...
6179 * (note that we do not exit early, i.e., do not optimize out
6180 * expand_assignments(): think about ... | var=`sleep 1` | ...
6181 */
6182 free_strings(new_env);
6183 _exit(EXIT_SUCCESS);
6184 }
6185
6186#if BB_MMU
6187 set_vars_and_save_old(new_env);
6188 free(new_env); /* optional */
6189 /* we can also destroy set_vars_and_save_old's return value,
6190 * to save memory */
6191#else
6192 nommu_save->new_env = new_env;
6193 nommu_save->old_vars = set_vars_and_save_old(new_env);
6194#endif
6195
6196 if (argv_expanded) {
6197 argv = argv_expanded;
6198 } else {
6199 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6200#if !BB_MMU
6201 nommu_save->argv = argv;
6202#endif
6203 }
6204 dump_cmd_in_x_mode(argv);
6205
6206#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6207 if (strchr(argv[0], '/') != NULL)
6208 goto skip;
6209#endif
6210
6211 /* Check if the command matches any of the builtins.
6212 * Depending on context, this might be redundant. But it's
6213 * easier to waste a few CPU cycles than it is to figure out
6214 * if this is one of those cases.
6215 */
6216 {
6217 /* On NOMMU, it is more expensive to re-execute shell
6218 * just in order to run echo or test builtin.
6219 * It's better to skip it here and run corresponding
6220 * non-builtin later. */
6221 const struct built_in_command *x;
6222 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6223 if (x) {
6224 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6225 }
6226 }
6227#if ENABLE_HUSH_FUNCTIONS
6228 /* Check if the command matches any functions */
6229 {
6230 const struct function *funcp = find_function(argv[0]);
6231 if (funcp) {
6232 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6233 }
6234 }
6235#endif
6236
6237#if ENABLE_FEATURE_SH_STANDALONE
6238 /* Check if the command matches any busybox applets */
6239 {
6240 int a = find_applet_by_name(argv[0]);
6241 if (a >= 0) {
6242# if BB_MMU /* see above why on NOMMU it is not allowed */
6243 if (APPLET_IS_NOEXEC(a)) {
6244 debug_printf_exec("running applet '%s'\n", argv[0]);
6245 run_applet_no_and_exit(a, argv);
6246 }
6247# endif
6248 /* Re-exec ourselves */
6249 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6250 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6251 execv(bb_busybox_exec_path, argv);
6252 /* If they called chroot or otherwise made the binary no longer
6253 * executable, fall through */
6254 }
6255 }
6256#endif
6257
6258#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6259 skip:
6260#endif
6261 execvp_or_die(argv);
6262}
6263
6264/* Called after [v]fork() in run_pipe
6265 */
6266static void pseudo_exec(nommu_save_t *nommu_save,
6267 struct command *command,
6268 char **argv_expanded) NORETURN;
6269static void pseudo_exec(nommu_save_t *nommu_save,
6270 struct command *command,
6271 char **argv_expanded)
6272{
6273 if (command->argv) {
6274 pseudo_exec_argv(nommu_save, command->argv,
6275 command->assignment_cnt, argv_expanded);
6276 }
6277
6278 if (command->group) {
6279 /* Cases when we are here:
6280 * ( list )
6281 * { list } &
6282 * ... | ( list ) | ...
6283 * ... | { list } | ...
6284 */
6285#if BB_MMU
6286 int rcode;
6287 debug_printf_exec("pseudo_exec: run_list\n");
6288 reset_traps_to_defaults();
6289 rcode = run_list(command->group);
6290 /* OK to leak memory by not calling free_pipe_list,
6291 * since this process is about to exit */
6292 _exit(rcode);
6293#else
6294 re_execute_shell(&nommu_save->argv_from_re_execing,
6295 command->group_as_string,
6296 G.global_argv[0],
6297 G.global_argv + 1,
6298 NULL);
6299#endif
6300 }
6301
6302 /* Case when we are here: ... | >file */
6303 debug_printf_exec("pseudo_exec'ed null command\n");
6304 _exit(EXIT_SUCCESS);
6305}
6306
6307#if ENABLE_HUSH_JOB
6308static const char *get_cmdtext(struct pipe *pi)
6309{
6310 char **argv;
6311 char *p;
6312 int len;
6313
6314 /* This is subtle. ->cmdtext is created only on first backgrounding.
6315 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6316 * On subsequent bg argv is trashed, but we won't use it */
6317 if (pi->cmdtext)
6318 return pi->cmdtext;
6319 argv = pi->cmds[0].argv;
6320 if (!argv || !argv[0]) {
6321 pi->cmdtext = xzalloc(1);
6322 return pi->cmdtext;
6323 }
6324
6325 len = 0;
6326 do {
6327 len += strlen(*argv) + 1;
6328 } while (*++argv);
6329 p = xmalloc(len);
6330 pi->cmdtext = p;
6331 argv = pi->cmds[0].argv;
6332 do {
6333 len = strlen(*argv);
6334 memcpy(p, *argv, len);
6335 p += len;
6336 *p++ = ' ';
6337 } while (*++argv);
6338 p[-1] = '\0';
6339 return pi->cmdtext;
6340}
6341
6342static void insert_bg_job(struct pipe *pi)
6343{
6344 struct pipe *job, **jobp;
6345 int i;
6346
6347 /* Linear search for the ID of the job to use */
6348 pi->jobid = 1;
6349 for (job = G.job_list; job; job = job->next)
6350 if (job->jobid >= pi->jobid)
6351 pi->jobid = job->jobid + 1;
6352
6353 /* Add job to the list of running jobs */
6354 jobp = &G.job_list;
6355 while ((job = *jobp) != NULL)
6356 jobp = &job->next;
6357 job = *jobp = xmalloc(sizeof(*job));
6358
6359 *job = *pi; /* physical copy */
6360 job->next = NULL;
6361 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6362 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6363 for (i = 0; i < pi->num_cmds; i++) {
6364 job->cmds[i].pid = pi->cmds[i].pid;
6365 /* all other fields are not used and stay zero */
6366 }
6367 job->cmdtext = xstrdup(get_cmdtext(pi));
6368
6369 if (G_interactive_fd)
6370 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6371 G.last_jobid = job->jobid;
6372}
6373
6374static void remove_bg_job(struct pipe *pi)
6375{
6376 struct pipe *prev_pipe;
6377
6378 if (pi == G.job_list) {
6379 G.job_list = pi->next;
6380 } else {
6381 prev_pipe = G.job_list;
6382 while (prev_pipe->next != pi)
6383 prev_pipe = prev_pipe->next;
6384 prev_pipe->next = pi->next;
6385 }
6386 if (G.job_list)
6387 G.last_jobid = G.job_list->jobid;
6388 else
6389 G.last_jobid = 0;
6390}
6391
6392/* Remove a backgrounded job */
6393static void delete_finished_bg_job(struct pipe *pi)
6394{
6395 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006396 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006397}
6398#endif /* JOB */
6399
6400/* Check to see if any processes have exited -- if they
6401 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006402static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006403{
6404 int attributes;
6405 int status;
6406#if ENABLE_HUSH_JOB
6407 struct pipe *pi;
6408#endif
6409 pid_t childpid;
6410 int rcode = 0;
6411
6412 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6413
6414 attributes = WUNTRACED;
6415 if (fg_pipe == NULL)
6416 attributes |= WNOHANG;
6417
6418 errno = 0;
6419#if ENABLE_HUSH_FAST
6420 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6421//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6422//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6423 /* There was neither fork nor SIGCHLD since last waitpid */
6424 /* Avoid doing waitpid syscall if possible */
6425 if (!G.we_have_children) {
6426 errno = ECHILD;
6427 return -1;
6428 }
6429 if (fg_pipe == NULL) { /* is WNOHANG set? */
6430 /* We have children, but they did not exit
6431 * or stop yet (we saw no SIGCHLD) */
6432 return 0;
6433 }
6434 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6435 }
6436#endif
6437
6438/* Do we do this right?
6439 * bash-3.00# sleep 20 | false
6440 * <ctrl-Z pressed>
6441 * [3]+ Stopped sleep 20 | false
6442 * bash-3.00# echo $?
6443 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6444 * [hush 1.14.0: yes we do it right]
6445 */
6446 wait_more:
6447 while (1) {
6448 int i;
6449 int dead;
6450
6451#if ENABLE_HUSH_FAST
6452 i = G.count_SIGCHLD;
6453#endif
6454 childpid = waitpid(-1, &status, attributes);
6455 if (childpid <= 0) {
6456 if (childpid && errno != ECHILD)
6457 bb_perror_msg("waitpid");
6458#if ENABLE_HUSH_FAST
6459 else { /* Until next SIGCHLD, waitpid's are useless */
6460 G.we_have_children = (childpid == 0);
6461 G.handled_SIGCHLD = i;
6462//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6463 }
6464#endif
6465 break;
6466 }
6467 dead = WIFEXITED(status) || WIFSIGNALED(status);
6468
6469#if DEBUG_JOBS
6470 if (WIFSTOPPED(status))
6471 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6472 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6473 if (WIFSIGNALED(status))
6474 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6475 childpid, WTERMSIG(status), WEXITSTATUS(status));
6476 if (WIFEXITED(status))
6477 debug_printf_jobs("pid %d exited, exitcode %d\n",
6478 childpid, WEXITSTATUS(status));
6479#endif
6480 /* Were we asked to wait for fg pipe? */
6481 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006482 i = fg_pipe->num_cmds;
6483 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006484 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6485 if (fg_pipe->cmds[i].pid != childpid)
6486 continue;
6487 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006488 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006489 fg_pipe->cmds[i].pid = 0;
6490 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006491 ex = WEXITSTATUS(status);
6492 /* bash prints killer signal's name for *last*
6493 * process in pipe (prints just newline for SIGINT).
6494 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6495 */
6496 if (WIFSIGNALED(status)) {
6497 int sig = WTERMSIG(status);
6498 if (i == fg_pipe->num_cmds-1)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006499 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006500 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6501 * Maybe we need to use sig | 128? */
6502 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006503 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006504 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006505 } else {
6506 fg_pipe->cmds[i].is_stopped = 1;
6507 fg_pipe->stopped_cmds++;
6508 }
6509 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6510 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006511 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006512 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006513 i = fg_pipe->num_cmds;
6514 while (--i >= 0) {
6515 rcode = fg_pipe->cmds[i].cmd_exitcode;
6516 /* usually last process gives overall exitstatus,
6517 * but with "set -o pipefail", last *failed* process does */
6518 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6519 break;
6520 }
6521 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006522/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6523 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6524 * and "killall -STOP cat" */
6525 if (G_interactive_fd) {
6526#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006527 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006528 insert_bg_job(fg_pipe);
6529#endif
6530 return rcode;
6531 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006532 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006533 return rcode;
6534 }
6535 /* There are still running processes in the fg pipe */
6536 goto wait_more; /* do waitpid again */
6537 }
6538 /* it wasnt fg_pipe, look for process in bg pipes */
6539 }
6540
6541#if ENABLE_HUSH_JOB
6542 /* We asked to wait for bg or orphaned children */
6543 /* No need to remember exitcode in this case */
6544 for (pi = G.job_list; pi; pi = pi->next) {
6545 for (i = 0; i < pi->num_cmds; i++) {
6546 if (pi->cmds[i].pid == childpid)
6547 goto found_pi_and_prognum;
6548 }
6549 }
6550 /* Happens when shell is used as init process (init=/bin/sh) */
6551 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6552 continue; /* do waitpid again */
6553
6554 found_pi_and_prognum:
6555 if (dead) {
6556 /* child exited */
6557 pi->cmds[i].pid = 0;
6558 pi->alive_cmds--;
6559 if (!pi->alive_cmds) {
6560 if (G_interactive_fd)
6561 printf(JOB_STATUS_FORMAT, pi->jobid,
6562 "Done", pi->cmdtext);
6563 delete_finished_bg_job(pi);
6564 }
6565 } else {
6566 /* child stopped */
6567 pi->cmds[i].is_stopped = 1;
6568 pi->stopped_cmds++;
6569 }
6570#endif
6571 } /* while (waitpid succeeds)... */
6572
6573 return rcode;
6574}
6575
6576#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006577static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006578{
6579 pid_t p;
6580 int rcode = checkjobs(fg_pipe);
6581 if (G_saved_tty_pgrp) {
6582 /* Job finished, move the shell to the foreground */
6583 p = getpgrp(); /* our process group id */
6584 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6585 tcsetpgrp(G_interactive_fd, p);
6586 }
6587 return rcode;
6588}
6589#endif
6590
6591/* Start all the jobs, but don't wait for anything to finish.
6592 * See checkjobs().
6593 *
6594 * Return code is normally -1, when the caller has to wait for children
6595 * to finish to determine the exit status of the pipe. If the pipe
6596 * is a simple builtin command, however, the action is done by the
6597 * time run_pipe returns, and the exit code is provided as the
6598 * return value.
6599 *
6600 * Returns -1 only if started some children. IOW: we have to
6601 * mask out retvals of builtins etc with 0xff!
6602 *
6603 * The only case when we do not need to [v]fork is when the pipe
6604 * is single, non-backgrounded, non-subshell command. Examples:
6605 * cmd ; ... { list } ; ...
6606 * cmd && ... { list } && ...
6607 * cmd || ... { list } || ...
6608 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6609 * or (if SH_STANDALONE) an applet, and we can run the { list }
6610 * with run_list. If it isn't one of these, we fork and exec cmd.
6611 *
6612 * Cases when we must fork:
6613 * non-single: cmd | cmd
6614 * backgrounded: cmd & { list } &
6615 * subshell: ( list ) [&]
6616 */
6617#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006618#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006619 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6620#endif
6621static int redirect_and_varexp_helper(char ***new_env_p,
6622 struct variable **old_vars_p,
6623 struct command *command,
6624 int squirrel[3],
6625 char **argv_expanded)
6626{
6627 /* setup_redirects acts on file descriptors, not FILEs.
6628 * This is perfect for work that comes after exec().
6629 * Is it really safe for inline use? Experimentally,
6630 * things seem to work. */
6631 int rcode = setup_redirects(command, squirrel);
6632 if (rcode == 0) {
6633 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6634 *new_env_p = new_env;
6635 dump_cmd_in_x_mode(new_env);
6636 dump_cmd_in_x_mode(argv_expanded);
6637 if (old_vars_p)
6638 *old_vars_p = set_vars_and_save_old(new_env);
6639 }
6640 return rcode;
6641}
6642static NOINLINE int run_pipe(struct pipe *pi)
6643{
6644 static const char *const null_ptr = NULL;
6645
6646 int cmd_no;
6647 int next_infd;
6648 struct command *command;
6649 char **argv_expanded;
6650 char **argv;
6651 /* it is not always needed, but we aim to smaller code */
6652 int squirrel[] = { -1, -1, -1 };
6653 int rcode;
6654
6655 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6656 debug_enter();
6657
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006658 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6659 * Result should be 3 lines: q w e, qwe, q w e
6660 */
6661 G.ifs = get_local_var_value("IFS");
6662 if (!G.ifs)
6663 G.ifs = defifs;
6664
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006665 IF_HUSH_JOB(pi->pgrp = -1;)
6666 pi->stopped_cmds = 0;
6667 command = &pi->cmds[0];
6668 argv_expanded = NULL;
6669
6670 if (pi->num_cmds != 1
6671 || pi->followup == PIPE_BG
6672 || command->cmd_type == CMD_SUBSHELL
6673 ) {
6674 goto must_fork;
6675 }
6676
6677 pi->alive_cmds = 1;
6678
6679 debug_printf_exec(": group:%p argv:'%s'\n",
6680 command->group, command->argv ? command->argv[0] : "NONE");
6681
6682 if (command->group) {
6683#if ENABLE_HUSH_FUNCTIONS
6684 if (command->cmd_type == CMD_FUNCDEF) {
6685 /* "executing" func () { list } */
6686 struct function *funcp;
6687
6688 funcp = new_function(command->argv[0]);
6689 /* funcp->name is already set to argv[0] */
6690 funcp->body = command->group;
6691# if !BB_MMU
6692 funcp->body_as_string = command->group_as_string;
6693 command->group_as_string = NULL;
6694# endif
6695 command->group = NULL;
6696 command->argv[0] = NULL;
6697 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6698 funcp->parent_cmd = command;
6699 command->child_func = funcp;
6700
6701 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6702 debug_leave();
6703 return EXIT_SUCCESS;
6704 }
6705#endif
6706 /* { list } */
6707 debug_printf("non-subshell group\n");
6708 rcode = 1; /* exitcode if redir failed */
6709 if (setup_redirects(command, squirrel) == 0) {
6710 debug_printf_exec(": run_list\n");
6711 rcode = run_list(command->group) & 0xff;
6712 }
6713 restore_redirects(squirrel);
6714 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6715 debug_leave();
6716 debug_printf_exec("run_pipe: return %d\n", rcode);
6717 return rcode;
6718 }
6719
6720 argv = command->argv ? command->argv : (char **) &null_ptr;
6721 {
6722 const struct built_in_command *x;
6723#if ENABLE_HUSH_FUNCTIONS
6724 const struct function *funcp;
6725#else
6726 enum { funcp = 0 };
6727#endif
6728 char **new_env = NULL;
6729 struct variable *old_vars = NULL;
6730
6731 if (argv[command->assignment_cnt] == NULL) {
6732 /* Assignments, but no command */
6733 /* Ensure redirects take effect (that is, create files).
6734 * Try "a=t >file" */
6735#if 0 /* A few cases in testsuite fail with this code. FIXME */
6736 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6737 /* Set shell variables */
6738 if (new_env) {
6739 argv = new_env;
6740 while (*argv) {
6741 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6742 /* Do we need to flag set_local_var() errors?
6743 * "assignment to readonly var" and "putenv error"
6744 */
6745 argv++;
6746 }
6747 }
6748 /* Redirect error sets $? to 1. Otherwise,
6749 * if evaluating assignment value set $?, retain it.
6750 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6751 if (rcode == 0)
6752 rcode = G.last_exitcode;
6753 /* Exit, _skipping_ variable restoring code: */
6754 goto clean_up_and_ret0;
6755
6756#else /* Older, bigger, but more correct code */
6757
6758 rcode = setup_redirects(command, squirrel);
6759 restore_redirects(squirrel);
6760 /* Set shell variables */
6761 if (G_x_mode)
6762 bb_putchar_stderr('+');
6763 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006764 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006765 if (G_x_mode)
6766 fprintf(stderr, " %s", p);
6767 debug_printf_exec("set shell var:'%s'->'%s'\n",
6768 *argv, p);
6769 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6770 /* Do we need to flag set_local_var() errors?
6771 * "assignment to readonly var" and "putenv error"
6772 */
6773 argv++;
6774 }
6775 if (G_x_mode)
6776 bb_putchar_stderr('\n');
6777 /* Redirect error sets $? to 1. Otherwise,
6778 * if evaluating assignment value set $?, retain it.
6779 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6780 if (rcode == 0)
6781 rcode = G.last_exitcode;
6782 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6783 debug_leave();
6784 debug_printf_exec("run_pipe: return %d\n", rcode);
6785 return rcode;
6786#endif
6787 }
6788
6789 /* Expand the rest into (possibly) many strings each */
6790 if (0) {}
6791#if ENABLE_HUSH_BASH_COMPAT
6792 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6793 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6794 }
6795#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006796 else {
6797 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6798 }
6799
6800 /* if someone gives us an empty string: `cmd with empty output` */
6801 if (!argv_expanded[0]) {
6802 free(argv_expanded);
6803 debug_leave();
6804 return G.last_exitcode;
6805 }
6806
6807 x = find_builtin(argv_expanded[0]);
6808#if ENABLE_HUSH_FUNCTIONS
6809 funcp = NULL;
6810 if (!x)
6811 funcp = find_function(argv_expanded[0]);
6812#endif
6813 if (x || funcp) {
6814 if (!funcp) {
6815 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6816 debug_printf("exec with redirects only\n");
6817 rcode = setup_redirects(command, NULL);
6818 goto clean_up_and_ret1;
6819 }
6820 }
6821 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6822 if (rcode == 0) {
6823 if (!funcp) {
6824 debug_printf_exec(": builtin '%s' '%s'...\n",
6825 x->b_cmd, argv_expanded[1]);
6826 rcode = x->b_function(argv_expanded) & 0xff;
6827 fflush_all();
6828 }
6829#if ENABLE_HUSH_FUNCTIONS
6830 else {
6831# if ENABLE_HUSH_LOCAL
6832 struct variable **sv;
6833 sv = G.shadowed_vars_pp;
6834 G.shadowed_vars_pp = &old_vars;
6835# endif
6836 debug_printf_exec(": function '%s' '%s'...\n",
6837 funcp->name, argv_expanded[1]);
6838 rcode = run_function(funcp, argv_expanded) & 0xff;
6839# if ENABLE_HUSH_LOCAL
6840 G.shadowed_vars_pp = sv;
6841# endif
6842 }
6843#endif
6844 }
6845 clean_up_and_ret:
6846 unset_vars(new_env);
6847 add_vars(old_vars);
6848/* clean_up_and_ret0: */
6849 restore_redirects(squirrel);
6850 clean_up_and_ret1:
6851 free(argv_expanded);
6852 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6853 debug_leave();
6854 debug_printf_exec("run_pipe return %d\n", rcode);
6855 return rcode;
6856 }
6857
6858 if (ENABLE_FEATURE_SH_STANDALONE) {
6859 int n = find_applet_by_name(argv_expanded[0]);
6860 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6861 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6862 if (rcode == 0) {
6863 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6864 argv_expanded[0], argv_expanded[1]);
6865 rcode = run_nofork_applet(n, argv_expanded);
6866 }
6867 goto clean_up_and_ret;
6868 }
6869 }
6870 /* It is neither builtin nor applet. We must fork. */
6871 }
6872
6873 must_fork:
6874 /* NB: argv_expanded may already be created, and that
6875 * might include `cmd` runs! Do not rerun it! We *must*
6876 * use argv_expanded if it's non-NULL */
6877
6878 /* Going to fork a child per each pipe member */
6879 pi->alive_cmds = 0;
6880 next_infd = 0;
6881
6882 cmd_no = 0;
6883 while (cmd_no < pi->num_cmds) {
6884 struct fd_pair pipefds;
6885#if !BB_MMU
6886 volatile nommu_save_t nommu_save;
6887 nommu_save.new_env = NULL;
6888 nommu_save.old_vars = NULL;
6889 nommu_save.argv = NULL;
6890 nommu_save.argv_from_re_execing = NULL;
6891#endif
6892 command = &pi->cmds[cmd_no];
6893 cmd_no++;
6894 if (command->argv) {
6895 debug_printf_exec(": pipe member '%s' '%s'...\n",
6896 command->argv[0], command->argv[1]);
6897 } else {
6898 debug_printf_exec(": pipe member with no argv\n");
6899 }
6900
6901 /* pipes are inserted between pairs of commands */
6902 pipefds.rd = 0;
6903 pipefds.wr = 1;
6904 if (cmd_no < pi->num_cmds)
6905 xpiped_pair(pipefds);
6906
6907 command->pid = BB_MMU ? fork() : vfork();
6908 if (!command->pid) { /* child */
6909#if ENABLE_HUSH_JOB
6910 disable_restore_tty_pgrp_on_exit();
6911 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6912
6913 /* Every child adds itself to new process group
6914 * with pgid == pid_of_first_child_in_pipe */
6915 if (G.run_list_level == 1 && G_interactive_fd) {
6916 pid_t pgrp;
6917 pgrp = pi->pgrp;
6918 if (pgrp < 0) /* true for 1st process only */
6919 pgrp = getpid();
6920 if (setpgid(0, pgrp) == 0
6921 && pi->followup != PIPE_BG
6922 && G_saved_tty_pgrp /* we have ctty */
6923 ) {
6924 /* We do it in *every* child, not just first,
6925 * to avoid races */
6926 tcsetpgrp(G_interactive_fd, pgrp);
6927 }
6928 }
6929#endif
6930 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6931 /* 1st cmd in backgrounded pipe
6932 * should have its stdin /dev/null'ed */
6933 close(0);
6934 if (open(bb_dev_null, O_RDONLY))
6935 xopen("/", O_RDONLY);
6936 } else {
6937 xmove_fd(next_infd, 0);
6938 }
6939 xmove_fd(pipefds.wr, 1);
6940 if (pipefds.rd > 1)
6941 close(pipefds.rd);
6942 /* Like bash, explicit redirects override pipes,
6943 * and the pipe fd is available for dup'ing. */
6944 if (setup_redirects(command, NULL))
6945 _exit(1);
6946
6947 /* Restore default handlers just prior to exec */
6948 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6949
6950 /* Stores to nommu_save list of env vars putenv'ed
6951 * (NOMMU, on MMU we don't need that) */
6952 /* cast away volatility... */
6953 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6954 /* pseudo_exec() does not return */
6955 }
6956
6957 /* parent or error */
6958#if ENABLE_HUSH_FAST
6959 G.count_SIGCHLD++;
6960//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6961#endif
6962 enable_restore_tty_pgrp_on_exit();
6963#if !BB_MMU
6964 /* Clean up after vforked child */
6965 free(nommu_save.argv);
6966 free(nommu_save.argv_from_re_execing);
6967 unset_vars(nommu_save.new_env);
6968 add_vars(nommu_save.old_vars);
6969#endif
6970 free(argv_expanded);
6971 argv_expanded = NULL;
6972 if (command->pid < 0) { /* [v]fork failed */
6973 /* Clearly indicate, was it fork or vfork */
6974 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6975 } else {
6976 pi->alive_cmds++;
6977#if ENABLE_HUSH_JOB
6978 /* Second and next children need to know pid of first one */
6979 if (pi->pgrp < 0)
6980 pi->pgrp = command->pid;
6981#endif
6982 }
6983
6984 if (cmd_no > 1)
6985 close(next_infd);
6986 if (cmd_no < pi->num_cmds)
6987 close(pipefds.wr);
6988 /* Pass read (output) pipe end to next iteration */
6989 next_infd = pipefds.rd;
6990 }
6991
6992 if (!pi->alive_cmds) {
6993 debug_leave();
6994 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6995 return 1;
6996 }
6997
6998 debug_leave();
6999 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7000 return -1;
7001}
7002
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007003/* NB: called by pseudo_exec, and therefore must not modify any
7004 * global data until exec/_exit (we can be a child after vfork!) */
7005static int run_list(struct pipe *pi)
7006{
7007#if ENABLE_HUSH_CASE
7008 char *case_word = NULL;
7009#endif
7010#if ENABLE_HUSH_LOOPS
7011 struct pipe *loop_top = NULL;
7012 char **for_lcur = NULL;
7013 char **for_list = NULL;
7014#endif
7015 smallint last_followup;
7016 smalluint rcode;
7017#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7018 smalluint cond_code = 0;
7019#else
7020 enum { cond_code = 0 };
7021#endif
7022#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02007023 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007024 smallint last_rword; /* ditto */
7025#endif
7026
7027 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7028 debug_enter();
7029
7030#if ENABLE_HUSH_LOOPS
7031 /* Check syntax for "for" */
Denys Vlasenko0d6a4ec2010-12-18 01:34:49 +01007032 {
7033 struct pipe *cpipe;
7034 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7035 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7036 continue;
7037 /* current word is FOR or IN (BOLD in comments below) */
7038 if (cpipe->next == NULL) {
7039 syntax_error("malformed for");
7040 debug_leave();
7041 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7042 return 1;
7043 }
7044 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7045 if (cpipe->next->res_word == RES_DO)
7046 continue;
7047 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7048 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7049 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7050 ) {
7051 syntax_error("malformed for");
7052 debug_leave();
7053 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7054 return 1;
7055 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007056 }
7057 }
7058#endif
7059
7060 /* Past this point, all code paths should jump to ret: label
7061 * in order to return, no direct "return" statements please.
7062 * This helps to ensure that no memory is leaked. */
7063
7064#if ENABLE_HUSH_JOB
7065 G.run_list_level++;
7066#endif
7067
7068#if HAS_KEYWORDS
7069 rword = RES_NONE;
7070 last_rword = RES_XXXX;
7071#endif
7072 last_followup = PIPE_SEQ;
7073 rcode = G.last_exitcode;
7074
7075 /* Go through list of pipes, (maybe) executing them. */
7076 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7077 if (G.flag_SIGINT)
7078 break;
7079
7080 IF_HAS_KEYWORDS(rword = pi->res_word;)
7081 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7082 rword, cond_code, last_rword);
7083#if ENABLE_HUSH_LOOPS
7084 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7085 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7086 ) {
7087 /* start of a loop: remember where loop starts */
7088 loop_top = pi;
7089 G.depth_of_loop++;
7090 }
7091#endif
7092 /* Still in the same "if...", "then..." or "do..." branch? */
7093 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7094 if ((rcode == 0 && last_followup == PIPE_OR)
7095 || (rcode != 0 && last_followup == PIPE_AND)
7096 ) {
7097 /* It is "<true> || CMD" or "<false> && CMD"
7098 * and we should not execute CMD */
7099 debug_printf_exec("skipped cmd because of || or &&\n");
7100 last_followup = pi->followup;
7101 continue;
7102 }
7103 }
7104 last_followup = pi->followup;
7105 IF_HAS_KEYWORDS(last_rword = rword;)
7106#if ENABLE_HUSH_IF
7107 if (cond_code) {
7108 if (rword == RES_THEN) {
7109 /* if false; then ... fi has exitcode 0! */
7110 G.last_exitcode = rcode = EXIT_SUCCESS;
7111 /* "if <false> THEN cmd": skip cmd */
7112 continue;
7113 }
7114 } else {
7115 if (rword == RES_ELSE || rword == RES_ELIF) {
7116 /* "if <true> then ... ELSE/ELIF cmd":
7117 * skip cmd and all following ones */
7118 break;
7119 }
7120 }
7121#endif
7122#if ENABLE_HUSH_LOOPS
7123 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7124 if (!for_lcur) {
7125 /* first loop through for */
7126
7127 static const char encoded_dollar_at[] ALIGN1 = {
7128 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7129 }; /* encoded representation of "$@" */
7130 static const char *const encoded_dollar_at_argv[] = {
7131 encoded_dollar_at, NULL
7132 }; /* argv list with one element: "$@" */
7133 char **vals;
7134
7135 vals = (char**)encoded_dollar_at_argv;
7136 if (pi->next->res_word == RES_IN) {
7137 /* if no variable values after "in" we skip "for" */
7138 if (!pi->next->cmds[0].argv) {
7139 G.last_exitcode = rcode = EXIT_SUCCESS;
7140 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7141 break;
7142 }
7143 vals = pi->next->cmds[0].argv;
7144 } /* else: "for var; do..." -> assume "$@" list */
7145 /* create list of variable values */
7146 debug_print_strings("for_list made from", vals);
7147 for_list = expand_strvec_to_strvec(vals);
7148 for_lcur = for_list;
7149 debug_print_strings("for_list", for_list);
7150 }
7151 if (!*for_lcur) {
7152 /* "for" loop is over, clean up */
7153 free(for_list);
7154 for_list = NULL;
7155 for_lcur = NULL;
7156 break;
7157 }
7158 /* Insert next value from for_lcur */
7159 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7160 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7161 continue;
7162 }
7163 if (rword == RES_IN) {
7164 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7165 }
7166 if (rword == RES_DONE) {
7167 continue; /* "done" has no cmds too */
7168 }
7169#endif
7170#if ENABLE_HUSH_CASE
7171 if (rword == RES_CASE) {
7172 case_word = expand_strvec_to_string(pi->cmds->argv);
7173 continue;
7174 }
7175 if (rword == RES_MATCH) {
7176 char **argv;
7177
7178 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7179 break;
7180 /* all prev words didn't match, does this one match? */
7181 argv = pi->cmds->argv;
7182 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007183 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007184 /* TODO: which FNM_xxx flags to use? */
7185 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7186 free(pattern);
7187 if (cond_code == 0) { /* match! we will execute this branch */
7188 free(case_word); /* make future "word)" stop */
7189 case_word = NULL;
7190 break;
7191 }
7192 argv++;
7193 }
7194 continue;
7195 }
7196 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7197 if (cond_code != 0)
7198 continue; /* not matched yet, skip this pipe */
7199 }
7200#endif
7201 /* Just pressing <enter> in shell should check for jobs.
7202 * OTOH, in non-interactive shell this is useless
7203 * and only leads to extra job checks */
7204 if (pi->num_cmds == 0) {
7205 if (G_interactive_fd)
7206 goto check_jobs_and_continue;
7207 continue;
7208 }
7209
7210 /* After analyzing all keywords and conditions, we decided
7211 * to execute this pipe. NB: have to do checkjobs(NULL)
7212 * after run_pipe to collect any background children,
7213 * even if list execution is to be stopped. */
7214 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7215 {
7216 int r;
7217#if ENABLE_HUSH_LOOPS
7218 G.flag_break_continue = 0;
7219#endif
7220 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7221 if (r != -1) {
7222 /* We ran a builtin, function, or group.
7223 * rcode is already known
7224 * and we don't need to wait for anything. */
7225 G.last_exitcode = rcode;
7226 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7227 check_and_run_traps(0);
7228#if ENABLE_HUSH_LOOPS
7229 /* Was it "break" or "continue"? */
7230 if (G.flag_break_continue) {
7231 smallint fbc = G.flag_break_continue;
7232 /* We might fall into outer *loop*,
7233 * don't want to break it too */
7234 if (loop_top) {
7235 G.depth_break_continue--;
7236 if (G.depth_break_continue == 0)
7237 G.flag_break_continue = 0;
7238 /* else: e.g. "continue 2" should *break* once, *then* continue */
7239 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7240 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7241 goto check_jobs_and_break;
7242 /* "continue": simulate end of loop */
7243 rword = RES_DONE;
7244 continue;
7245 }
7246#endif
7247#if ENABLE_HUSH_FUNCTIONS
7248 if (G.flag_return_in_progress == 1) {
7249 /* same as "goto check_jobs_and_break" */
7250 checkjobs(NULL);
7251 break;
7252 }
7253#endif
7254 } else if (pi->followup == PIPE_BG) {
7255 /* What does bash do with attempts to background builtins? */
7256 /* even bash 3.2 doesn't do that well with nested bg:
7257 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7258 * I'm NOT treating inner &'s as jobs */
7259 check_and_run_traps(0);
7260#if ENABLE_HUSH_JOB
7261 if (G.run_list_level == 1)
7262 insert_bg_job(pi);
7263#endif
7264 /* Last command's pid goes to $! */
7265 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7266 G.last_exitcode = rcode = EXIT_SUCCESS;
7267 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7268 } else {
7269#if ENABLE_HUSH_JOB
7270 if (G.run_list_level == 1 && G_interactive_fd) {
7271 /* Waits for completion, then fg's main shell */
7272 rcode = checkjobs_and_fg_shell(pi);
7273 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7274 check_and_run_traps(0);
7275 } else
7276#endif
7277 { /* This one just waits for completion */
7278 rcode = checkjobs(pi);
7279 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7280 check_and_run_traps(0);
7281 }
7282 G.last_exitcode = rcode;
7283 }
7284 }
7285
7286 /* Analyze how result affects subsequent commands */
7287#if ENABLE_HUSH_IF
7288 if (rword == RES_IF || rword == RES_ELIF)
7289 cond_code = rcode;
7290#endif
7291#if ENABLE_HUSH_LOOPS
7292 /* Beware of "while false; true; do ..."! */
7293 if (pi->next && pi->next->res_word == RES_DO) {
7294 if (rword == RES_WHILE) {
7295 if (rcode) {
7296 /* "while false; do...done" - exitcode 0 */
7297 G.last_exitcode = rcode = EXIT_SUCCESS;
7298 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7299 goto check_jobs_and_break;
7300 }
7301 }
7302 if (rword == RES_UNTIL) {
7303 if (!rcode) {
7304 debug_printf_exec(": until expr is true: breaking\n");
7305 check_jobs_and_break:
7306 checkjobs(NULL);
7307 break;
7308 }
7309 }
7310 }
7311#endif
7312
7313 check_jobs_and_continue:
7314 checkjobs(NULL);
7315 } /* for (pi) */
7316
7317#if ENABLE_HUSH_JOB
7318 G.run_list_level--;
7319#endif
7320#if ENABLE_HUSH_LOOPS
7321 if (loop_top)
7322 G.depth_of_loop--;
7323 free(for_list);
7324#endif
7325#if ENABLE_HUSH_CASE
7326 free(case_word);
7327#endif
7328 debug_leave();
7329 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7330 return rcode;
7331}
7332
7333/* Select which version we will use */
7334static int run_and_free_list(struct pipe *pi)
7335{
7336 int rcode = 0;
7337 debug_printf_exec("run_and_free_list entered\n");
Dan Fandrich85c62472010-11-20 13:05:17 -08007338 if (!G.o_opt[OPT_O_NOEXEC]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007339 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7340 rcode = run_list(pi);
7341 }
7342 /* free_pipe_list has the side effect of clearing memory.
7343 * In the long run that function can be merged with run_list,
7344 * but doing that now would hobble the debugging effort. */
7345 free_pipe_list(pi);
7346 debug_printf_exec("run_and_free_list return %d\n", rcode);
7347 return rcode;
7348}
7349
7350
Denis Vlasenkof9375282009-04-05 19:13:39 +00007351/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007352static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007353{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007354 unsigned sig;
7355 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007356 sigset_t old_blocked_set;
7357
7358 if (!G.inherited_set_is_saved) {
7359 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7360 G.inherited_set = G.blocked_set;
7361 }
7362 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007363
Denis Vlasenkof9375282009-04-05 19:13:39 +00007364 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007365 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007366 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007367 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007368 mask |= SPECIAL_JOB_SIGS;
7369 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007370 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007371
Denis Vlasenkof9375282009-04-05 19:13:39 +00007372 sig = 0;
7373 while (mask) {
7374 if (mask & 1)
7375 sigaddset(&G.blocked_set, sig);
7376 mask >>= 1;
7377 sig++;
7378 }
7379 sigdelset(&G.blocked_set, SIGCHLD);
7380
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007381 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7382 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7383
Denis Vlasenkof9375282009-04-05 19:13:39 +00007384 /* POSIX allows shell to re-enable SIGCHLD
7385 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007386#if ENABLE_HUSH_FAST
7387 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007388 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007389 signal(SIGCHLD, SIGCHLD_handler);
7390#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007391 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007392 signal(SIGCHLD, SIG_DFL);
7393#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007394
7395 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007396}
7397
7398#if ENABLE_HUSH_JOB
7399/* helper */
7400static void maybe_set_to_sigexit(int sig)
7401{
7402 void (*handler)(int);
7403 /* non_DFL_mask'ed signals are, well, masked,
7404 * no need to set handler for them.
7405 */
7406 if (!((G.non_DFL_mask >> sig) & 1)) {
7407 handler = signal(sig, sigexit);
7408 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7409 signal(sig, handler);
7410 }
7411}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007412/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007413static void set_fatal_handlers(void)
7414{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007415 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007416 if (HUSH_DEBUG) {
7417 maybe_set_to_sigexit(SIGILL );
7418 maybe_set_to_sigexit(SIGFPE );
7419 maybe_set_to_sigexit(SIGBUS );
7420 maybe_set_to_sigexit(SIGSEGV);
7421 maybe_set_to_sigexit(SIGTRAP);
7422 } /* else: hush is perfect. what SEGV? */
7423 maybe_set_to_sigexit(SIGABRT);
7424 /* bash 3.2 seems to handle these just like 'fatal' ones */
7425 maybe_set_to_sigexit(SIGPIPE);
7426 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007427 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007428 * if we aren't interactive... but in this case
7429 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007430 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007431 /*maybe_set_to_sigexit(SIGTERM);*/
7432 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007433}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007434#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007435
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007436static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007437{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007438 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007439 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007440 case 'n':
Dan Fandrich85c62472010-11-20 13:05:17 -08007441 G.o_opt[OPT_O_NOEXEC] = state;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007442 break;
7443 case 'x':
7444 IF_HUSH_MODE_X(G_x_mode = state;)
7445 break;
7446 case 'o':
7447 if (!o_opt) {
7448 /* "set -+o" without parameter.
7449 * in bash, set -o produces this output:
7450 * pipefail off
7451 * and set +o:
7452 * set +o pipefail
7453 * We always use the second form.
7454 */
7455 const char *p = o_opt_strings;
7456 idx = 0;
7457 while (*p) {
7458 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7459 idx++;
7460 p += strlen(p) + 1;
7461 }
7462 break;
7463 }
7464 idx = index_in_strings(o_opt_strings, o_opt);
7465 if (idx >= 0) {
7466 G.o_opt[idx] = state;
7467 break;
7468 }
7469 default:
7470 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007471 }
7472 return EXIT_SUCCESS;
7473}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007474
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007475int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007476int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007477{
7478 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007479 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007480 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007481 struct variable *cur_var;
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007482 struct variable *shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007483
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007484 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007485 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007486 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007487#if !BB_MMU
7488 G.argv0_for_re_execing = argv[0];
7489#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007490 /* Deal with HUSH_VERSION */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007491 shell_ver = xzalloc(sizeof(*shell_ver));
7492 shell_ver->flg_export = 1;
7493 shell_ver->flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007494 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007495 * therefore we xstrdup: */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007496 shell_ver->varstr = xstrdup(hush_version_str);
Denys Vlasenko605067b2010-09-06 12:10:51 +02007497 /* Create shell local variables from the values
7498 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007499 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007500 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007501 G.top_var = shell_ver;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007502 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007503 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007504 if (e) while (*e) {
7505 char *value = strchr(*e, '=');
7506 if (value) { /* paranoia */
7507 cur_var->next = xzalloc(sizeof(*cur_var));
7508 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007509 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007510 cur_var->max_len = strlen(*e);
7511 cur_var->flg_export = 1;
7512 }
7513 e++;
7514 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007515 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko75eb9d22010-12-21 21:18:12 +01007516 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7517 putenv(shell_ver->varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007518
7519 /* Export PWD */
7520 set_pwd_var(/*exp:*/ 1);
7521 /* bash also exports SHLVL and _,
7522 * and sets (but doesn't export) the following variables:
7523 * BASH=/bin/bash
7524 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7525 * BASH_VERSION='3.2.0(1)-release'
7526 * HOSTTYPE=i386
7527 * MACHTYPE=i386-pc-linux-gnu
7528 * OSTYPE=linux-gnu
7529 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007530 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007531 * EUID=<NNNNN>
7532 * UID=<NNNNN>
7533 * GROUPS=()
7534 * LINES=<NNN>
7535 * COLUMNS=<NNN>
7536 * BASH_ARGC=()
7537 * BASH_ARGV=()
7538 * BASH_LINENO=()
7539 * BASH_SOURCE=()
7540 * DIRSTACK=()
7541 * PIPESTATUS=([0]="0")
7542 * HISTFILE=/<xxx>/.bash_history
7543 * HISTFILESIZE=500
7544 * HISTSIZE=500
7545 * MAILCHECK=60
7546 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7547 * SHELL=/bin/bash
7548 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7549 * TERM=dumb
7550 * OPTERR=1
7551 * OPTIND=1
7552 * IFS=$' \t\n'
7553 * PS1='\s-\v\$ '
7554 * PS2='> '
7555 * PS4='+ '
7556 */
7557
Denis Vlasenko38f63192007-01-22 09:03:07 +00007558#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007559 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007560# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7561 {
7562 const char *hp = get_local_var_value("HISTFILE");
7563 if (!hp) {
7564 hp = get_local_var_value("HOME");
7565 if (hp) {
7566 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7567 //set_local_var(xasprintf("HISTFILE=%s", ...));
7568 }
7569 }
7570 }
7571# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007572#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007573
Denis Vlasenko87a86552008-07-29 19:43:10 +00007574 G.global_argc = argc;
7575 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007576 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007577 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007578
Denis Vlasenkoed782372009-04-10 00:45:02 +00007579 if (setjmp(die_jmp)) {
7580 /* xfunc has failed! die die die */
7581 /* no EXIT traps, this is an escape hatch! */
7582 G.exiting = 1;
7583 hush_exit(xfunc_error_retval);
7584 }
7585
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007586 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007587 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007588 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007589 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007590 * in order to intercept (more) signals.
7591 */
7592
7593 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007594 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007595 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007596 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007597 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007598#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007599 "<:$:R:V:"
7600# if ENABLE_HUSH_FUNCTIONS
7601 "F:"
7602# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007603#endif
7604 );
7605 if (opt <= 0)
7606 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007607 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007608 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007609 /* Possibilities:
7610 * sh ... -c 'script'
7611 * sh ... -c 'script' ARG0 [ARG1...]
7612 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007613 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007614 * "" needs to be replaced with NULL
7615 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007616 * Note: the form without ARG0 never happens:
7617 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007618 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007619 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007620 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007621 G.root_ppid = getppid();
7622 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007623 G.global_argv = argv + optind;
7624 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007625 if (builtin_argc) {
7626 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7627 const struct built_in_command *x;
7628
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007629 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007630 x = find_builtin(optarg);
7631 if (x) { /* paranoia */
7632 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7633 G.global_argv += builtin_argc;
7634 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007635 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007636 }
7637 goto final_return;
7638 }
7639 if (!G.global_argv[0]) {
7640 /* -c 'script' (no params): prevent empty $0 */
7641 G.global_argv--; /* points to argv[i] of 'script' */
7642 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007643 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007644 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007645 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007646 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007647 goto final_return;
7648 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007649 /* Well, we cannot just declare interactiveness,
7650 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007651 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007652 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007653 case 's':
7654 /* "-s" means "read from stdin", but this is how we always
7655 * operate, so simply do nothing here. */
7656 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007657#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007658 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007659 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007660 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007661 case '$': {
7662 unsigned long long empty_trap_mask;
7663
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007664 G.root_pid = bb_strtou(optarg, &optarg, 16);
7665 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007666 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7667 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007668 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7669 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007670 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007671 optarg++;
7672 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007673 optarg++;
7674 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7675 if (empty_trap_mask != 0) {
7676 int sig;
7677 init_sigmasks();
7678 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7679 for (sig = 1; sig < NSIG; sig++) {
7680 if (empty_trap_mask & (1LL << sig)) {
7681 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7682 sigaddset(&G.blocked_set, sig);
7683 }
7684 }
7685 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7686 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007687# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007688 optarg++;
7689 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007690# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007691 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007692 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007693 case 'R':
7694 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007695 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007696 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007697# if ENABLE_HUSH_FUNCTIONS
7698 case 'F': {
7699 struct function *funcp = new_function(optarg);
7700 /* funcp->name is already set to optarg */
7701 /* funcp->body is set to NULL. It's a special case. */
7702 funcp->body_as_string = argv[optind];
7703 optind++;
7704 break;
7705 }
7706# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007707#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007708 case 'n':
7709 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007710 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007711 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007712 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007713#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007714 fprintf(stderr, "Usage: sh [FILE]...\n"
7715 " or: sh -c command [args]...\n\n");
7716 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007717#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007718 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007719#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007720 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007721 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007722
Denys Vlasenkodea47882009-10-09 15:40:49 +02007723 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007724 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007725 G.root_ppid = getppid();
7726 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007727
7728 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007729 if (argv[0] && argv[0][0] == '-') {
7730 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007731 debug_printf("sourcing /etc/profile\n");
7732 input = fopen_for_read("/etc/profile");
7733 if (input != NULL) {
7734 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007735 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007736 parse_and_run_file(input);
7737 fclose(input);
7738 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007739 /* bash: after sourcing /etc/profile,
7740 * tries to source (in the given order):
7741 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007742 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007743 * bash also sources ~/.bash_logout on exit.
7744 * If called as sh, skips .bash_XXX files.
7745 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007746 }
7747
Denis Vlasenkof9375282009-04-05 19:13:39 +00007748 if (argv[optind]) {
7749 FILE *input;
7750 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007751 * "bash <script>" (which is never interactive (unless -i?))
7752 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007753 * If called as sh, does the same but with $ENV.
7754 */
7755 debug_printf("running script '%s'\n", argv[optind]);
7756 G.global_argv = argv + optind;
7757 G.global_argc = argc - optind;
7758 input = xfopen_for_read(argv[optind]);
7759 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007760 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007761 parse_and_run_file(input);
7762#if ENABLE_FEATURE_CLEAN_UP
7763 fclose(input);
7764#endif
7765 goto final_return;
7766 }
7767
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007768 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007769 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007770 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007771
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007772 /* A shell is interactive if the '-i' flag was given,
7773 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007774 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007775 * no arguments remaining or the -s flag given
7776 * standard input is a terminal
7777 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007778 * Refer to Posix.2, the description of the 'sh' utility.
7779 */
7780#if ENABLE_HUSH_JOB
7781 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007782 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7783 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7784 if (G_saved_tty_pgrp < 0)
7785 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007786
7787 /* try to dup stdin to high fd#, >= 255 */
7788 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7789 if (G_interactive_fd < 0) {
7790 /* try to dup to any fd */
7791 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007792 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007793 /* give up */
7794 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007795 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007796 }
7797 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007798// TODO: track & disallow any attempts of user
7799// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007800 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007801 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007802 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007803 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007804
Mike Frysinger38478a62009-05-20 04:48:06 -04007805 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007806 /* If we were run as 'hush &', sleep until we are
7807 * in the foreground (tty pgrp == our pgrp).
7808 * If we get started under a job aware app (like bash),
7809 * make sure we are now in charge so we don't fight over
7810 * who gets the foreground */
7811 while (1) {
7812 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007813 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7814 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007815 break;
7816 /* send TTIN to ourself (should stop us) */
7817 kill(- shell_pgrp, SIGTTIN);
7818 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007819 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007820
Denis Vlasenkof9375282009-04-05 19:13:39 +00007821 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007822 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007823
Mike Frysinger38478a62009-05-20 04:48:06 -04007824 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007825 /* Set other signals to restore saved_tty_pgrp */
7826 set_fatal_handlers();
7827 /* Put ourselves in our own process group
7828 * (bash, too, does this only if ctty is available) */
7829 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7830 /* Grab control of the terminal */
7831 tcsetpgrp(G_interactive_fd, getpid());
7832 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007833 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007834 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007835 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007836 } else {
7837 init_sigmasks();
7838 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007839#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007840 /* No job control compiled in, only prompt/line editing */
7841 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007842 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7843 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007844 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007845 G_interactive_fd = dup(STDIN_FILENO);
7846 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007847 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007848 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007849 }
7850 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007851 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007852 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007853 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007854 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007855#else
7856 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007857 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007858#endif
7859 /* bash:
7860 * if interactive but not a login shell, sources ~/.bashrc
7861 * (--norc turns this off, --rcfile <file> overrides)
7862 */
7863
7864 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007865 /* note: ash and hush share this string */
7866 printf("\n\n%s %s\n"
7867 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7868 "\n",
7869 bb_banner,
7870 "hush - the humble shell"
7871 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007872 }
7873
Denis Vlasenkof9375282009-04-05 19:13:39 +00007874 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007875
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007876 final_return:
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007877 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007878}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007879
7880
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007881#if ENABLE_MSH
7882int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7883int msh_main(int argc, char **argv)
7884{
7885 //bb_error_msg("msh is deprecated, please use hush instead");
7886 return hush_main(argc, argv);
7887}
7888#endif
7889
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007890
7891/*
7892 * Built-ins
7893 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007894static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007895{
7896 return 0;
7897}
7898
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007899static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007900{
7901 int argc = 0;
7902 while (*argv) {
7903 argc++;
7904 argv++;
7905 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007906 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007907}
7908
7909static int FAST_FUNC builtin_test(char **argv)
7910{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007911 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007912}
7913
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007914static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007915{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007916 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007917}
7918
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007919#if ENABLE_PRINTF
7920static int FAST_FUNC builtin_printf(char **argv)
7921{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007922 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007923}
7924#endif
7925
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007926static char **skip_dash_dash(char **argv)
7927{
7928 argv++;
7929 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7930 argv++;
7931 return argv;
7932}
7933
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007934static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007935{
7936 int rcode = EXIT_SUCCESS;
7937
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007938 argv = skip_dash_dash(argv);
7939 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007940 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007941 /* bash:
7942 * eval "echo Hi; done" ("done" is syntax error):
7943 * "echo Hi" will not execute too.
7944 */
7945 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007946 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007947 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007948 }
7949 return rcode;
7950}
7951
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007952static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007953{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007954 const char *newdir;
7955
7956 argv = skip_dash_dash(argv);
7957 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007958 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007959 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007960 * bash says "bash: cd: HOME not set" and does nothing
7961 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007962 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007963 const char *home = get_local_var_value("HOME");
7964 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007965 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007966 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007967 /* Mimic bash message exactly */
7968 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007969 return EXIT_FAILURE;
7970 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007971 /* Read current dir (get_cwd(1) is inside) and set PWD.
7972 * Note: do not enforce exporting. If PWD was unset or unexported,
7973 * set it again, but do not export. bash does the same.
7974 */
7975 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007976 return EXIT_SUCCESS;
7977}
7978
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007979static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007980{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007981 argv = skip_dash_dash(argv);
7982 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007983 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007984
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007985 /* Careful: we can end up here after [v]fork. Do not restore
7986 * tty pgrp then, only top-level shell process does that */
7987 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7988 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7989
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007990 /* TODO: if exec fails, bash does NOT exit! We do.
7991 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7992 * and tcsetpgrp, and this is inherently racy.
7993 */
7994 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007995}
7996
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007997static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007998{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007999 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00008000
8001 /* interactive bash:
8002 * # trap "echo EEE" EXIT
8003 * # exit
8004 * exit
8005 * There are stopped jobs.
8006 * (if there are _stopped_ jobs, running ones don't count)
8007 * # exit
8008 * exit
8009 # EEE (then bash exits)
8010 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02008011 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00008012 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00008013
8014 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008015 argv = skip_dash_dash(argv);
8016 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008017 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008018 /* mimic bash: exit 123abc == exit 255 + error msg */
8019 xfunc_error_retval = 255;
8020 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008021 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008022}
8023
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008024static void print_escaped(const char *s)
8025{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008026 if (*s == '\'')
8027 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008028 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008029 const char *p = strchrnul(s, '\'');
8030 /* print 'xxxx', possibly just '' */
8031 printf("'%.*s'", (int)(p - s), s);
8032 if (*p == '\0')
8033 break;
8034 s = p;
8035 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008036 /* s points to '; print "'''...'''" */
8037 putchar('"');
8038 do putchar('\''); while (*++s == '\'');
8039 putchar('"');
8040 } while (*s);
8041}
8042
Denys Vlasenko295fef82009-06-03 12:47:26 +02008043#if !ENABLE_HUSH_LOCAL
8044#define helper_export_local(argv, exp, lvl) \
8045 helper_export_local(argv, exp)
8046#endif
8047static void helper_export_local(char **argv, int exp, int lvl)
8048{
8049 do {
8050 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008051 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008052
8053 /* So far we do not check that name is valid (TODO?) */
8054
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008055 if (*name_end == '\0') {
8056 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008057
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008058 vpp = get_ptr_to_local_var(name, name_end - name);
8059 var = vpp ? *vpp : NULL;
8060
Denys Vlasenko295fef82009-06-03 12:47:26 +02008061 if (exp == -1) { /* unexporting? */
8062 /* export -n NAME (without =VALUE) */
8063 if (var) {
8064 var->flg_export = 0;
8065 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8066 unsetenv(name);
8067 } /* else: export -n NOT_EXISTING_VAR: no-op */
8068 continue;
8069 }
8070 if (exp == 1) { /* exporting? */
8071 /* export NAME (without =VALUE) */
8072 if (var) {
8073 var->flg_export = 1;
8074 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8075 putenv(var->varstr);
8076 continue;
8077 }
8078 }
8079 /* Exporting non-existing variable.
8080 * bash does not put it in environment,
8081 * but remembers that it is exported,
8082 * and does put it in env when it is set later.
8083 * We just set it to "" and export. */
8084 /* Or, it's "local NAME" (without =VALUE).
8085 * bash sets the value to "". */
8086 name = xasprintf("%s=", name);
8087 } else {
8088 /* (Un)exporting/making local NAME=VALUE */
8089 name = xstrdup(name);
8090 }
8091 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8092 } while (*++argv);
8093}
8094
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008095static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008096{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008097 unsigned opt_unexport;
8098
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008099#if ENABLE_HUSH_EXPORT_N
8100 /* "!": do not abort on errors */
8101 opt_unexport = getopt32(argv, "!n");
8102 if (opt_unexport == (uint32_t)-1)
8103 return EXIT_FAILURE;
8104 argv += optind;
8105#else
8106 opt_unexport = 0;
8107 argv++;
8108#endif
8109
8110 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008111 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008112 if (e) {
8113 while (*e) {
8114#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008115 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008116#else
8117 /* ash emits: export VAR='VAL'
8118 * bash: declare -x VAR="VAL"
8119 * we follow ash example */
8120 const char *s = *e++;
8121 const char *p = strchr(s, '=');
8122
8123 if (!p) /* wtf? take next variable */
8124 continue;
8125 /* export var= */
8126 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008127 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008128 putchar('\n');
8129#endif
8130 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008131 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008132 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008133 return EXIT_SUCCESS;
8134 }
8135
Denys Vlasenko295fef82009-06-03 12:47:26 +02008136 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008137
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008138 return EXIT_SUCCESS;
8139}
8140
Denys Vlasenko295fef82009-06-03 12:47:26 +02008141#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008142static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008143{
8144 if (G.func_nest_level == 0) {
8145 bb_error_msg("%s: not in a function", argv[0]);
8146 return EXIT_FAILURE; /* bash compat */
8147 }
8148 helper_export_local(argv, 0, G.func_nest_level);
8149 return EXIT_SUCCESS;
8150}
8151#endif
8152
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008153static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008154{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008155 int sig;
8156 char *new_cmd;
8157
8158 if (!G.traps)
8159 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8160
8161 argv++;
8162 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008163 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008164 /* No args: print all trapped */
8165 for (i = 0; i < NSIG; ++i) {
8166 if (G.traps[i]) {
8167 printf("trap -- ");
8168 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008169 /* note: bash adds "SIG", but only if invoked
8170 * as "bash". If called as "sh", or if set -o posix,
8171 * then it prints short signal names.
8172 * We are printing short names: */
8173 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008174 }
8175 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008176 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008177 return EXIT_SUCCESS;
8178 }
8179
8180 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008181 /* If first arg is a number: reset all specified signals */
8182 sig = bb_strtou(*argv, NULL, 10);
8183 if (errno == 0) {
8184 int ret;
8185 process_sig_list:
8186 ret = EXIT_SUCCESS;
8187 while (*argv) {
8188 sig = get_signum(*argv++);
8189 if (sig < 0 || sig >= NSIG) {
8190 ret = EXIT_FAILURE;
8191 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008192 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008193 continue;
8194 }
8195
8196 free(G.traps[sig]);
8197 G.traps[sig] = xstrdup(new_cmd);
8198
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008199 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008200 get_signame(sig), sig, G.traps[sig]);
8201
8202 /* There is no signal for 0 (EXIT) */
8203 if (sig == 0)
8204 continue;
8205
8206 if (new_cmd) {
8207 sigaddset(&G.blocked_set, sig);
8208 } else {
8209 /* There was a trap handler, we are removing it
8210 * (if sig has non-DFL handling,
8211 * we don't need to do anything) */
8212 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8213 continue;
8214 sigdelset(&G.blocked_set, sig);
8215 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008216 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008217 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008218 return ret;
8219 }
8220
8221 if (!argv[1]) { /* no second arg */
8222 bb_error_msg("trap: invalid arguments");
8223 return EXIT_FAILURE;
8224 }
8225
8226 /* First arg is "-": reset all specified to default */
8227 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8228 /* Everything else: set arg as signal handler
8229 * (includes "" case, which ignores signal) */
8230 if (argv[0][0] == '-') {
8231 if (argv[0][1] == '\0') { /* "-" */
8232 /* new_cmd remains NULL: "reset these sigs" */
8233 goto reset_traps;
8234 }
8235 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8236 argv++;
8237 }
8238 /* else: "-something", no special meaning */
8239 }
8240 new_cmd = *argv;
8241 reset_traps:
8242 argv++;
8243 goto process_sig_list;
8244}
8245
Mike Frysinger93cadc22009-05-27 17:06:25 -04008246/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008247static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008248{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008249 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008250
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008251 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008252 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008253 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008254
8255 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008256 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008257 type = "an alias";*/
8258#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008259 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008260 type = "a function";
8261#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008262 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008263 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008264 else if ((path = find_in_path(*argv)) != NULL)
8265 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008266 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008267 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008268 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008269 continue;
8270 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008271
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008272 printf("%s is %s\n", *argv, type);
8273 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008274 }
8275
8276 return ret;
8277}
8278
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008279#if ENABLE_HUSH_JOB
8280/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008281static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008282{
8283 int i, jobnum;
8284 struct pipe *pi;
8285
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008286 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008287 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008288
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008289 /* If they gave us no args, assume they want the last backgrounded task */
8290 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008291 for (pi = G.job_list; pi; pi = pi->next) {
8292 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008293 goto found;
8294 }
8295 }
8296 bb_error_msg("%s: no current job", argv[0]);
8297 return EXIT_FAILURE;
8298 }
8299 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8300 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8301 return EXIT_FAILURE;
8302 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008303 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008304 if (pi->jobid == jobnum) {
8305 goto found;
8306 }
8307 }
8308 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8309 return EXIT_FAILURE;
8310 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008311 /* TODO: bash prints a string representation
8312 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008313 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008314 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008315 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008316 }
8317
8318 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008319 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8320 for (i = 0; i < pi->num_cmds; i++) {
8321 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8322 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008323 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008324 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008325
8326 i = kill(- pi->pgrp, SIGCONT);
8327 if (i < 0) {
8328 if (errno == ESRCH) {
8329 delete_finished_bg_job(pi);
8330 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008331 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008332 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008333 }
8334
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008335 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008336 remove_bg_job(pi);
8337 return checkjobs_and_fg_shell(pi);
8338 }
8339 return EXIT_SUCCESS;
8340}
8341#endif
8342
8343#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008344static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008345{
8346 const struct built_in_command *x;
8347
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008348 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008349 "Built-in commands:\n"
8350 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008351 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008352 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008353 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008354 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008355 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008356 return EXIT_SUCCESS;
8357}
8358#endif
8359
8360#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008361static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008362{
8363 struct pipe *job;
8364 const char *status_string;
8365
Denis Vlasenko87a86552008-07-29 19:43:10 +00008366 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008367 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008368 status_string = "Stopped";
8369 else
8370 status_string = "Running";
8371
8372 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8373 }
8374 return EXIT_SUCCESS;
8375}
8376#endif
8377
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008378#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008379static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008380{
8381 void *p;
8382 unsigned long l;
8383
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008384# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008385 /* Optional. Reduces probability of false positives */
8386 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008387# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008388 /* Crude attempt to find where "free memory" starts,
8389 * sans fragmentation. */
8390 p = malloc(240);
8391 l = (unsigned long)p;
8392 free(p);
8393 p = malloc(3400);
8394 if (l < (unsigned long)p) l = (unsigned long)p;
8395 free(p);
8396
8397 if (!G.memleak_value)
8398 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008399
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008400 l -= G.memleak_value;
8401 if ((long)l < 0)
8402 l = 0;
8403 l /= 1024;
8404 if (l > 127)
8405 l = 127;
8406
8407 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8408 return l;
8409}
8410#endif
8411
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008412static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008413{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008414 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008415 return EXIT_SUCCESS;
8416}
8417
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008418static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008419{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008420 const char *r;
8421 char *opt_n = NULL;
8422 char *opt_p = NULL;
8423 char *opt_t = NULL;
8424 char *opt_u = NULL;
8425 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008426
Denys Vlasenko03dad222010-01-12 23:29:57 +01008427 /* "!": do not abort on errors.
8428 * Option string must start with "sr" to match BUILTIN_READ_xxx
8429 */
8430 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8431 if (read_flags == (uint32_t)-1)
8432 return EXIT_FAILURE;
8433 argv += optind;
8434
8435 r = shell_builtin_read(set_local_var_from_halves,
8436 argv,
8437 get_local_var_value("IFS"), /* can be NULL */
8438 read_flags,
8439 opt_n,
8440 opt_p,
8441 opt_t,
8442 opt_u
8443 );
8444
8445 if ((uintptr_t)r > 1) {
8446 bb_error_msg("%s", r);
8447 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008448 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008449
Denys Vlasenko03dad222010-01-12 23:29:57 +01008450 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008451}
8452
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008453/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8454 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008455 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008456 * set [-abCefhmnuvx] [-o option] [argument...]
8457 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008458 * set -- [argument...]
8459 * set -o
8460 * set +o
8461 * Implementations shall support the options in both their hyphen and
8462 * plus-sign forms. These options can also be specified as options to sh.
8463 * Examples:
8464 * Write out all variables and their values: set
8465 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8466 * Turn on the -x and -v options: set -xv
8467 * Unset all positional parameters: set --
8468 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8469 * Set the positional parameters to the expansion of x, even if x expands
8470 * with a leading '-' or '+': set -- $x
8471 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008472 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008473 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008474static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008475{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008476 int n;
8477 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008478 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008479
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008480 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008481 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008482 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008483 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008484 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008485 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008486
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008487 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008488 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008489 ++argv;
8490 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008491 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008492 if (arg[0] != '+' && arg[0] != '-')
8493 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008494 for (n = 1; arg[n]; ++n) {
8495 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008496 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008497 if (arg[n] == 'o' && argv[1])
8498 argv++;
8499 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008500 } while ((arg = *++argv) != NULL);
8501 /* Now argv[0] is 1st argument */
8502
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008503 if (arg == NULL)
8504 return EXIT_SUCCESS;
8505 set_argv:
8506
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008507 /* NB: G.global_argv[0] ($0) is never freed/changed */
8508 g_argv = G.global_argv;
8509 if (G.global_args_malloced) {
8510 pp = g_argv;
8511 while (*++pp)
8512 free(*pp);
8513 g_argv[1] = NULL;
8514 } else {
8515 G.global_args_malloced = 1;
8516 pp = xzalloc(sizeof(pp[0]) * 2);
8517 pp[0] = g_argv[0]; /* retain $0 */
8518 g_argv = pp;
8519 }
8520 /* This realloc's G.global_argv */
8521 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8522
8523 n = 1;
8524 while (*++pp)
8525 n++;
8526 G.global_argc = n;
8527
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008528 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008529
8530 /* Nothing known, so abort */
8531 error:
8532 bb_error_msg("set: %s: invalid option", arg);
8533 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008534}
8535
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008536static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008537{
8538 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008539 argv = skip_dash_dash(argv);
8540 if (argv[0]) {
8541 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008542 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008543 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008544 if (G.global_args_malloced) {
8545 int m = 1;
8546 while (m <= n)
8547 free(G.global_argv[m++]);
8548 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008549 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008550 memmove(&G.global_argv[1], &G.global_argv[n+1],
8551 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008552 return EXIT_SUCCESS;
8553 }
8554 return EXIT_FAILURE;
8555}
8556
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008557static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008558{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008559 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008560 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008561 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008562#if ENABLE_HUSH_FUNCTIONS
8563 smallint sv_flg;
8564#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008565
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008566 argv = skip_dash_dash(argv);
8567 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008568 if (!filename) {
8569 /* bash says: "bash: .: filename argument required" */
8570 return 2; /* bash compat */
8571 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008572 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008573 if (!strchr(filename, '/')) {
8574 arg_path = find_in_path(filename);
8575 if (arg_path)
8576 filename = arg_path;
8577 }
8578 input = fopen_or_warn(filename, "r");
8579 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008580 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008581 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008582 return EXIT_FAILURE;
8583 }
8584 close_on_exec_on(fileno(input));
8585
Mike Frysinger885b6f22009-04-18 21:04:25 +00008586#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008587 sv_flg = G.flag_return_in_progress;
8588 /* "we are inside sourced file, ok to use return" */
8589 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008590#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008591 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008592
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008593 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008594 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008595
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008596 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008597#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008598 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008599#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008600
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008601 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008602}
8603
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008604static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008605{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008606 int rc;
8607 mode_t mask;
8608
8609 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008610 argv = skip_dash_dash(argv);
8611 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008612 mode_t old_mask = mask;
8613
8614 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008615 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008616 mask ^= 0777;
8617 if (rc == 0) {
8618 mask = old_mask;
8619 /* bash messages:
8620 * bash: umask: 'q': invalid symbolic mode operator
8621 * bash: umask: 999: octal number out of range
8622 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008623 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008624 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008625 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008626 rc = 1;
8627 /* Mimic bash */
8628 printf("%04o\n", (unsigned) mask);
8629 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008630 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008631 umask(mask);
8632
8633 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008634}
8635
Mike Frysingerd690f682009-03-30 06:50:54 +00008636/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008637static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008638{
Mike Frysingerd690f682009-03-30 06:50:54 +00008639 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008640 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008641
Denis Vlasenko28e67962009-04-26 23:22:40 +00008642 /* "!": do not abort on errors */
8643 /* "+": stop at 1st non-option */
8644 opts = getopt32(argv, "!+vf");
8645 if (opts == (unsigned)-1)
8646 return EXIT_FAILURE;
8647 if (opts == 3) {
8648 bb_error_msg("unset: -v and -f are exclusive");
8649 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008650 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008651 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008652
8653 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008654 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008655 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008656 if (unset_local_var(*argv)) {
8657 /* unset <nonexistent_var> doesn't fail.
8658 * Error is when one tries to unset RO var.
8659 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008660 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008661 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008662 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008663#if ENABLE_HUSH_FUNCTIONS
8664 else {
8665 unset_func(*argv);
8666 }
8667#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008668 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008669 }
8670 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008671}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008672
Mike Frysinger56bdea12009-03-28 20:01:58 +00008673/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008674static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008675{
8676 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008677 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008678
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008679 argv = skip_dash_dash(argv);
8680 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008681 /* Don't care about wait results */
8682 /* Note 1: must wait until there are no more children */
8683 /* Note 2: must be interruptible */
8684 /* Examples:
8685 * $ sleep 3 & sleep 6 & wait
8686 * [1] 30934 sleep 3
8687 * [2] 30935 sleep 6
8688 * [1] Done sleep 3
8689 * [2] Done sleep 6
8690 * $ sleep 3 & sleep 6 & wait
8691 * [1] 30936 sleep 3
8692 * [2] 30937 sleep 6
8693 * [1] Done sleep 3
8694 * ^C <-- after ~4 sec from keyboard
8695 * $
8696 */
8697 sigaddset(&G.blocked_set, SIGCHLD);
8698 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8699 while (1) {
8700 checkjobs(NULL);
8701 if (errno == ECHILD)
8702 break;
8703 /* Wait for SIGCHLD or any other signal of interest */
8704 /* sigtimedwait with infinite timeout: */
8705 sig = sigwaitinfo(&G.blocked_set, NULL);
8706 if (sig > 0) {
8707 sig = check_and_run_traps(sig);
8708 if (sig && sig != SIGCHLD) { /* see note 2 */
8709 ret = 128 + sig;
8710 break;
8711 }
8712 }
8713 }
8714 sigdelset(&G.blocked_set, SIGCHLD);
8715 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8716 return ret;
8717 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008718
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008719 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008720 while (*argv) {
8721 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008722 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008723 /* mimic bash message */
8724 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008725 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008726 }
8727 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008728 if (WIFSIGNALED(status))
8729 ret = 128 + WTERMSIG(status);
8730 else if (WIFEXITED(status))
8731 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008732 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008733 ret = EXIT_FAILURE;
8734 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008735 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008736 ret = 127;
8737 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008738 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008739 }
8740
8741 return ret;
8742}
8743
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008744#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8745static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8746{
8747 if (argv[1]) {
8748 def = bb_strtou(argv[1], NULL, 10);
8749 if (errno || def < def_min || argv[2]) {
8750 bb_error_msg("%s: bad arguments", argv[0]);
8751 def = UINT_MAX;
8752 }
8753 }
8754 return def;
8755}
8756#endif
8757
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008758#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008759static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008760{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008761 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008762 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008763 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008764 return EXIT_SUCCESS; /* bash compat */
8765 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008766 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008767
8768 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8769 if (depth == UINT_MAX)
8770 G.flag_break_continue = BC_BREAK;
8771 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008772 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008773
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008774 return EXIT_SUCCESS;
8775}
8776
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008777static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008778{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008779 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8780 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008781}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008782#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008783
8784#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008785static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008786{
8787 int rc;
8788
8789 if (G.flag_return_in_progress != -1) {
8790 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8791 return EXIT_FAILURE; /* bash compat */
8792 }
8793
8794 G.flag_return_in_progress = 1;
8795
8796 /* bash:
8797 * out of range: wraps around at 256, does not error out
8798 * non-numeric param:
8799 * f() { false; return qwe; }; f; echo $?
8800 * bash: return: qwe: numeric argument required <== we do this
8801 * 255 <== we also do this
8802 */
8803 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8804 return rc;
8805}
8806#endif