blob: a710f7cd9f2537fcb7280945ed7dd7b8425567a0 [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 Vlasenko27726cb2009-09-12 14:48:33 +020085#include <malloc.h> /* for malloc_trim */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000086#include <glob.h>
87/* #include <dmalloc.h> */
88#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000089# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000090#endif
Denys Vlasenko03dad222010-01-12 23:29:57 +010091
92#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000093#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000094#include "match.h"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +020095#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +020096# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +020097#else
98# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +020099#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000100#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200101# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +0000102#endif
Mike Frysinger98c52642009-04-02 10:02:37 +0000103
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200104//applet:IF_HUSH(APPLET(hush, _BB_DIR_BIN, _BB_SUID_DROP))
105//applet:IF_MSH(APPLET(msh, _BB_DIR_BIN, _BB_SUID_DROP))
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200106//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
107//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
108
109//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
110//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
111
112//config:config HUSH
113//config: bool "hush"
114//config: default y
115//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200116//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200117//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
118//config: case/esac. Redirections, here documents, $((arithmetic))
119//config: and functions are supported.
120//config:
121//config: It will compile and work on no-mmu systems.
122//config:
Denys Vlasenkoe2069fb2010-10-04 00:01:47 +0200123//config: It does not handle select, aliases, tilde expansion,
124//config: &>file and >&file redirection of stdout+stderr.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200125//config:
126//config:config HUSH_BASH_COMPAT
127//config: bool "bash-compatible extensions"
128//config: default y
129//config: depends on HUSH
130//config: help
131//config: Enable bash-compatible extensions.
132//config:
Denys Vlasenko9e800222010-10-03 14:28:04 +0200133//config:config HUSH_BRACE_EXPANSION
134//config: bool "Brace expansion"
135//config: default y
136//config: depends on HUSH_BASH_COMPAT
137//config: help
138//config: Enable {abc,def} extension.
139//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200140//config:config HUSH_HELP
141//config: bool "help builtin"
142//config: default y
143//config: depends on HUSH
144//config: help
145//config: Enable help builtin in hush. Code size + ~1 kbyte.
146//config:
147//config:config HUSH_INTERACTIVE
148//config: bool "Interactive mode"
149//config: default y
150//config: depends on HUSH
151//config: help
152//config: Enable interactive mode (prompt and command editing).
153//config: Without this, hush simply reads and executes commands
154//config: from stdin just like a shell script from a file.
155//config: No prompt, no PS1/PS2 magic shell variables.
156//config:
Denys Vlasenko99862cb2010-09-12 17:34:13 +0200157//config:config HUSH_SAVEHISTORY
158//config: bool "Save command history to .hush_history"
159//config: default y
160//config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
161//config: help
162//config: Enable history saving in hush.
163//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200164//config:config HUSH_JOB
165//config: bool "Job control"
166//config: default y
167//config: depends on HUSH_INTERACTIVE
168//config: help
169//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
170//config: command (not entire shell), fg/bg builtins work. Without this option,
171//config: "cmd &" still works by simply spawning a process and immediately
172//config: prompting for next command (or executing next command in a script),
173//config: but no separate process group is formed.
174//config:
175//config:config HUSH_TICK
176//config: bool "Process substitution"
177//config: default y
178//config: depends on HUSH
179//config: help
180//config: Enable process substitution `command` and $(command) in hush.
181//config:
182//config:config HUSH_IF
183//config: bool "Support if/then/elif/else/fi"
184//config: default y
185//config: depends on HUSH
186//config: help
187//config: Enable if/then/elif/else/fi in hush.
188//config:
189//config:config HUSH_LOOPS
190//config: bool "Support for, while and until loops"
191//config: default y
192//config: depends on HUSH
193//config: help
194//config: Enable for, while and until loops in hush.
195//config:
196//config:config HUSH_CASE
197//config: bool "Support case ... esac statement"
198//config: default y
199//config: depends on HUSH
200//config: help
201//config: Enable case ... esac statement in hush. +400 bytes.
202//config:
203//config:config HUSH_FUNCTIONS
204//config: bool "Support funcname() { commands; } syntax"
205//config: default y
206//config: depends on HUSH
207//config: help
208//config: Enable support for shell functions in hush. +800 bytes.
209//config:
210//config:config HUSH_LOCAL
211//config: bool "Support local builtin"
212//config: default y
213//config: depends on HUSH_FUNCTIONS
214//config: help
215//config: Enable support for local variables in functions.
216//config:
217//config:config HUSH_RANDOM_SUPPORT
218//config: bool "Pseudorandom generator and $RANDOM variable"
219//config: default y
220//config: depends on HUSH
221//config: help
222//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
223//config: Each read of "$RANDOM" will generate a new pseudorandom value.
224//config:
225//config:config HUSH_EXPORT_N
226//config: bool "Support 'export -n' option"
227//config: default y
228//config: depends on HUSH
229//config: help
230//config: export -n unexports variables. It is a bash extension.
231//config:
232//config:config HUSH_MODE_X
233//config: bool "Support 'hush -x' option and 'set -x' command"
234//config: default y
235//config: depends on HUSH
236//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200237//config: This instructs hush to print commands before execution.
238//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200239//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200240//config:config MSH
241//config: bool "msh (deprecated: aliased to hush)"
242//config: default n
243//config: select HUSH
244//config: help
245//config: msh is deprecated and will be removed, please migrate to hush.
246//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200247
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100248/* -i (interactive) and -s (read stdin) are also accepted,
249 * but currently do nothing, therefore aren't shown in help.
250 * NOMMU-specific options are not meant to be used by users,
251 * therefore we don't show them either.
252 */
253//usage:#define hush_trivial_usage
254//usage: "[-nx] [-c SCRIPT]"
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200255//usage:#define hush_full_usage ""
Dan Fandrich89ca2f92010-11-28 01:54:39 +0100256//usage:#define msh_trivial_usage hush_trivial_usage
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200257//usage:#define msh_full_usage ""
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +0200258//usage:#define sh_trivial_usage NOUSAGE_STR
259//usage:#define sh_full_usage ""
260//usage:#define bash_trivial_usage NOUSAGE_STR
261//usage:#define bash_full_usage ""
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200262
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000263
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200264/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000265#define LEAK_HUNTING 0
266#define BUILD_AS_NOMMU 0
267/* Enable/disable sanity checks. Ok to enable in production,
268 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
269 * Keeping 1 for now even in released versions.
270 */
271#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200272/* Slightly bigger (+200 bytes), but faster hush.
273 * So far it only enables a trick with counting SIGCHLDs and forks,
274 * which allows us to do fewer waitpid's.
275 * (we can detect a case where neither forks were done nor SIGCHLDs happened
276 * and therefore waitpid will return the same result as last time)
277 */
278#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200279/* TODO: implement simplified code for users which do not need ${var%...} ops
280 * So far ${var%...} ops are always enabled:
281 */
282#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000283
284
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000285#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000286# undef BB_MMU
287# undef USE_FOR_NOMMU
288# undef USE_FOR_MMU
289# define BB_MMU 0
290# define USE_FOR_NOMMU(...) __VA_ARGS__
291# define USE_FOR_MMU(...)
292#endif
293
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200294#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100295#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000296/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000297# undef CONFIG_FEATURE_SH_STANDALONE
298# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000299# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100300# undef IF_NOT_FEATURE_SH_STANDALONE
301# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000302# define IF_FEATURE_SH_STANDALONE(...)
303# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000304#endif
305
Denis Vlasenko05743d72008-02-10 12:10:08 +0000306#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000307# undef ENABLE_FEATURE_EDITING
308# define ENABLE_FEATURE_EDITING 0
309# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
310# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000311#endif
312
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000313/* Do we support ANY keywords? */
314#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000315# define HAS_KEYWORDS 1
316# define IF_HAS_KEYWORDS(...) __VA_ARGS__
317# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000318#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000319# define HAS_KEYWORDS 0
320# define IF_HAS_KEYWORDS(...)
321# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000322#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000323
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000324/* If you comment out one of these below, it will be #defined later
325 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000326#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000327/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000328#define debug_printf_parse(...) do {} while (0)
329#define debug_print_tree(a, b) do {} while (0)
330#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000331#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000332#define debug_printf_jobs(...) do {} while (0)
333#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200334#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000335#define debug_printf_glob(...) do {} while (0)
336#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000337#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000338#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000339
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000340#define ERR_PTR ((void*)(long)1)
341
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200342#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000343
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200344#define _SPECIAL_VARS_STR "_*@$!?#"
345#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
346#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
Denys Vlasenko36f774a2010-09-05 14:45:38 +0200347#if ENABLE_HUSH_BASH_COMPAT
348/* Support / and // replace ops */
349/* Note that // is stored as \ in "encoded" string representation */
350# define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
351# define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
352# define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
353#else
354# define VAR_ENCODED_SUBST_OPS "%#:-=+?"
355# define VAR_SUBST_OPS "%#:-=+?"
356# define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
357#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200358
359#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000360
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200361struct variable;
362
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000363static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
364
365/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000366 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000367 */
368#if !BB_MMU
369typedef struct nommu_save_t {
370 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200371 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000372 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000373 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000374} nommu_save_t;
375#endif
376
Denys Vlasenko9b782552010-09-08 13:33:26 +0200377enum {
Eric Andersen25f27032001-04-26 23:22:31 +0000378 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000379#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000380 RES_IF ,
381 RES_THEN ,
382 RES_ELIF ,
383 RES_ELSE ,
384 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000385#endif
386#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000387 RES_FOR ,
388 RES_WHILE ,
389 RES_UNTIL ,
390 RES_DO ,
391 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000392#endif
393#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000394 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000395#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000396#if ENABLE_HUSH_CASE
397 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200398 /* three pseudo-keywords support contrived "case" syntax: */
399 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
400 RES_MATCH , /* "word)" */
401 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000402 RES_ESAC ,
403#endif
404 RES_XXXX ,
405 RES_SNTX
Denys Vlasenko9b782552010-09-08 13:33:26 +0200406};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000407
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000408typedef struct o_string {
409 char *data;
410 int length; /* position where data is appended */
411 int maxlen;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +0200412 int o_expflags;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000413 /* At least some part of the string was inside '' or "",
414 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenko38292b62010-09-05 14:49:40 +0200415 smallint has_quoted_part;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000416 smallint has_empty_slot;
417 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
418} o_string;
419enum {
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200420 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
421 EXP_FLAG_GLOB = 0x2,
422 /* Protect newly added chars against globbing
423 * by prepending \ to *, ?, [, \ */
424 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
425};
426enum {
427 MAYBE_ASSIGNMENT = 0,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000428 DEFINITELY_ASSIGNMENT = 1,
Denys Vlasenko0e13b402010-09-21 12:35:39 +0200429 NOT_ASSIGNMENT = 2,
430 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
431 WORD_IS_KEYWORD = 3,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000432};
433/* Used for initialization: o_string foo = NULL_O_STRING; */
434#define NULL_O_STRING { NULL }
435
436/* I can almost use ordinary FILE*. Is open_memstream() universally
437 * available? Where is it documented? */
438typedef struct in_str {
439 const char *p;
440 /* eof_flag=1: last char in ->p is really an EOF */
441 char eof_flag; /* meaningless if ->p == NULL */
442 char peek_buf[2];
443#if ENABLE_HUSH_INTERACTIVE
444 smallint promptme;
445 smallint promptmode; /* 0: PS1, 1: PS2 */
446#endif
447 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200448 int (*get) (struct in_str *) FAST_FUNC;
449 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000450} in_str;
451#define i_getch(input) ((input)->get(input))
452#define i_peek(input) ((input)->peek(input))
453
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200454/* The descrip member of this structure is only used to make
455 * debugging output pretty */
456static const struct {
457 int mode;
458 signed char default_fd;
459 char descrip[3];
460} redir_table[] = {
461 { O_RDONLY, 0, "<" },
462 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
463 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
464 { O_CREAT|O_RDWR, 1, "<>" },
465 { O_RDONLY, 0, "<<" },
466/* Should not be needed. Bogus default_fd helps in debugging */
467/* { O_RDONLY, 77, "<<" }, */
468};
469
Eric Andersen25f27032001-04-26 23:22:31 +0000470struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000471 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000472 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000473 int rd_fd; /* fd to redirect */
474 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
475 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000476 smallint rd_type; /* (enum redir_type) */
477 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000478 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200479 * bit 0: do we need to trim leading tabs?
480 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000481 */
Eric Andersen25f27032001-04-26 23:22:31 +0000482};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000483typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200484 REDIRECT_INPUT = 0,
485 REDIRECT_OVERWRITE = 1,
486 REDIRECT_APPEND = 2,
487 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000488 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200489 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000490
491 REDIRFD_CLOSE = -3,
492 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000493 REDIRFD_TO_FILE = -1,
494 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000495
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000496 HEREDOC_SKIPTABS = 1,
497 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000498} redir_type;
499
Eric Andersen25f27032001-04-26 23:22:31 +0000500
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000501struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000502 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000503 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000504 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200505 smallint cmd_type; /* CMD_xxx */
506#define CMD_NORMAL 0
507#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200508#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenkod383b492010-09-06 10:22:13 +0200509/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200510# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000511#endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200512#if ENABLE_HUSH_FUNCTIONS
513# define CMD_FUNCDEF 3
514#endif
515
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100516 smalluint cmd_exitcode;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200517 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
518 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000519#if !BB_MMU
520 char *group_as_string;
521#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000522#if ENABLE_HUSH_FUNCTIONS
523 struct function *child_func;
524/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200525 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000526 * When we execute "f1() {a;}" cmd, we create new function and clear
527 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200528 * When we execute "f1() {b;}", we notice that f1 exists,
529 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000530 * we put those fields back into cmd->xxx
531 * (struct function has ->parent_cmd ptr to facilitate that).
532 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
533 * Without this trick, loop would execute a;b;b;b;...
534 * instead of correct sequence a;b;a;b;...
535 * When command is freed, it severs the link
536 * (sets ->child_func->parent_cmd to NULL).
537 */
538#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000539 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000540/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
541 * and on execution these are substituted with their values.
542 * Substitution can make _several_ words out of one argv[n]!
543 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000544 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000545 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000546 struct redir_struct *redirects; /* I/O redirections */
547};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000548/* Is there anything in this command at all? */
549#define IS_NULL_CMD(cmd) \
550 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
551
Eric Andersen25f27032001-04-26 23:22:31 +0000552struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000553 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000554 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000555 int alive_cmds; /* number of commands running (not exited) */
556 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000557#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000558 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000559 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000560 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000561#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000562 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000563 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000564 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
565 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000566};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000567typedef enum pipe_style {
568 PIPE_SEQ = 1,
569 PIPE_AND = 2,
570 PIPE_OR = 3,
571 PIPE_BG = 4,
572} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000573/* Is there anything in this pipe at all? */
574#define IS_NULL_PIPE(pi) \
575 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000576
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000577/* This holds pointers to the various results of parsing */
578struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000579 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000580 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000581 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000582 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000583 /* last command in pipe (being constructed right now) */
584 struct command *command;
585 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000586 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000587#if !BB_MMU
588 o_string as_string;
589#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000590#if HAS_KEYWORDS
591 smallint ctx_res_w;
592 smallint ctx_inverted; /* "! cmd | cmd" */
593#if ENABLE_HUSH_CASE
594 smallint ctx_dsemicolon; /* ";;" seen */
595#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000596 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
597 int old_flag;
598 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000599 * example: "if pipe1; pipe2; then pipe3; fi"
600 * when we see "if" or "then", we malloc and copy current context,
601 * and make ->stack point to it. then we parse pipeN.
602 * when closing "then" / fi" / whatever is found,
603 * we move list_head into ->stack->command->group,
604 * copy ->stack into current context, and delete ->stack.
605 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000606 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000607 struct parse_context *stack;
608#endif
609};
610
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000611/* On program start, environ points to initial environment.
612 * putenv adds new pointers into it, unsetenv removes them.
613 * Neither of these (de)allocates the strings.
614 * setenv allocates new strings in malloc space and does putenv,
615 * and thus setenv is unusable (leaky) for shell's purposes */
616#define setenv(...) setenv_is_leaky_dont_use()
617struct variable {
618 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000619 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200620#if ENABLE_HUSH_LOCAL
621 unsigned func_nest_level;
622#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000623 int max_len; /* if > 0, name is part of initial env; else name is malloced */
624 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000625 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000626};
627
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000628enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000629 BC_BREAK = 1,
630 BC_CONTINUE = 2,
631};
632
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000633#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000634struct function {
635 struct function *next;
636 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000637 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000638 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200639# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000640 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200641# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000642};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000643#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000644
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000645
Denys Vlasenko6696eac2010-11-14 02:01:50 +0100646/* set -/+o OPT support. (TODO: make it optional)
647 * bash supports the following opts:
648 * allexport off
649 * braceexpand on
650 * emacs on
651 * errexit off
652 * errtrace off
653 * functrace off
654 * hashall on
655 * histexpand off
656 * history on
657 * ignoreeof off
658 * interactive-comments on
659 * keyword off
660 * monitor on
661 * noclobber off
662 * noexec off
663 * noglob off
664 * nolog off
665 * notify off
666 * nounset off
667 * onecmd off
668 * physical off
669 * pipefail off
670 * posix off
671 * privileged off
672 * verbose off
673 * vi off
674 * xtrace off
675 */
676static const char o_opt_strings[] ALIGN1 = "pipefail\0";
677enum {
678 OPT_O_PIPEFAIL,
679 NUM_OPT_O
680};
681
682
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000683/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000684/* Sorted roughly by size (smaller offsets == smaller code) */
685struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000686 /* interactive_fd != 0 means we are an interactive shell.
687 * If we are, then saved_tty_pgrp can also be != 0, meaning
688 * that controlling tty is available. With saved_tty_pgrp == 0,
689 * job control still works, but terminal signals
690 * (^C, ^Z, ^Y, ^\) won't work at all, and background
691 * process groups can only be created with "cmd &".
692 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
693 * to give tty to the foreground process group,
694 * and will take it back when the group is stopped (^Z)
695 * or killed (^C).
696 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000697#if ENABLE_HUSH_INTERACTIVE
698 /* 'interactive_fd' is a fd# open to ctty, if we have one
699 * _AND_ if we decided to act interactively */
700 int interactive_fd;
701 const char *PS1;
702 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000703# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000704#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000705# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000706#endif
707#if ENABLE_FEATURE_EDITING
708 line_input_t *line_input_state;
709#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000710 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200711 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000712 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200713#if ENABLE_HUSH_RANDOM_SUPPORT
714 random_t random_gen;
715#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000716#if ENABLE_HUSH_JOB
717 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000718 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000719 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000720 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400721# define G_saved_tty_pgrp (G.saved_tty_pgrp)
722#else
723# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000724#endif
Denys Vlasenko26777aa2010-11-22 23:49:10 +0100725 char o_opt[NUM_OPT_O];
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000726 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000727#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000728 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000729#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000730#if ENABLE_HUSH_FUNCTIONS
731 /* 0: outside of a function (or sourced file)
732 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000733 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000734 */
735 smallint flag_return_in_progress;
736#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200737 smallint n_mode;
738#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +0200739 smallint x_mode;
Denys Vlasenko29082232010-07-16 13:52:32 +0200740# define G_x_mode (G.x_mode)
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200741#else
742# define G_x_mode 0
743#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000744 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000745 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000746 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000747 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000748 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100749 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000750 /* how many non-NULL argv's we have. NB: $# + 1 */
751 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000752 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000753#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000754 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000755#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000756#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000757 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000758 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000759#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000760 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000761 const char *cwd;
Denys Vlasenko52e460b2010-09-16 16:12:00 +0200762 struct variable *top_var;
Denys Vlasenko29082232010-07-16 13:52:32 +0200763 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000764#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000765 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200766# if ENABLE_HUSH_LOCAL
767 struct variable **shadowed_vars_pp;
768 unsigned func_nest_level;
769# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000770#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000771 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200772#if ENABLE_HUSH_FAST
773 unsigned count_SIGCHLD;
774 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200775 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200776#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000777 /* which signals have non-DFL handler (even with no traps set)? */
778 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000779 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000780 sigset_t blocked_set;
781 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000782#if HUSH_DEBUG
783 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000784 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000785#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200786 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000787};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000788#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000789/* Not #defining name to G.name - this quickly gets unwieldy
790 * (too many defines). Also, I actually prefer to see when a variable
791 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000792#define INIT_G() do { \
793 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
794} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000795
796
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000797/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200798static int builtin_cd(char **argv) FAST_FUNC;
799static int builtin_echo(char **argv) FAST_FUNC;
800static int builtin_eval(char **argv) FAST_FUNC;
801static int builtin_exec(char **argv) FAST_FUNC;
802static int builtin_exit(char **argv) FAST_FUNC;
803static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000804#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200805static int builtin_fg_bg(char **argv) FAST_FUNC;
806static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000807#endif
808#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200809static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000810#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200811#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200812static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200813#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000814#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200815static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000816#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400817#if ENABLE_PRINTF
818static int builtin_printf(char **argv) FAST_FUNC;
819#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200820static int builtin_pwd(char **argv) FAST_FUNC;
821static int builtin_read(char **argv) FAST_FUNC;
822static int builtin_set(char **argv) FAST_FUNC;
823static int builtin_shift(char **argv) FAST_FUNC;
824static int builtin_source(char **argv) FAST_FUNC;
825static int builtin_test(char **argv) FAST_FUNC;
826static int builtin_trap(char **argv) FAST_FUNC;
827static int builtin_type(char **argv) FAST_FUNC;
828static int builtin_true(char **argv) FAST_FUNC;
829static int builtin_umask(char **argv) FAST_FUNC;
830static int builtin_unset(char **argv) FAST_FUNC;
831static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000832#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200833static int builtin_break(char **argv) FAST_FUNC;
834static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000835#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000836#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200837static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000838#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000839
840/* Table of built-in functions. They can be forked or not, depending on
841 * context: within pipes, they fork. As simple commands, they do not.
842 * When used in non-forking context, they can change global variables
843 * in the parent shell process. If forked, of course they cannot.
844 * For example, 'unset foo | whatever' will parse and run, but foo will
845 * still be set at the end. */
846struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100847 const char *b_cmd;
848 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000849#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100850 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200851# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000852#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200853# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000854#endif
855};
856
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200857static const struct built_in_command bltins1[] = {
858 BLTIN("." , builtin_source , "Run commands in a file"),
859 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000860#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200861 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000862#endif
863#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200864 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000865#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200866 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000867#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200868 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000869#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200870 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
871 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
872 BLTIN("exit" , builtin_exit , "Exit"),
873 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000874#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200875 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000876#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000877#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200878 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000879#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000880#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200881 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000882#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200883#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200884 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200885#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000886#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200887 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000888#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200889 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000890#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200891 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000892#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200893 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
894 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200895#if ENABLE_HUSH_BASH_COMPAT
896 BLTIN("source" , builtin_source , "Run commands in a file"),
897#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200898 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100899 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100900 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200901 BLTIN("umask" , builtin_umask , "Set file creation mask"),
902 BLTIN("unset" , builtin_unset , "Unset variables"),
903 BLTIN("wait" , builtin_wait , "Wait for process"),
904};
905/* For now, echo and test are unconditionally enabled.
906 * Maybe make it configurable? */
907static const struct built_in_command bltins2[] = {
908 BLTIN("[" , builtin_test , NULL),
909 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400910#if ENABLE_PRINTF
911 BLTIN("printf" , builtin_printf , NULL),
912#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200913 BLTIN("pwd" , builtin_pwd , NULL),
914 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000915};
916
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000917
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000918/* Debug printouts.
919 */
920#if HUSH_DEBUG
921/* prevent disasters with G.debug_indent < 0 */
922# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
923# define debug_enter() (G.debug_indent++)
924# define debug_leave() (G.debug_indent--)
925#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200926# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000927# define debug_enter() ((void)0)
928# define debug_leave() ((void)0)
929#endif
930
931#ifndef debug_printf
932# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
933#endif
934
935#ifndef debug_printf_parse
936# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
937#endif
938
939#ifndef debug_printf_exec
940#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
941#endif
942
943#ifndef debug_printf_env
944# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
945#endif
946
947#ifndef debug_printf_jobs
948# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
949# define DEBUG_JOBS 1
950#else
951# define DEBUG_JOBS 0
952#endif
953
954#ifndef debug_printf_expand
955# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
956# define DEBUG_EXPAND 1
957#else
958# define DEBUG_EXPAND 0
959#endif
960
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200961#ifndef debug_printf_varexp
962# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
963#endif
964
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000965#ifndef debug_printf_glob
966# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
967# define DEBUG_GLOB 1
968#else
969# define DEBUG_GLOB 0
970#endif
971
972#ifndef debug_printf_list
973# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
974#endif
975
976#ifndef debug_printf_subst
977# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
978#endif
979
980#ifndef debug_printf_clean
981# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
982# define DEBUG_CLEAN 1
983#else
984# define DEBUG_CLEAN 0
985#endif
986
987#if DEBUG_EXPAND
988static void debug_print_strings(const char *prefix, char **vv)
989{
990 indent();
991 fprintf(stderr, "%s:\n", prefix);
992 while (*vv)
993 fprintf(stderr, " '%s'\n", *vv++);
994}
995#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200996# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000997#endif
998
999
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001000/* Leak hunting. Use hush_leaktool.sh for post-processing.
1001 */
1002#if LEAK_HUNTING
1003static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001004{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001005 void *ptr = xmalloc((size + 0xff) & ~0xff);
1006 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1007 return ptr;
1008}
1009static void *xxrealloc(int lineno, void *ptr, size_t size)
1010{
1011 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1012 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1013 return ptr;
1014}
1015static char *xxstrdup(int lineno, const char *str)
1016{
1017 char *ptr = xstrdup(str);
1018 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1019 return ptr;
1020}
1021static void xxfree(void *ptr)
1022{
1023 fdprintf(2, "free %p\n", ptr);
1024 free(ptr);
1025}
Denys Vlasenko8391c482010-05-22 17:50:43 +02001026# define xmalloc(s) xxmalloc(__LINE__, s)
1027# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1028# define xstrdup(s) xxstrdup(__LINE__, s)
1029# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001030#endif
1031
1032
1033/* Syntax and runtime errors. They always abort scripts.
1034 * In interactive use they usually discard unparsed and/or unexecuted commands
1035 * and return to the prompt.
1036 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1037 */
1038#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +02001039# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001040# define syntax_error(lineno, msg) syntax_error(msg)
1041# define syntax_error_at(lineno, msg) syntax_error_at(msg)
1042# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1043# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1044# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001045#endif
1046
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001047static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001048{
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001049 va_list p;
1050
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001051#if HUSH_DEBUG >= 2
1052 bb_error_msg("hush.c:%u", lineno);
1053#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001054 va_start(p, fmt);
1055 bb_verror_msg(fmt, p, NULL);
1056 va_end(p);
1057 if (!G_interactive_fd)
1058 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001059}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001060
1061static void syntax_error(unsigned lineno, const char *msg)
1062{
1063 if (msg)
1064 die_if_script(lineno, "syntax error: %s", msg);
1065 else
1066 die_if_script(lineno, "syntax error", NULL);
1067}
1068
1069static void syntax_error_at(unsigned lineno, const char *msg)
1070{
1071 die_if_script(lineno, "syntax error at '%s'", msg);
1072}
1073
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001074static void syntax_error_unterm_str(unsigned lineno, const char *s)
1075{
1076 die_if_script(lineno, "syntax error: unterminated %s", s);
1077}
1078
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001079/* It so happens that all such cases are totally fatal
1080 * even if shell is interactive: EOF while looking for closing
1081 * delimiter. There is nowhere to read stuff from after that,
1082 * it's EOF! The only choice is to terminate.
1083 */
1084static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001085static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001086{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001087 char msg[2] = { ch, '\0' };
1088 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001089 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001090}
1091
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001092static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001093{
1094 char msg[2];
1095 msg[0] = ch;
1096 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001097 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001098}
1099
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001100#if HUSH_DEBUG < 2
1101# undef die_if_script
1102# undef syntax_error
1103# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001104# undef syntax_error_unterm_ch
1105# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001106# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001107#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001108# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001109# define syntax_error(msg) syntax_error(__LINE__, msg)
1110# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1111# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1112# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1113# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001114#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001115
Denis Vlasenko552433b2009-04-04 19:29:21 +00001116
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001117#if ENABLE_HUSH_INTERACTIVE
1118static void cmdedit_update_prompt(void);
1119#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001120# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001121#endif
1122
1123
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001124/* Utility functions
1125 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001126/* Replace each \x with x in place, return ptr past NUL. */
1127static char *unbackslash(char *src)
1128{
Denys Vlasenko71885402009-09-24 01:44:13 +02001129 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001130 while (1) {
1131 if (*src == '\\')
1132 src++;
1133 if ((*dst++ = *src++) == '\0')
1134 break;
1135 }
1136 return dst;
1137}
1138
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001139static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001140{
1141 int i;
1142 unsigned count1;
1143 unsigned count2;
1144 char **v;
1145
1146 v = strings;
1147 count1 = 0;
1148 if (v) {
1149 while (*v) {
1150 count1++;
1151 v++;
1152 }
1153 }
1154 count2 = 0;
1155 v = add;
1156 while (*v) {
1157 count2++;
1158 v++;
1159 }
1160 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1161 v[count1 + count2] = NULL;
1162 i = count2;
1163 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001164 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001165 return v;
1166}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001167#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001168static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1169{
1170 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1171 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1172 return ptr;
1173}
1174#define add_strings_to_strings(strings, add, need_to_dup) \
1175 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1176#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001177
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001178/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001179static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001180{
1181 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001182 v[0] = add;
1183 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001184 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001185}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001186#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001187static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1188{
1189 char **ptr = add_string_to_strings(strings, add);
1190 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1191 return ptr;
1192}
1193#define add_string_to_strings(strings, add) \
1194 xx_add_string_to_strings(__LINE__, strings, add)
1195#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001196
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001197static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001198{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001199 char **v;
1200
1201 if (!strings)
1202 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001203 v = strings;
1204 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001205 free(*v);
1206 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001207 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001208 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001209}
1210
Denis Vlasenko76d50412008-06-10 16:19:39 +00001211
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001212/* Helpers for setting new $n and restoring them back
1213 */
1214typedef struct save_arg_t {
1215 char *sv_argv0;
1216 char **sv_g_argv;
1217 int sv_g_argc;
1218 smallint sv_g_malloced;
1219} save_arg_t;
1220
1221static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1222{
1223 int n;
1224
1225 sv->sv_argv0 = argv[0];
1226 sv->sv_g_argv = G.global_argv;
1227 sv->sv_g_argc = G.global_argc;
1228 sv->sv_g_malloced = G.global_args_malloced;
1229
1230 argv[0] = G.global_argv[0]; /* retain $0 */
1231 G.global_argv = argv;
1232 G.global_args_malloced = 0;
1233
1234 n = 1;
1235 while (*++argv)
1236 n++;
1237 G.global_argc = n;
1238}
1239
1240static void restore_G_args(save_arg_t *sv, char **argv)
1241{
1242 char **pp;
1243
1244 if (G.global_args_malloced) {
1245 /* someone ran "set -- arg1 arg2 ...", undo */
1246 pp = G.global_argv;
1247 while (*++pp) /* note: does not free $0 */
1248 free(*pp);
1249 free(G.global_argv);
1250 }
1251 argv[0] = sv->sv_argv0;
1252 G.global_argv = sv->sv_g_argv;
1253 G.global_argc = sv->sv_g_argc;
1254 G.global_args_malloced = sv->sv_g_malloced;
1255}
1256
1257
Denis Vlasenkod5762932009-03-31 11:22:57 +00001258/* Basic theory of signal handling in shell
1259 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001260 * This does not describe what hush does, rather, it is current understanding
1261 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001262 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1263 *
1264 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1265 * is finished or backgrounded. It is the same in interactive and
1266 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001267 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001268 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001269 * backgrounds (i.e. stops) or kills all members of currently running
1270 * pipe.
1271 *
1272 * Wait builtin in interruptible by signals for which user trap is set
1273 * or by SIGINT in interactive shell.
1274 *
1275 * Trap handlers will execute even within trap handlers. (right?)
1276 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001277 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1278 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001279 *
1280 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001281 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001282 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001283 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001284 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001285 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001286 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001287 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001288 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001289 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001290 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001291 *
1292 * SIGQUIT: ignore
1293 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001294 * SIGHUP (interactive):
1295 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001296 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001297 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1298 * that all pipe members are stopped. Try this in bash:
1299 * while :; do :; done - ^Z does not background it
1300 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001301 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001302 * of the command line, show prompt. NB: ^C does not send SIGINT
1303 * to interactive shell while shell is waiting for a pipe,
1304 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001305 * Example 1: this waits 5 sec, but does not execute ls:
1306 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1307 * Example 2: this does not wait and does not execute ls:
1308 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1309 * Example 3: this does not wait 5 sec, but executes ls:
1310 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001311 *
1312 * (What happens to signals which are IGN on shell start?)
1313 * (What happens with signal mask on shell start?)
1314 *
1315 * Implementation in hush
1316 * ======================
1317 * We use in-kernel pending signal mask to determine which signals were sent.
1318 * We block all signals which we don't want to take action immediately,
1319 * i.e. we block all signals which need to have special handling as described
1320 * above, and all signals which have traps set.
1321 * After each pipe execution, we extract any pending signals via sigtimedwait()
1322 * and act on them.
1323 *
1324 * unsigned non_DFL_mask: a mask of such "special" signals
1325 * sigset_t blocked_set: current blocked signal set
1326 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001327 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001328 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001329 * "trap 'cmd' SIGxxx":
1330 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001331 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001332 * unblock signals with special interactive handling
1333 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001334 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001335 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001336 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001337 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001338 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001339 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001340 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001341 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001342 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001343 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001344 * Standard says "When a subshell is entered, traps that are not being ignored
1345 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001346 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001347 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001348enum {
1349 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001350 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001351 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001352 | (1 << SIGHUP)
1353 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001354 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001355#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001356 | (1 << SIGTTIN)
1357 | (1 << SIGTTOU)
1358 | (1 << SIGTSTP)
1359#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001360};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001361
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001362#if ENABLE_HUSH_FAST
1363static void SIGCHLD_handler(int sig UNUSED_PARAM)
1364{
1365 G.count_SIGCHLD++;
1366//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1367}
1368#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001369
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001370#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001371
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001372/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001373# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001374/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001375# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001376
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001377/* Restores tty foreground process group, and exits.
1378 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001379 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001380 * or called directly with -EXITCODE.
1381 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001382static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001383static void sigexit(int sig)
1384{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001385 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001386 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001387
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001388 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001389 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001390 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1391 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001392
1393 /* Not a signal, just exit */
1394 if (sig <= 0)
1395 _exit(- sig);
1396
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001397 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001398}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001399#else
1400
Denys Vlasenko8391c482010-05-22 17:50:43 +02001401# define disable_restore_tty_pgrp_on_exit() ((void)0)
1402# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001403
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001404#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001405
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001406/* Restores tty foreground process group, and exits. */
1407static void hush_exit(int exitcode) NORETURN;
1408static void hush_exit(int exitcode)
1409{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001410 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1411 /* Prevent recursion:
1412 * trap "echo Hi; exit" EXIT; exit
1413 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001414 char *argv[3];
1415 /* argv[0] is unused */
1416 argv[1] = G.traps[0];
1417 argv[2] = NULL;
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001418 G.exiting = 1; /* prevent EXIT trap recursion */
Denys Vlasenkoa110c902010-09-12 15:38:04 +02001419 /* Note: G.traps[0] is not cleared!
Denys Vlasenkode8c3f62010-09-12 16:13:44 +02001420 * "trap" will still show it, if executed
1421 * in the handler */
1422 builtin_eval(argv);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001423 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001424
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001425#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001426 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001427 sigexit(- (exitcode & 0xff));
1428#else
1429 exit(exitcode);
1430#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001431}
1432
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001433
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001434static int check_and_run_traps(int sig)
1435{
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02001436 /* I want it in rodata, not in bss.
1437 * gcc 4.2.1 puts it in rodata only if it has { 0, 0 }
1438 * initializer. But other compilers may still use bss.
1439 * TODO: find more portable solution.
1440 */
1441 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001442 smalluint save_rcode;
1443 int last_sig = 0;
1444
1445 if (sig)
1446 goto jump_in;
1447 while (1) {
1448 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1449 if (sig <= 0)
1450 break;
1451 jump_in:
1452 last_sig = sig;
1453 if (G.traps && G.traps[sig]) {
1454 if (G.traps[sig][0]) {
1455 /* We have user-defined handler */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001456 char *argv[3];
1457 /* argv[0] is unused */
1458 argv[1] = G.traps[sig];
1459 argv[2] = NULL;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001460 save_rcode = G.last_exitcode;
1461 builtin_eval(argv);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001462 G.last_exitcode = save_rcode;
1463 } /* else: "" trap, ignoring signal */
1464 continue;
1465 }
1466 /* not a trap: special action */
1467 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001468#if ENABLE_HUSH_FAST
1469 case SIGCHLD:
1470 G.count_SIGCHLD++;
1471//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1472 break;
1473#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001474 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001475 /* Builtin was ^C'ed, make it look prettier: */
1476 bb_putchar('\n');
1477 G.flag_SIGINT = 1;
1478 break;
1479#if ENABLE_HUSH_JOB
1480 case SIGHUP: {
1481 struct pipe *job;
1482 /* bash is observed to signal whole process groups,
1483 * not individual processes */
1484 for (job = G.job_list; job; job = job->next) {
1485 if (job->pgrp <= 0)
1486 continue;
1487 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1488 if (kill(- job->pgrp, SIGHUP) == 0)
1489 kill(- job->pgrp, SIGCONT);
1490 }
1491 sigexit(SIGHUP);
1492 }
1493#endif
1494 default: /* ignored: */
1495 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1496 break;
1497 }
1498 }
1499 return last_sig;
1500}
1501
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001502
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001503static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001504{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001505 if (force || G.cwd == NULL) {
1506 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1507 * we must not try to free(bb_msg_unknown) */
1508 if (G.cwd == bb_msg_unknown)
1509 G.cwd = NULL;
1510 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1511 if (!G.cwd)
1512 G.cwd = bb_msg_unknown;
1513 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001514 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001515}
1516
Denis Vlasenko83506862007-11-23 13:11:42 +00001517
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001518/*
1519 * Shell and environment variable support
1520 */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001521static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001522{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001523 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001524 struct variable *cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001525
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001526 pp = &G.top_var;
1527 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001528 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001529 return pp;
1530 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001531 }
1532 return NULL;
1533}
1534
Denys Vlasenko03dad222010-01-12 23:29:57 +01001535static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001536{
Denys Vlasenko29082232010-07-16 13:52:32 +02001537 struct variable **vpp;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001538 unsigned len = strlen(name);
Denys Vlasenko29082232010-07-16 13:52:32 +02001539
1540 if (G.expanded_assignments) {
1541 char **cpp = G.expanded_assignments;
Denys Vlasenko29082232010-07-16 13:52:32 +02001542 while (*cpp) {
1543 char *cp = *cpp;
1544 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1545 return cp + len + 1;
1546 cpp++;
1547 }
1548 }
1549
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001550 vpp = get_ptr_to_local_var(name, len);
Denys Vlasenko29082232010-07-16 13:52:32 +02001551 if (vpp)
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001552 return (*vpp)->varstr + len + 1;
Denys Vlasenko29082232010-07-16 13:52:32 +02001553
Denys Vlasenkodea47882009-10-09 15:40:49 +02001554 if (strcmp(name, "PPID") == 0)
1555 return utoa(G.root_ppid);
1556 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001557#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001558 if (strcmp(name, "RANDOM") == 0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001559 return utoa(next_random(&G.random_gen));
1560#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001561 return NULL;
1562}
1563
1564/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001565 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001566 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001567 * 0: do not change export flag
1568 * (if creating new variable, flag will be 0)
1569 * 1: set export flag and putenv the variable
1570 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001571 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001572 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001573#if !BB_MMU && ENABLE_HUSH_LOCAL
1574/* all params are used */
1575#elif BB_MMU && ENABLE_HUSH_LOCAL
1576#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1577 set_local_var(str, flg_export, local_lvl)
1578#elif BB_MMU && !ENABLE_HUSH_LOCAL
1579#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001580 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001581#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1582#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1583 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001584#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001585static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001586{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001587 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001588 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001589 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001590 int name_len;
1591
Denis Vlasenko950bd722009-04-21 11:23:56 +00001592 eq_sign = strchr(str, '=');
1593 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001594 free(str);
1595 return -1;
1596 }
1597
Denis Vlasenko950bd722009-04-21 11:23:56 +00001598 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001599 var_pp = &G.top_var;
1600 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001601 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001602 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001603 continue;
1604 }
1605 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001606 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001607#if !BB_MMU
1608 if (!flg_read_only)
1609#endif
1610 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001611 free(str);
1612 return -1;
1613 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001614 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001615 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1616 *eq_sign = '\0';
1617 unsetenv(str);
1618 *eq_sign = '=';
1619 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001620#if ENABLE_HUSH_LOCAL
1621 if (cur->func_nest_level < local_lvl) {
1622 /* New variable is declared as local,
1623 * and existing one is global, or local
1624 * from enclosing function.
1625 * Remove and save old one: */
1626 *var_pp = cur->next;
1627 cur->next = *G.shadowed_vars_pp;
1628 *G.shadowed_vars_pp = cur;
1629 /* bash 3.2.33(1) and exported vars:
1630 * # export z=z
1631 * # f() { local z=a; env | grep ^z; }
1632 * # f
1633 * z=a
1634 * # env | grep ^z
1635 * z=z
1636 */
1637 if (cur->flg_export)
1638 flg_export = 1;
1639 break;
1640 }
1641#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001642 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001643 free_and_exp:
1644 free(str);
1645 goto exp;
1646 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001647 if (cur->max_len != 0) {
1648 if (cur->max_len >= strlen(str)) {
1649 /* This one is from startup env, reuse space */
1650 strcpy(cur->varstr, str);
1651 goto free_and_exp;
1652 }
1653 } else {
1654 /* max_len == 0 signifies "malloced" var, which we can
1655 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001656 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001657 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001658 cur->max_len = 0;
1659 goto set_str_and_exp;
1660 }
1661
Denys Vlasenko295fef82009-06-03 12:47:26 +02001662 /* Not found - create new variable struct */
1663 cur = xzalloc(sizeof(*cur));
1664#if ENABLE_HUSH_LOCAL
1665 cur->func_nest_level = local_lvl;
1666#endif
1667 cur->next = *var_pp;
1668 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001669
1670 set_str_and_exp:
1671 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001672#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001673 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001674#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001675 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001676 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001677 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001678 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1679 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001680 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001681 if (flg_export == -1) {
1682 cur->flg_export = 0;
1683 /* unsetenv was already done */
1684 } else {
1685 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1686 return putenv(cur->varstr);
1687 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001688 }
1689 return 0;
1690}
1691
Denys Vlasenko6db47842009-09-05 20:15:17 +02001692/* Used at startup and after each cd */
1693static void set_pwd_var(int exp)
1694{
1695 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1696 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1697}
1698
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001699static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001700{
1701 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001702 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001703
1704 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001705 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001706 var_pp = &G.top_var;
1707 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001708 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1709 if (cur->flg_read_only) {
1710 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001711 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001712 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001713 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001714 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1715 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001716 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1717 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001718 if (!cur->max_len)
1719 free(cur->varstr);
1720 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001721 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001722 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001723 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001724 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001725 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001726}
1727
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001728static int unset_local_var(const char *name)
1729{
1730 return unset_local_var_len(name, strlen(name));
1731}
1732
1733static void unset_vars(char **strings)
1734{
1735 char **v;
1736
1737 if (!strings)
1738 return;
1739 v = strings;
1740 while (*v) {
1741 const char *eq = strchrnul(*v, '=');
1742 unset_local_var_len(*v, (int)(eq - *v));
1743 v++;
1744 }
1745 free(strings);
1746}
1747
Denys Vlasenko03dad222010-01-12 23:29:57 +01001748static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001749{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001750 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001751 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001752}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001753
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001754
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001755/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001756 * Helpers for "var1=val1 var2=val2 cmd" feature
1757 */
1758static void add_vars(struct variable *var)
1759{
1760 struct variable *next;
1761
1762 while (var) {
1763 next = var->next;
1764 var->next = G.top_var;
1765 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001766 if (var->flg_export) {
1767 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001768 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001769 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001770 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001771 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001772 var = next;
1773 }
1774}
1775
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001776static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001777{
1778 char **s;
1779 struct variable *old = NULL;
1780
1781 if (!strings)
1782 return old;
1783 s = strings;
1784 while (*s) {
1785 struct variable *var_p;
1786 struct variable **var_pp;
1787 char *eq;
1788
1789 eq = strchr(*s, '=');
1790 if (eq) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02001791 var_pp = get_ptr_to_local_var(*s, eq - *s);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001792 if (var_pp) {
1793 /* Remove variable from global linked list */
1794 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001795 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001796 *var_pp = var_p->next;
1797 /* Add it to returned list */
1798 var_p->next = old;
1799 old = var_p;
1800 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001801 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001802 }
1803 s++;
1804 }
1805 return old;
1806}
1807
1808
1809/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001810 * in_str support
1811 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001812static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001813{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001814 int ch = *i->p;
1815 if (ch != '\0') {
1816 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001817 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001818 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001819 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001820}
1821
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001822static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001823{
1824 return *i->p;
1825}
1826
1827#if ENABLE_HUSH_INTERACTIVE
1828
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001829static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001830{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001831 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001832 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001833 if (G.PS1 == NULL)
1834 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001835 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001836 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001837 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001838 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001839 if (G.PS2 == NULL)
1840 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001841}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001842
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02001843static const char *setup_prompt_string(int promptmode)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001844{
1845 const char *prompt_str;
1846 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001847 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1848 /* Set up the prompt */
1849 if (promptmode == 0) { /* PS1 */
1850 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001851 /* bash uses $PWD value, even if it is set by user.
1852 * It uses current dir only if PWD is unset.
1853 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001854 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001855 prompt_str = G.PS1;
1856 } else
1857 prompt_str = G.PS2;
1858 } else
1859 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001860 debug_printf("result '%s'\n", prompt_str);
1861 return prompt_str;
1862}
1863
1864static void get_user_input(struct in_str *i)
1865{
1866 int r;
1867 const char *prompt_str;
1868
1869 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001870# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001871 /* Enable command line editing only while a command line
1872 * is actually being read */
1873 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001874 G.flag_SIGINT = 0;
1875 /* buglet: SIGINT will not make new prompt to appear _at once_,
1876 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001877 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 +00001878 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001879 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001880 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001881 i->eof_flag = (r < 0);
1882 if (i->eof_flag) { /* EOF/error detected */
1883 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1884 G.user_input_buf[1] = '\0';
1885 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001886# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001887 do {
1888 G.flag_SIGINT = 0;
1889 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001890 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001891 G.user_input_buf[0] = r = fgetc(i->file);
1892 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001893//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001894 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001895 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001896# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001897 i->p = G.user_input_buf;
1898}
1899
1900#endif /* INTERACTIVE */
1901
1902/* This is the magic location that prints prompts
1903 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001904static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001905{
1906 int ch;
1907
1908 /* If there is data waiting, eat it up */
1909 if (i->p && *i->p) {
1910#if ENABLE_HUSH_INTERACTIVE
1911 take_cached:
1912#endif
1913 ch = *i->p++;
1914 if (i->eof_flag && !*i->p)
1915 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001916 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001917 } else {
1918 /* need to double check i->file because we might be doing something
1919 * more complicated by now, like sourcing or substituting. */
1920#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001921 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001922 do {
1923 get_user_input(i);
1924 } while (!*i->p); /* need non-empty line */
1925 i->promptmode = 1; /* PS2 */
1926 i->promptme = 0;
1927 goto take_cached;
1928 }
1929#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001930 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001931 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001932 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001933#if ENABLE_HUSH_INTERACTIVE
1934 if (ch == '\n')
1935 i->promptme = 1;
1936#endif
1937 return ch;
1938}
1939
Denis Vlasenko913a2012009-04-05 22:17:04 +00001940/* All callers guarantee this routine will never
1941 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001942 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001943static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001944{
1945 int ch;
1946 if (i->p && *i->p) {
1947 if (i->eof_flag && !i->p[1])
1948 return EOF;
1949 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001950 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001951 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001952 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001953 i->eof_flag = (ch == EOF);
1954 i->peek_buf[0] = ch;
1955 i->peek_buf[1] = '\0';
1956 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001957 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001958 return ch;
1959}
1960
1961static void setup_file_in_str(struct in_str *i, FILE *f)
1962{
1963 i->peek = file_peek;
1964 i->get = file_get;
1965#if ENABLE_HUSH_INTERACTIVE
1966 i->promptme = 1;
1967 i->promptmode = 0; /* PS1 */
1968#endif
1969 i->file = f;
1970 i->p = NULL;
1971}
1972
1973static void setup_string_in_str(struct in_str *i, const char *s)
1974{
1975 i->peek = static_peek;
1976 i->get = static_get;
1977#if ENABLE_HUSH_INTERACTIVE
1978 i->promptme = 1;
1979 i->promptmode = 0; /* PS1 */
1980#endif
1981 i->p = s;
1982 i->eof_flag = 0;
1983}
1984
1985
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001986/*
1987 * o_string support
1988 */
1989#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001990
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001991static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001992{
1993 o->length = 0;
Denys Vlasenko38292b62010-09-05 14:49:40 +02001994 o->has_quoted_part = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001995 if (o->data)
1996 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001997}
1998
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001999static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00002000{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00002001 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002002 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00002003}
2004
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002005static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2006{
2007 free(o->data);
2008}
2009
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002010static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002011{
2012 if (o->length + len > o->maxlen) {
2013 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2014 o->data = xrealloc(o->data, 1 + o->maxlen);
2015 }
2016}
2017
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002018static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002019{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002020 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2021 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002022 o->data[o->length] = ch;
2023 o->length++;
2024 o->data[o->length] = '\0';
2025}
2026
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002027static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002028{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002029 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002030 memcpy(&o->data[o->length], str, len);
2031 o->length += len;
2032 o->data[o->length] = '\0';
2033}
2034
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002035static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00002036{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002037 o_addblock(o, str, strlen(str));
2038}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002039
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002040#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002041static void nommu_addchr(o_string *o, int ch)
2042{
2043 if (o)
2044 o_addchr(o, ch);
2045}
2046#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002047# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002048#endif
2049
2050static void o_addstr_with_NUL(o_string *o, const char *str)
2051{
2052 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002053}
2054
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002055/*
Denys Vlasenko238081f2010-10-03 14:26:26 +02002056 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002057 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2058 * Apparently, on unquoted $v bash still does globbing
2059 * ("v='*.txt'; echo $v" prints all .txt files),
2060 * but NOT brace expansion! Thus, there should be TWO independent
2061 * quoting mechanisms on $v expansion side: one protects
2062 * $v from brace expansion, and other additionally protects "$v" against globbing.
2063 * We have only second one.
2064 */
2065
Denys Vlasenko9e800222010-10-03 14:28:04 +02002066#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002067# define MAYBE_BRACES "{}"
2068#else
2069# define MAYBE_BRACES ""
2070#endif
2071
Eric Andersen25f27032001-04-26 23:22:31 +00002072/* My analysis of quoting semantics tells me that state information
2073 * is associated with a destination, not a source.
2074 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002075static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002076{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002077 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002078 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002079 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002080 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002081 o_grow_by(o, sz);
2082 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002083 o->data[o->length] = '\\';
2084 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002085 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002086 o->data[o->length] = ch;
2087 o->length++;
2088 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002089}
2090
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002091static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002092{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002093 int sz = 1;
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002094 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2095 && strchr("*?[\\" MAYBE_BRACES, ch)
2096 ) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002097 sz++;
2098 o->data[o->length] = '\\';
2099 o->length++;
2100 }
2101 o_grow_by(o, sz);
2102 o->data[o->length] = ch;
2103 o->length++;
2104 o->data[o->length] = '\0';
2105}
2106
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002107static void o_addqblock(o_string *o, const char *str, int len)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002108{
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002109 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002110 char ch;
2111 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002112 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002113 if (ordinary_cnt > len) /* paranoia */
2114 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002115 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002116 if (ordinary_cnt == len)
2117 return;
2118 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002119 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002120
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002121 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002122 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002123 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002124 sz++;
2125 o->data[o->length] = '\\';
2126 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002127 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002128 o_grow_by(o, sz);
2129 o->data[o->length] = ch;
2130 o->length++;
2131 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002132 }
2133}
2134
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002135static void o_addQblock(o_string *o, const char *str, int len)
2136{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002137 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002138 o_addblock(o, str, len);
2139 return;
2140 }
2141 o_addqblock(o, str, len);
2142}
2143
Denys Vlasenko38292b62010-09-05 14:49:40 +02002144static void o_addQstr(o_string *o, const char *str)
2145{
2146 o_addQblock(o, str, strlen(str));
2147}
2148
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002149/* A special kind of o_string for $VAR and `cmd` expansion.
2150 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002151 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002152 * list[i] contains an INDEX (int!) into this string data.
2153 * It means that if list[] needs to grow, data needs to be moved higher up
2154 * but list[i]'s need not be modified.
2155 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002156 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002157 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2158 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002159#if DEBUG_EXPAND || DEBUG_GLOB
2160static void debug_print_list(const char *prefix, o_string *o, int n)
2161{
2162 char **list = (char**)o->data;
2163 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2164 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002165
2166 indent();
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002167 fprintf(stderr, "%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 +02002168 prefix, list, n, string_start, o->length, o->maxlen,
2169 !!(o->o_expflags & EXP_FLAG_GLOB),
2170 o->has_quoted_part,
2171 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002172 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002173 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002174 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2175 o->data + (int)list[i] + string_start,
2176 o->data + (int)list[i] + string_start);
2177 i++;
2178 }
2179 if (n) {
2180 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002181 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002182 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002183 }
2184}
2185#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002186# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002187#endif
2188
2189/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2190 * in list[n] so that it points past last stored byte so far.
2191 * It returns n+1. */
2192static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002193{
2194 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002195 int string_start;
2196 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002197
2198 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002199 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2200 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002201 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002202 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002203 /* list[n] points to string_start, make space for 16 more pointers */
2204 o->maxlen += 0x10 * sizeof(list[0]);
2205 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002206 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002207 memmove(list + n + 0x10, list + n, string_len);
2208 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002209 } else {
2210 debug_printf_list("list[%d]=%d string_start=%d\n",
2211 n, string_len, string_start);
2212 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002213 } else {
2214 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002215 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2216 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002217 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2218 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002219 o->has_empty_slot = 0;
2220 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002221 list[n] = (char*)(uintptr_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002222 return n + 1;
2223}
2224
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002225/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002226static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002227{
2228 char **list = (char**)o->data;
2229 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2230
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002231 return ((int)(uintptr_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002232}
2233
Denys Vlasenko9e800222010-10-03 14:28:04 +02002234#if ENABLE_HUSH_BRACE_EXPANSION
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002235/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2236 * first, it processes even {a} (no commas), second,
2237 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002238 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002239 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002240
2241/* Helper */
2242static int glob_needed(const char *s)
2243{
2244 while (*s) {
2245 if (*s == '\\') {
2246 if (!s[1])
2247 return 0;
2248 s += 2;
2249 continue;
2250 }
2251 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2252 return 1;
2253 s++;
2254 }
2255 return 0;
2256}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002257/* Return pointer to next closing brace or to comma */
2258static const char *next_brace_sub(const char *cp)
2259{
2260 unsigned depth = 0;
2261 cp++;
2262 while (*cp != '\0') {
2263 if (*cp == '\\') {
2264 if (*++cp == '\0')
2265 break;
2266 cp++;
2267 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002268 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002269 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002270 break;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002271 if (*cp++ == '{')
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002272 depth++;
2273 }
2274
2275 return *cp != '\0' ? cp : NULL;
2276}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002277/* Recursive brace globber. Note: may garble pattern[]. */
2278static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002279{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002280 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002281 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002282 const char *next;
2283 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002284 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002285 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002286
2287 debug_printf_glob("glob_brace('%s')\n", pattern);
2288
2289 begin = pattern;
2290 while (1) {
2291 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002292 goto simple_glob;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002293 if (*begin == '{') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002294 /* Find the first sub-pattern and at the same time
2295 * find the rest after the closing brace */
2296 next = next_brace_sub(begin);
2297 if (next == NULL) {
2298 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002299 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002300 }
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002301 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002302 /* "{abc}" with no commas - illegal
2303 * brace expr, disregard and skip it */
2304 begin = next + 1;
2305 continue;
2306 }
2307 break;
2308 }
2309 if (*begin == '\\' && begin[1] != '\0')
2310 begin++;
2311 begin++;
2312 }
2313 debug_printf_glob("begin:%s\n", begin);
2314 debug_printf_glob("next:%s\n", next);
2315
2316 /* Now find the end of the whole brace expression */
2317 rest = next;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002318 while (*rest != '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002319 rest = next_brace_sub(rest);
2320 if (rest == NULL) {
2321 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002322 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002323 }
2324 debug_printf_glob("rest:%s\n", rest);
2325 }
2326 rest_len = strlen(++rest) + 1;
2327
2328 /* We are sure the brace expression is well-formed */
2329
2330 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002331 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002332
2333 /* We have a brace expression. BEGIN points to the opening {,
2334 * NEXT points past the terminator of the first element, and REST
2335 * points past the final }. We will accumulate result names from
2336 * recursive runs for each brace alternative in the buffer using
2337 * GLOB_APPEND. */
2338
2339 p = begin + 1;
2340 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002341 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002342 memcpy(
2343 mempcpy(
2344 mempcpy(new_pattern_buf,
2345 /* We know the prefix for all sub-patterns */
2346 pattern, begin - pattern),
2347 p, next - p),
2348 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002349
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002350 /* Note: glob_brace() may garble new_pattern_buf[].
2351 * That's why we re-copy prefix every time (1st memcpy above).
2352 */
2353 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02002354 if (*next == '}') {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002355 /* We saw the last entry */
2356 break;
2357 }
2358 p = next + 1;
2359 next = next_brace_sub(next);
2360 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002361 free(new_pattern_buf);
2362 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002363
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002364 simple_glob:
2365 {
2366 int gr;
2367 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002368
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002369 memset(&globdata, 0, sizeof(globdata));
2370 gr = glob(pattern, 0, NULL, &globdata);
2371 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2372 if (gr != 0) {
2373 if (gr == GLOB_NOMATCH) {
2374 globfree(&globdata);
2375 /* NB: garbles parameter */
2376 unbackslash(pattern);
2377 o_addstr_with_NUL(o, pattern);
2378 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2379 return o_save_ptr_helper(o, n);
2380 }
2381 if (gr == GLOB_NOSPACE)
2382 bb_error_msg_and_die(bb_msg_memory_exhausted);
2383 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2384 * but we didn't specify it. Paranoia again. */
2385 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2386 }
2387 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2388 char **argv = globdata.gl_pathv;
2389 while (1) {
2390 o_addstr_with_NUL(o, *argv);
2391 n = o_save_ptr_helper(o, n);
2392 argv++;
2393 if (!*argv)
2394 break;
2395 }
2396 }
2397 globfree(&globdata);
2398 }
2399 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002400}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002401/* Performs globbing on last list[],
2402 * saving each result as a new list[].
2403 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002404static int perform_glob(o_string *o, int n)
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002405{
2406 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002407
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002408 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002409 if (!o->data)
2410 return o_save_ptr_helper(o, n);
2411 pattern = o->data + o_get_last_ptr(o, n);
2412 debug_printf_glob("glob pattern '%s'\n", pattern);
2413 if (!glob_needed(pattern)) {
2414 /* unbackslash last string in o in place, fix length */
2415 o->length = unbackslash(pattern) - o->data;
2416 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2417 return o_save_ptr_helper(o, n);
2418 }
2419
2420 copy = xstrdup(pattern);
2421 /* "forget" pattern in o */
2422 o->length = pattern - o->data;
2423 n = glob_brace(copy, o, n);
2424 free(copy);
2425 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002426 debug_print_list("perform_glob returning", o, n);
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002427 return n;
2428}
2429
Denys Vlasenko238081f2010-10-03 14:26:26 +02002430#else /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002431
2432/* Helper */
2433static int glob_needed(const char *s)
2434{
2435 while (*s) {
2436 if (*s == '\\') {
2437 if (!s[1])
2438 return 0;
2439 s += 2;
2440 continue;
2441 }
2442 if (*s == '*' || *s == '[' || *s == '?')
2443 return 1;
2444 s++;
2445 }
2446 return 0;
2447}
2448/* Performs globbing on last list[],
2449 * saving each result as a new list[].
2450 */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002451static int perform_glob(o_string *o, int n)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002452{
2453 glob_t globdata;
2454 int gr;
2455 char *pattern;
2456
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002457 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002458 if (!o->data)
2459 return o_save_ptr_helper(o, n);
2460 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002461 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002462 if (!glob_needed(pattern)) {
2463 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002464 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002465 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002466 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002467 return o_save_ptr_helper(o, n);
2468 }
2469
2470 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002471 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2472 * If we glob "*.\*" and don't find anything, we need
2473 * to fall back to using literal "*.*", but GLOB_NOCHECK
2474 * will return "*.\*"!
2475 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002476 gr = glob(pattern, 0, NULL, &globdata);
2477 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002478 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002479 if (gr == GLOB_NOMATCH) {
2480 globfree(&globdata);
2481 goto literal;
2482 }
2483 if (gr == GLOB_NOSPACE)
2484 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002485 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2486 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002487 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002488 }
2489 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2490 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002491 /* "forget" pattern in o */
2492 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002493 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002494 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002495 n = o_save_ptr_helper(o, n);
2496 argv++;
2497 if (!*argv)
2498 break;
2499 }
2500 }
2501 globfree(&globdata);
2502 if (DEBUG_GLOB)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002503 debug_print_list("perform_glob returning", o, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002504 return n;
2505}
2506
Denys Vlasenko238081f2010-10-03 14:26:26 +02002507#endif /* !HUSH_BRACE_EXPANSION */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002508
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002509/* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002510 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002511static int o_save_ptr(o_string *o, int n)
2512{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02002513 if (o->o_expflags & EXP_FLAG_GLOB) {
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002514 /* If o->has_empty_slot, list[n] was already globbed
2515 * (if it was requested back then when it was filled)
2516 * so don't do that again! */
2517 if (!o->has_empty_slot)
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02002518 return perform_glob(o, n); /* o_save_ptr_helper is inside */
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002519 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002520 return o_save_ptr_helper(o, n);
2521}
2522
2523/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002524static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002525{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002526 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002527 int string_start;
2528
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002529 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2530 if (DEBUG_EXPAND)
2531 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002532 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002533 list = (char**)o->data;
2534 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2535 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002536 while (n) {
2537 n--;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002538 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002539 }
2540 return list;
2541}
2542
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002543static void free_pipe_list(struct pipe *pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002544
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002545/* Returns pi->next - next pipe in the list */
2546static struct pipe *free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002547{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002548 struct pipe *next;
2549 int i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002550
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002551 debug_printf_clean("free_pipe (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002552 for (i = 0; i < pi->num_cmds; i++) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002553 struct command *command;
2554 struct redir_struct *r, *rnext;
2555
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002556 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002557 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002558 if (command->argv) {
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002559 if (DEBUG_CLEAN) {
2560 int a;
2561 char **p;
2562 for (a = 0, p = command->argv; *p; a++, p++) {
2563 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2564 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002565 }
2566 free_strings(command->argv);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002567 //command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002568 }
2569 /* not "else if": on syntax error, we may have both! */
2570 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002571 debug_printf_clean(" begin group (cmd_type:%d)\n",
2572 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002573 free_pipe_list(command->group);
2574 debug_printf_clean(" end group\n");
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002575 //command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002576 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002577 /* else is crucial here.
2578 * If group != NULL, child_func is meaningless */
2579#if ENABLE_HUSH_FUNCTIONS
2580 else if (command->child_func) {
2581 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2582 command->child_func->parent_cmd = NULL;
2583 }
2584#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002585#if !BB_MMU
2586 free(command->group_as_string);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002587 //command->group_as_string = NULL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002588#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002589 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002590 debug_printf_clean(" redirect %d%s",
2591 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002592 /* guard against the case >$FOO, where foo is unset or blank */
2593 if (r->rd_filename) {
2594 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2595 free(r->rd_filename);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002596 //r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002597 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002598 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002599 rnext = r->next;
2600 free(r);
2601 }
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002602 //command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002603 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002604 free(pi->cmds); /* children are an array, they get freed all at once */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002605 //pi->cmds = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002606#if ENABLE_HUSH_JOB
2607 free(pi->cmdtext);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002608 //pi->cmdtext = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002609#endif
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002610
2611 next = pi->next;
2612 free(pi);
2613 return next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002614}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002615
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002616static void free_pipe_list(struct pipe *pi)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002617{
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002618 while (pi) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002619#if HAS_KEYWORDS
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002620 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002621#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002622 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denys Vlasenko27c56f12010-09-07 09:56:34 +02002623 pi = free_pipe(pi);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002624 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002625}
2626
2627
Denys Vlasenkob36abf22010-09-05 14:50:59 +02002628/*** Parsing routines ***/
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002629
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01002630#ifndef debug_print_tree
2631static void debug_print_tree(struct pipe *pi, int lvl)
2632{
2633 static const char *const PIPE[] = {
2634 [PIPE_SEQ] = "SEQ",
2635 [PIPE_AND] = "AND",
2636 [PIPE_OR ] = "OR" ,
2637 [PIPE_BG ] = "BG" ,
2638 };
2639 static const char *RES[] = {
2640 [RES_NONE ] = "NONE" ,
2641# if ENABLE_HUSH_IF
2642 [RES_IF ] = "IF" ,
2643 [RES_THEN ] = "THEN" ,
2644 [RES_ELIF ] = "ELIF" ,
2645 [RES_ELSE ] = "ELSE" ,
2646 [RES_FI ] = "FI" ,
2647# endif
2648# if ENABLE_HUSH_LOOPS
2649 [RES_FOR ] = "FOR" ,
2650 [RES_WHILE] = "WHILE",
2651 [RES_UNTIL] = "UNTIL",
2652 [RES_DO ] = "DO" ,
2653 [RES_DONE ] = "DONE" ,
2654# endif
2655# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2656 [RES_IN ] = "IN" ,
2657# endif
2658# if ENABLE_HUSH_CASE
2659 [RES_CASE ] = "CASE" ,
2660 [RES_CASE_IN ] = "CASE_IN" ,
2661 [RES_MATCH] = "MATCH",
2662 [RES_CASE_BODY] = "CASE_BODY",
2663 [RES_ESAC ] = "ESAC" ,
2664# endif
2665 [RES_XXXX ] = "XXXX" ,
2666 [RES_SNTX ] = "SNTX" ,
2667 };
2668 static const char *const CMDTYPE[] = {
2669 "{}",
2670 "()",
2671 "[noglob]",
2672# if ENABLE_HUSH_FUNCTIONS
2673 "func()",
2674# endif
2675 };
2676
2677 int pin, prn;
2678
2679 pin = 0;
2680 while (pi) {
2681 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2682 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2683 prn = 0;
2684 while (prn < pi->num_cmds) {
2685 struct command *command = &pi->cmds[prn];
2686 char **argv = command->argv;
2687
2688 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
2689 lvl*2, "", prn,
2690 command->assignment_cnt);
2691 if (command->group) {
2692 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
2693 CMDTYPE[command->cmd_type],
2694 argv
2695# if !BB_MMU
2696 , " group_as_string:", command->group_as_string
2697# else
2698 , "", ""
2699# endif
2700 );
2701 debug_print_tree(command->group, lvl+1);
2702 prn++;
2703 continue;
2704 }
2705 if (argv) while (*argv) {
2706 fprintf(stderr, " '%s'", *argv);
2707 argv++;
2708 }
2709 fprintf(stderr, "\n");
2710 prn++;
2711 }
2712 pi = pi->next;
2713 pin++;
2714 }
2715}
2716#endif /* debug_print_tree */
2717
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002718static struct pipe *new_pipe(void)
2719{
Eric Andersen25f27032001-04-26 23:22:31 +00002720 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002721 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002722 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002723 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002724 return pi;
2725}
2726
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002727/* Command (member of a pipe) is complete, or we start a new pipe
2728 * if ctx->command is NULL.
2729 * No errors possible here.
2730 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002731static int done_command(struct parse_context *ctx)
2732{
2733 /* The command is really already in the pipe structure, so
2734 * advance the pipe counter and make a new, null command. */
2735 struct pipe *pi = ctx->pipe;
2736 struct command *command = ctx->command;
2737
2738 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002739 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002740 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002741 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002742 }
2743 pi->num_cmds++;
2744 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002745 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002746 } else {
2747 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2748 }
2749
2750 /* Only real trickiness here is that the uncommitted
2751 * command structure is not counted in pi->num_cmds. */
2752 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002753 ctx->command = command = &pi->cmds[pi->num_cmds];
2754 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002755 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002756 return pi->num_cmds; /* used only for 0/nonzero check */
2757}
2758
2759static void done_pipe(struct parse_context *ctx, pipe_style type)
2760{
2761 int not_null;
2762
2763 debug_printf_parse("done_pipe entered, followup %d\n", type);
2764 /* Close previous command */
2765 not_null = done_command(ctx);
2766 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002767#if HAS_KEYWORDS
2768 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2769 ctx->ctx_inverted = 0;
2770 ctx->pipe->res_word = ctx->ctx_res_w;
2771#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002772
2773 /* Without this check, even just <enter> on command line generates
2774 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002775 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002776 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00002777#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002778 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00002779#endif
2780#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002781 || ctx->ctx_res_w == RES_DONE
2782 || ctx->ctx_res_w == RES_FOR
2783 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00002784#endif
2785#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002786 || ctx->ctx_res_w == RES_ESAC
2787#endif
2788 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002789 struct pipe *new_p;
2790 debug_printf_parse("done_pipe: adding new pipe: "
2791 "not_null:%d ctx->ctx_res_w:%d\n",
2792 not_null, ctx->ctx_res_w);
2793 new_p = new_pipe();
2794 ctx->pipe->next = new_p;
2795 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002796 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00002797 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002798 * This is used to control execution.
2799 * RES_FOR and RES_IN are NOT sticky (needed to support
2800 * cases where variable or value happens to match a keyword):
2801 */
2802#if ENABLE_HUSH_LOOPS
2803 if (ctx->ctx_res_w == RES_FOR
2804 || ctx->ctx_res_w == RES_IN)
2805 ctx->ctx_res_w = RES_NONE;
2806#endif
2807#if ENABLE_HUSH_CASE
2808 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002809 ctx->ctx_res_w = RES_CASE_BODY;
2810 if (ctx->ctx_res_w == RES_CASE)
2811 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002812#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002813 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002814 /* Create the memory for command, roughly:
2815 * ctx->pipe->cmds = new struct command;
2816 * ctx->command = &ctx->pipe->cmds[0];
2817 */
2818 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00002819 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002820 }
2821 debug_printf_parse("done_pipe return\n");
2822}
2823
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002824static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002825{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002826 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002827 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002828 /* Create the memory for command, roughly:
2829 * ctx->pipe->cmds = new struct command;
2830 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002831 */
2832 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002833}
2834
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002835/* If a reserved word is found and processed, parse context is modified
2836 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00002837 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002838#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002839struct reserved_combo {
2840 char literal[6];
2841 unsigned char res;
2842 unsigned char assignment_flag;
2843 int flag;
2844};
2845enum {
2846 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002847# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002848 FLAG_IF = (1 << RES_IF ),
2849 FLAG_THEN = (1 << RES_THEN ),
2850 FLAG_ELIF = (1 << RES_ELIF ),
2851 FLAG_ELSE = (1 << RES_ELSE ),
2852 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002853# endif
2854# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002855 FLAG_FOR = (1 << RES_FOR ),
2856 FLAG_WHILE = (1 << RES_WHILE),
2857 FLAG_UNTIL = (1 << RES_UNTIL),
2858 FLAG_DO = (1 << RES_DO ),
2859 FLAG_DONE = (1 << RES_DONE ),
2860 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002861# endif
2862# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002863 FLAG_MATCH = (1 << RES_MATCH),
2864 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002865# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002866 FLAG_START = (1 << RES_XXXX ),
2867};
2868
2869static const struct reserved_combo* match_reserved_word(o_string *word)
2870{
Eric Andersen25f27032001-04-26 23:22:31 +00002871 /* Mostly a list of accepted follow-up reserved words.
2872 * FLAG_END means we are done with the sequence, and are ready
2873 * to turn the compound list into a command.
2874 * FLAG_START means the word must start a new compound list.
2875 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002876 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002877# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002878 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2879 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2880 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2881 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2882 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2883 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002884# endif
2885# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002886 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2887 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2888 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2889 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2890 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2891 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002892# endif
2893# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002894 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2895 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002896# endif
Eric Andersen25f27032001-04-26 23:22:31 +00002897 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002898 const struct reserved_combo *r;
2899
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02002900 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002901 if (strcmp(word->data, r->literal) == 0)
2902 return r;
2903 }
2904 return NULL;
2905}
Denis Vlasenkobb929512009-04-16 10:59:40 +00002906/* Return 0: not a keyword, 1: keyword
2907 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002908static int reserved_word(o_string *word, struct parse_context *ctx)
2909{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002910# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002911 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002912 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002913 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002914# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002915 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002916
Denys Vlasenko38292b62010-09-05 14:49:40 +02002917 if (word->has_quoted_part)
Denis Vlasenkobb929512009-04-16 10:59:40 +00002918 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002919 r = match_reserved_word(word);
2920 if (!r)
2921 return 0;
2922
2923 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002924# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002925 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
2926 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002927 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02002928 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002929# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002930 if (r->flag == 0) { /* '!' */
2931 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002932 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00002933 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002934 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002935 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002936 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002937 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002938 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002939 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002940
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002941 old = xmalloc(sizeof(*old));
2942 debug_printf_parse("push stack %p\n", old);
2943 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002944 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002945 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002946 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002947 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002948 ctx->ctx_res_w = RES_SNTX;
2949 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002950 } else {
2951 /* "{...} fi" is ok. "{...} if" is not
2952 * Example:
2953 * if { echo foo; } then { echo bar; } fi */
2954 if (ctx->command->group)
2955 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002956 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00002957
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002958 ctx->ctx_res_w = r->res;
2959 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002960 word->o_assignment = r->assignment_flag;
2961
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002962 if (ctx->old_flag & FLAG_END) {
2963 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00002964
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002965 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002966 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002967 old = ctx->stack;
2968 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002969 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002970# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002971 o_addstr(&old->as_string, ctx->as_string.data);
2972 o_free_unsafe(&ctx->as_string);
2973 old->command->group_as_string = xstrdup(old->as_string.data);
2974 debug_printf_parse("pop, remembering as:'%s'\n",
2975 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002976# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002977 *ctx = *old; /* physical copy */
2978 free(old);
2979 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002980 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002981}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002982#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00002983
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002984/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002985 * Normal return is 0. Syntax errors return 1.
2986 * Note: on return, word is reset, but not o_free'd!
2987 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002988static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002989{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002990 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00002991
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002992 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denys Vlasenko38292b62010-09-05 14:49:40 +02002993 if (word->length == 0 && !word->has_quoted_part) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002994 debug_printf_parse("done_word return 0: true null, ignored\n");
2995 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002996 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002997
Eric Andersen25f27032001-04-26 23:22:31 +00002998 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002999 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3000 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003001 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3002 * "2.7 Redirection
3003 * ...the word that follows the redirection operator
3004 * shall be subjected to tilde expansion, parameter expansion,
3005 * command substitution, arithmetic expansion, and quote
3006 * removal. Pathname expansion shall not be performed
3007 * on the word by a non-interactive shell; an interactive
3008 * shell may perform it, but shall do so only when
3009 * the expansion would result in one word."
3010 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003011 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003012 /* Cater for >\file case:
3013 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3014 * Same with heredocs:
3015 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3016 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003017 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3018 unbackslash(ctx->pending_redirect->rd_filename);
3019 /* Is it <<"HEREDOC"? */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003020 if (word->has_quoted_part) {
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003021 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3022 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003023 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003024 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003025 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003026 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003027 /* If this word wasn't an assignment, next ones definitely
3028 * can't be assignments. Even if they look like ones. */
3029 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3030 && word->o_assignment != WORD_IS_KEYWORD
3031 ) {
3032 word->o_assignment = NOT_ASSIGNMENT;
3033 } else {
3034 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3035 command->assignment_cnt++;
3036 word->o_assignment = MAYBE_ASSIGNMENT;
3037 }
3038
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003039#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003040# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003041 if (ctx->ctx_dsemicolon
3042 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3043 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003044 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003045 /* ctx->ctx_res_w = RES_MATCH; */
3046 ctx->ctx_dsemicolon = 0;
3047 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003048# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003049 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003050# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003051 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3052 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003053# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003054# if ENABLE_HUSH_CASE
3055 && ctx->ctx_res_w != RES_CASE
3056# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003057 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003058 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003059 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003060 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003061 debug_printf_parse("done_word return %d\n",
3062 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003063 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003064 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003065# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003066 if (strcmp(word->data, "[[") == 0) {
3067 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3068 }
3069 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003070# endif
Eric Andersen25f27032001-04-26 23:22:31 +00003071 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003072#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00003073 if (command->group) {
3074 /* "{ echo foo; } echo bar" - bad */
3075 syntax_error_at(word->data);
3076 debug_printf_parse("done_word return 1: syntax error, "
3077 "groups and arglists don't mix\n");
3078 return 1;
3079 }
Denys Vlasenko38292b62010-09-05 14:49:40 +02003080 if (word->has_quoted_part
Denis Vlasenko55789c62008-06-18 16:30:42 +00003081 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3082 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003083 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003084 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003085 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003086 char *p = word->data;
3087 while (p[0] == SPECIAL_VAR_SYMBOL
3088 && (p[1] & 0x7f) == '@'
3089 && p[2] == SPECIAL_VAR_SYMBOL
3090 ) {
3091 p += 3;
3092 }
3093 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003094 /* saw no "$@", or not only "$@" but some
3095 * real text is there too */
3096 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003097 * e.g. "", $empty"" etc to not disappear */
3098 o_addchr(word, SPECIAL_VAR_SYMBOL);
3099 o_addchr(word, SPECIAL_VAR_SYMBOL);
3100 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003101 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003102 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003103 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003104 }
Eric Andersen25f27032001-04-26 23:22:31 +00003105
Denis Vlasenko06810332007-05-21 23:30:54 +00003106#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003107 if (ctx->ctx_res_w == RES_FOR) {
Denys Vlasenko38292b62010-09-05 14:49:40 +02003108 if (word->has_quoted_part
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003109 || !is_well_formed_var_name(command->argv[0], '\0')
3110 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003111 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003112 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003113 return 1;
3114 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003115 /* Force FOR to have just one word (variable name) */
3116 /* NB: basically, this makes hush see "for v in ..."
3117 * syntax as if it is "for v; in ...". FOR and IN become
3118 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003119 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003120 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003121#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003122#if ENABLE_HUSH_CASE
3123 /* Force CASE to have just one word */
3124 if (ctx->ctx_res_w == RES_CASE) {
3125 done_pipe(ctx, PIPE_SEQ);
3126 }
3127#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003128
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003129 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00003130
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003131 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003132 return 0;
3133}
3134
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003135
3136/* Peek ahead in the input to find out if we have a "&n" construct,
3137 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003138 * Return:
3139 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3140 * REDIRFD_SYNTAX_ERR if syntax error,
3141 * REDIRFD_TO_FILE if no & was seen,
3142 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003143 */
3144#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003145#define parse_redir_right_fd(as_string, input) \
3146 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003147#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003148static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003149{
3150 int ch, d, ok;
3151
3152 ch = i_peek(input);
3153 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003154 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003155
3156 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003157 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003158 ch = i_peek(input);
3159 if (ch == '-') {
3160 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003161 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003162 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003163 }
3164 d = 0;
3165 ok = 0;
3166 while (ch != EOF && isdigit(ch)) {
3167 d = d*10 + (ch-'0');
3168 ok = 1;
3169 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003170 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003171 ch = i_peek(input);
3172 }
3173 if (ok) return d;
3174
3175//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3176
3177 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003178 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003179}
3180
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003181/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003182 */
3183static int parse_redirect(struct parse_context *ctx,
3184 int fd,
3185 redir_type style,
3186 struct in_str *input)
3187{
3188 struct command *command = ctx->command;
3189 struct redir_struct *redir;
3190 struct redir_struct **redirp;
3191 int dup_num;
3192
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003193 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003194 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003195 /* Check for a '>&1' type redirect */
3196 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3197 if (dup_num == REDIRFD_SYNTAX_ERR)
3198 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003199 } else {
3200 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003201 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003202 if (dup_num) { /* <<-... */
3203 ch = i_getch(input);
3204 nommu_addchr(&ctx->as_string, ch);
3205 ch = i_peek(input);
3206 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003207 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003208
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003209 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003210 int ch = i_peek(input);
3211 if (ch == '|') {
3212 /* >|FILE redirect ("clobbering" >).
3213 * Since we do not support "set -o noclobber" yet,
3214 * >| and > are the same for now. Just eat |.
3215 */
3216 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003217 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003218 }
3219 }
3220
3221 /* Create a new redir_struct and append it to the linked list */
3222 redirp = &command->redirects;
3223 while ((redir = *redirp) != NULL) {
3224 redirp = &(redir->next);
3225 }
3226 *redirp = redir = xzalloc(sizeof(*redir));
3227 /* redir->next = NULL; */
3228 /* redir->rd_filename = NULL; */
3229 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003230 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003231
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003232 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3233 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003234
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003235 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003236 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003237 /* Erik had a check here that the file descriptor in question
3238 * is legit; I postpone that to "run time"
3239 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003240 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3241 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003242 } else {
3243 /* Set ctx->pending_redirect, so we know what to do at the
3244 * end of the next parsed word. */
3245 ctx->pending_redirect = redir;
3246 }
3247 return 0;
3248}
3249
Eric Andersen25f27032001-04-26 23:22:31 +00003250/* If a redirect is immediately preceded by a number, that number is
3251 * supposed to tell which file descriptor to redirect. This routine
3252 * looks for such preceding numbers. In an ideal world this routine
3253 * needs to handle all the following classes of redirects...
3254 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3255 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3256 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3257 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003258 *
3259 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3260 * "2.7 Redirection
3261 * ... If n is quoted, the number shall not be recognized as part of
3262 * the redirection expression. For example:
3263 * echo \2>a
3264 * writes the character 2 into file a"
Denys Vlasenko38292b62010-09-05 14:49:40 +02003265 * We are getting it right by setting ->has_quoted_part on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003266 *
3267 * A -1 return means no valid number was found,
3268 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00003269 */
3270static int redirect_opt_num(o_string *o)
3271{
3272 int num;
3273
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003274 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003275 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003276 num = bb_strtou(o->data, NULL, 10);
3277 if (errno || num < 0)
3278 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003279 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003280 return num;
3281}
3282
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003283#if BB_MMU
3284#define fetch_till_str(as_string, input, word, skip_tabs) \
3285 fetch_till_str(input, word, skip_tabs)
3286#endif
3287static char *fetch_till_str(o_string *as_string,
3288 struct in_str *input,
3289 const char *word,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003290 int heredoc_flags)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003291{
3292 o_string heredoc = NULL_O_STRING;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003293 unsigned past_EOL;
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003294 int prev = 0; /* not \ */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003295 int ch;
3296
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003297 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003298 while (1) {
3299 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003300 if (ch != EOF)
3301 nommu_addchr(as_string, ch);
3302 if ((ch == '\n' || ch == EOF)
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003303 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3304 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003305 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3306 heredoc.data[past_EOL] = '\0';
3307 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3308 return heredoc.data;
3309 }
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003310 while (ch == '\n') {
3311 o_addchr(&heredoc, ch);
3312 prev = ch;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003313 jump_in:
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003314 past_EOL = heredoc.length;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003315 do {
3316 ch = i_getch(input);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003317 if (ch != EOF)
3318 nommu_addchr(as_string, ch);
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003319 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003320 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003321 }
3322 if (ch == EOF) {
3323 o_free_unsafe(&heredoc);
3324 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003325 }
3326 o_addchr(&heredoc, ch);
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02003327 nommu_addchr(as_string, ch);
Denys Vlasenkoc3adfac2010-09-06 11:46:03 +02003328 if (prev == '\\' && ch == '\\')
3329 /* Correctly handle foo\\<eol> (not a line cont.) */
3330 prev = 0; /* not \ */
3331 else
3332 prev = ch;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003333 }
3334}
3335
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003336/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3337 * and load them all. There should be exactly heredoc_cnt of them.
3338 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003339static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3340{
3341 struct pipe *pi = ctx->list_head;
3342
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003343 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003344 int i;
3345 struct command *cmd = pi->cmds;
3346
3347 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3348 pi->num_cmds,
3349 cmd->argv ? cmd->argv[0] : "NONE");
3350 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003351 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003352
3353 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3354 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003355 while (redir) {
3356 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003357 char *p;
3358
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003359 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003360 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003361 p = fetch_till_str(&ctx->as_string, input,
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02003362 redir->rd_filename, redir->rd_dup);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003363 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003364 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003365 return 1;
3366 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003367 free(redir->rd_filename);
3368 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003369 heredoc_cnt--;
3370 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003371 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003372 }
3373 cmd++;
3374 }
3375 pi = pi->next;
3376 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003377#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003378 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003379 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003380 bb_error_msg_and_die("heredoc BUG 2");
3381#endif
3382 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003383}
3384
3385
Denys Vlasenkob36abf22010-09-05 14:50:59 +02003386static int run_list(struct pipe *pi);
3387#if BB_MMU
3388#define parse_stream(pstring, input, end_trigger) \
3389 parse_stream(input, end_trigger)
3390#endif
3391static struct pipe *parse_stream(char **pstring,
3392 struct in_str *input,
3393 int end_trigger);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003394
Eric Andersen25f27032001-04-26 23:22:31 +00003395
Denys Vlasenkoc2704542009-11-20 19:14:19 +01003396#if !ENABLE_HUSH_FUNCTIONS
3397#define parse_group(dest, ctx, input, ch) \
3398 parse_group(ctx, input, ch)
3399#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003400static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003401 struct in_str *input, int ch)
3402{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003403 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003404 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003405 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003406 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003407 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003408 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003409
3410 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003411#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko38292b62010-09-05 14:49:40 +02003412 if (ch == '(' && !dest->has_quoted_part) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003413 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00003414 if (done_word(dest, ctx))
3415 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003416 if (!command->argv)
3417 goto skip; /* (... */
3418 if (command->argv[1]) { /* word word ... (... */
3419 syntax_error_unexpected_ch('(');
3420 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003421 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003422 /* it is "word(..." or "word (..." */
3423 do
3424 ch = i_getch(input);
3425 while (ch == ' ' || ch == '\t');
3426 if (ch != ')') {
3427 syntax_error_unexpected_ch(ch);
3428 return 1;
3429 }
3430 nommu_addchr(&ctx->as_string, ch);
3431 do
3432 ch = i_getch(input);
3433 while (ch == ' ' || ch == '\t' || ch == '\n');
3434 if (ch != '{') {
3435 syntax_error_unexpected_ch(ch);
3436 return 1;
3437 }
3438 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003439 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003440 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003441 }
3442#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003443
3444#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003445 if (command->argv /* word [word]{... */
3446 || dest->length /* word{... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02003447 || dest->has_quoted_part /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003448 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003449 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003450 debug_printf_parse("parse_group return 1: "
3451 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003452 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003453 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01003454#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003455
3456#if ENABLE_HUSH_FUNCTIONS
3457 skip:
3458#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00003459 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003460 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003461 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003462 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00003463 } else {
3464 /* bash does not allow "{echo...", requires whitespace */
3465 ch = i_getch(input);
3466 if (ch != ' ' && ch != '\t' && ch != '\n') {
3467 syntax_error_unexpected_ch(ch);
3468 return 1;
3469 }
3470 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003471 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003472
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003473 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003474#if BB_MMU
3475# define as_string NULL
3476#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003477 char *as_string = NULL;
3478#endif
3479 pipe_list = parse_stream(&as_string, input, endch);
3480#if !BB_MMU
3481 if (as_string)
3482 o_addstr(&ctx->as_string, as_string);
3483#endif
3484 /* empty ()/{} or parse error? */
3485 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00003486 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003487 if (!BB_MMU)
3488 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003489 debug_printf_parse("parse_group return 1: "
3490 "parse_stream returned %p\n", pipe_list);
3491 return 1;
3492 }
3493 command->group = pipe_list;
3494#if !BB_MMU
3495 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3496 command->group_as_string = as_string;
3497 debug_printf_parse("end of group, remembering as:'%s'\n",
3498 command->group_as_string);
3499#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003500#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003501 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003502 debug_printf_parse("parse_group return 0\n");
3503 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003504 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003505}
3506
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003507#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003508/* Subroutines for copying $(...) and `...` things */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003509static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003510/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003511static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003512{
3513 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003514 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003515 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003516 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003517 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003518 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003519 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003520 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003521 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003522 }
3523}
3524/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003525static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003526{
3527 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003528 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003529 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003530 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003531 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003532 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003533 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003534 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003535 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003536 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003537 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003538 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003539 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003540 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003541 add_till_backquote(dest, input, /*in_dquote:*/ 1);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003542 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003543 continue;
3544 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003545 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003546 }
3547}
3548/* Process `cmd` - copy contents until "`" is seen. Complicated by
3549 * \` quoting.
3550 * "Within the backquoted style of command substitution, backslash
3551 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3552 * The search for the matching backquote shall be satisfied by the first
3553 * backquote found without a preceding backslash; during this search,
3554 * if a non-escaped backquote is encountered within a shell comment,
3555 * a here-document, an embedded command substitution of the $(command)
3556 * form, or a quoted string, undefined results occur. A single-quoted
3557 * or double-quoted string that begins, but does not end, within the
3558 * "`...`" sequence produces undefined results."
3559 * Example Output
3560 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3561 */
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003562static void add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003563{
3564 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003565 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003566 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003567 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003568 if (ch == '\\') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003569 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3570 ch = i_getch(input);
3571 if (ch != '`'
3572 && ch != '$'
3573 && ch != '\\'
3574 && (!in_dquote || ch != '"')
3575 ) {
3576 o_addchr(dest, '\\');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003577 }
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003578 }
3579 if (ch == EOF) {
3580 syntax_error_unterm_ch('`');
3581 /*xfunc_die(); - redundant */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003582 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003583 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003584 }
3585}
3586/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3587 * quoting and nested ()s.
3588 * "With the $(command) style of command substitution, all characters
3589 * following the open parenthesis to the matching closing parenthesis
3590 * constitute the command. Any valid shell script can be used for command,
3591 * except a script consisting solely of redirections which produces
3592 * unspecified results."
3593 * Example Output
3594 * echo $(echo '(TEST)' BEST) (TEST) BEST
3595 * echo $(echo 'TEST)' BEST) TEST) BEST
3596 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02003597 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003598 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003599 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003600 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3601 * for ${var:N[:M]} and ${var/P[/R]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003602 */
Denys Vlasenko74369502010-05-21 19:52:01 +02003603#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003604static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003605{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003606 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02003607 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003608# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003609 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003610# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003611 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3612
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003613 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003614 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003615 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003616 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003617 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003618 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003619 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003620 if (!dbl)
3621 break;
3622 /* we look for closing )) of $((EXPR)) */
3623 if (i_peek(input) == end_ch) {
3624 i_getch(input); /* eat second ')' */
3625 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003626 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003627 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003628 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003629 if (ch == '(' || ch == '{') {
3630 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003631 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003632 o_addchr(dest, ch);
3633 continue;
3634 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003635 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003636 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003637 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003638 continue;
3639 }
3640 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003641 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003642 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003643 continue;
3644 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003645 if (ch == '`') {
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003646 add_till_backquote(dest, input, /*in_dquote:*/ 0);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02003647 o_addchr(dest, ch);
3648 continue;
3649 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003650 if (ch == '\\') {
3651 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003652 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003653 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003654 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003655 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00003656 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003657 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003658 continue;
3659 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003660 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003661 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003662}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003663#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003664
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003665/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003666#if BB_MMU
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003667#define parse_dollar(as_string, dest, input, quote_mask) \
3668 parse_dollar(dest, input, quote_mask)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003669#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003670#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003671static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003672 o_string *dest,
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003673 struct in_str *input, unsigned char quote_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003674{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003675 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003676
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003677 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003678 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003679 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003680 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00003681 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003682 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003683 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003684 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003685 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003686 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003687 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003688 if (!isalnum(ch) && ch != '_')
3689 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003690 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003691 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003692 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003693 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003694 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003695 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003696 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003697 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003698 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003699 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003700 o_addchr(dest, ch | quote_mask);
3701 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003702 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003703 case '$': /* pid */
3704 case '!': /* last bg pid */
3705 case '?': /* last exit code */
3706 case '#': /* number of args */
3707 case '*': /* args */
3708 case '@': /* args */
3709 goto make_one_char_var;
3710 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04003711 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3712
Denys Vlasenko74369502010-05-21 19:52:01 +02003713 ch = i_getch(input); /* eat '{' */
3714 nommu_addchr(as_string, ch);
3715
3716 ch = i_getch(input); /* first char after '{' */
Denys Vlasenko74369502010-05-21 19:52:01 +02003717 /* It should be ${?}, or ${#var},
3718 * or even ${?+subst} - operator acting on a special variable,
3719 * or the beginning of variable name.
3720 */
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003721 if (ch == EOF
3722 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3723 ) {
Denys Vlasenko74369502010-05-21 19:52:01 +02003724 bad_dollar_syntax:
3725 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003726 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02003727 return 1;
3728 }
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003729 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003730 ch |= quote_mask;
3731
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003732 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02003733 * However, this regresses some of our testsuite cases
3734 * which check invalid constructs like ${%}.
3735 * Oh well... let's check that the var name part is fine... */
3736
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003737 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003738 unsigned pos;
3739
Denys Vlasenko74369502010-05-21 19:52:01 +02003740 o_addchr(dest, ch);
3741 debug_printf_parse(": '%c'\n", ch);
3742
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003743 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003744 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02003745 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00003746 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00003747
Denys Vlasenko74369502010-05-21 19:52:01 +02003748 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003749 unsigned end_ch;
3750 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003751 /* handle parameter expansions
3752 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3753 */
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003754 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
Denys Vlasenko74369502010-05-21 19:52:01 +02003755 goto bad_dollar_syntax;
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003756
3757 /* Eat everything until closing '}' (or ':') */
3758 end_ch = '}';
3759 if (ENABLE_HUSH_BASH_COMPAT
3760 && ch == ':'
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003761 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003762 ) {
3763 /* It's ${var:N[:M]} thing */
3764 end_ch = '}' * 0x100 + ':';
3765 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003766 if (ENABLE_HUSH_BASH_COMPAT
3767 && ch == '/'
3768 ) {
3769 /* It's ${var/[/]pattern[/repl]} thing */
3770 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3771 i_getch(input);
3772 nommu_addchr(as_string, '/');
3773 ch = '\\';
3774 }
3775 end_ch = '}' * 0x100 + '/';
3776 }
3777 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003778 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003779 if (!BB_MMU)
3780 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003781#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003782 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02003783#else
3784#error Simple code to only allow ${var} is not implemented
3785#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003786 if (as_string) {
3787 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003788 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003789 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003790
3791 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3792 /* close the first block: */
3793 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003794 /* while parsing N from ${var:N[:M]}
3795 * or pattern from ${var/[/]pattern[/repl]} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003796 if ((end_ch & 0xff) == last_ch) {
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003797 /* got ':' or '/'- parse the rest */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003798 end_ch = '}';
3799 goto again;
3800 }
Denys Vlasenko36f774a2010-09-05 14:45:38 +02003801 /* got '}' */
3802 if (end_ch == '}' * 0x100 + ':') {
3803 /* it's ${var:N} - emulate :999999999 */
3804 o_addstr(dest, "999999999");
3805 } /* else: it's ${var/[/]pattern} */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02003806 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003807 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003808 }
Denys Vlasenko74369502010-05-21 19:52:01 +02003809 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003810 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3811 break;
3812 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003813#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003814 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003815 unsigned pos;
3816
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003817 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003818 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003819# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003820 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003821 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003822 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003823 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3824 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003825 if (!BB_MMU)
3826 pos = dest->length;
3827 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003828 if (as_string) {
3829 o_addstr(as_string, dest->data + pos);
3830 o_addchr(as_string, ')');
3831 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003832 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003833 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003834 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003835 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003836# endif
3837# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003838 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3839 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003840 if (!BB_MMU)
3841 pos = dest->length;
3842 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003843 if (as_string) {
3844 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01003845 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003846 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003847 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003848# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003849 break;
3850 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00003851#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003852 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003853 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003854 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003855 ch = i_peek(input);
3856 if (isalnum(ch)) { /* it's $_name or $_123 */
3857 ch = '_';
3858 goto make_var;
3859 }
3860 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02003861 /* TODO: $_ and $-: */
3862 /* $_ Shell or shell script name; or last argument of last command
3863 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
3864 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003865 /* $- Option flags set by set builtin or shell options (-i etc) */
3866 default:
3867 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003868 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003869 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003870 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003871#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00003872}
3873
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003874#if BB_MMU
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003875# if ENABLE_HUSH_BASH_COMPAT
3876#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3877 encode_string(dest, input, dquote_end, process_bkslash)
3878# else
3879/* only ${var/pattern/repl} (its pattern part) needs additional mode */
3880#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3881 encode_string(dest, input, dquote_end)
3882# endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003883#define as_string NULL
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003884
3885#else /* !MMU */
3886
3887# if ENABLE_HUSH_BASH_COMPAT
3888/* all parameters are needed, no macro tricks */
3889# else
3890#define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
3891 encode_string(as_string, dest, input, dquote_end)
3892# endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003893#endif
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003894static int encode_string(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003895 o_string *dest,
3896 struct in_str *input,
Denys Vlasenko14e289b2010-09-10 10:15:18 +02003897 int dquote_end,
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003898 int process_bkslash)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003899{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003900#if !ENABLE_HUSH_BASH_COMPAT
3901 const int process_bkslash = 1;
3902#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00003903 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003904 int next;
3905
3906 again:
3907 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003908 if (ch != EOF)
3909 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003910 if (ch == dquote_end) { /* may be only '"' or EOF */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003911 debug_printf_parse("encode_string return 0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003912 return 0;
3913 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00003914 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003915 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00003916 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003917 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003918 }
3919 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003920 if (ch != '\n') {
3921 next = i_peek(input);
3922 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003923 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003924 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003925 if (process_bkslash && ch == '\\') {
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003926 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003927 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00003928 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003929 }
3930 /* bash:
3931 * "The backslash retains its special meaning [in "..."]
3932 * only when followed by one of the following characters:
3933 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003934 * within double quotes by preceding it with a backslash."
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003935 * NB: in (unquoted) heredoc, above does not apply to ",
3936 * therefore we check for it by "next == dquote_end" cond.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003937 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003938 if (next == dquote_end || strchr("$`\\\n", next)) {
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003939 ch = i_getch(input); /* eat next */
3940 if (ch == '\n')
3941 goto again; /* skip \<newline> */
Denys Vlasenko4f870492010-09-10 11:06:01 +02003942 } /* else: ch remains == '\\', and we double it below: */
3943 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
Denys Vlasenko850b15b2010-09-09 12:58:19 +02003944 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003945 goto again;
3946 }
3947 if (ch == '$') {
Denys Vlasenko101a4e32010-09-09 14:04:57 +02003948 if (parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80) != 0) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02003949 debug_printf_parse("encode_string return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02003950 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003951 return 1;
3952 }
3953 goto again;
3954 }
3955#if ENABLE_HUSH_TICK
3956 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003957 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003958 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3959 o_addchr(dest, 0x80 | '`');
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02003960 add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003961 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3962 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00003963 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003964 }
3965#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00003966 o_addQchr(dest, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003967 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02003968#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003969}
3970
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003971/*
3972 * Scan input until EOF or end_trigger char.
3973 * Return a list of pipes to execute, or NULL on EOF
3974 * or if end_trigger character is met.
3975 * On syntax error, exit is shell is not interactive,
3976 * reset parsing machinery and start parsing anew,
3977 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003978 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003979static struct pipe *parse_stream(char **pstring,
3980 struct in_str *input,
3981 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003982{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003983 struct parse_context ctx;
3984 o_string dest = NULL_O_STRING;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003985 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00003986
Denys Vlasenko77a7b552010-09-09 12:40:03 +02003987 /* Single-quote triggers a bypass of the main loop until its mate is
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02003988 * found. When recursing, quote state is passed in via dest->o_expflags.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003989 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003990 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02003991 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003992 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003993
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003994 /* If very first arg is "" or '', dest.data may end up NULL.
3995 * Preventing this: */
3996 o_addchr(&dest, '\0');
3997 dest.length = 0;
3998
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02003999 /* We used to separate words on $IFS here. This was wrong.
4000 * $IFS is used only for word splitting when $var is expanded,
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004001 * here we should use blank chars as separators, not $IFS
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004002 */
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004003
4004 reset: /* we come back here only on syntax errors in interactive shell */
4005
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004006#if ENABLE_HUSH_INTERACTIVE
4007 input->promptmode = 0; /* PS1 */
4008#endif
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004009 if (MAYBE_ASSIGNMENT != 0)
4010 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004011 initialize_context(&ctx);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004012 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004013 while (1) {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004014 const char *is_blank;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004015 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004016 int ch;
4017 int next;
4018 int redir_fd;
4019 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004020
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004021 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004022 debug_printf_parse(": ch=%c (%d) escape=%d\n",
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02004023 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004024 if (ch == EOF) {
4025 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004026
4027 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004028 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004029 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004030 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004031 /* end_trigger == '}' case errors out earlier,
4032 * checking only ')' */
4033 if (end_trigger == ')') {
4034 syntax_error_unterm_ch('('); /* exits */
4035 /* goto parse_error; */
4036 }
4037
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004038 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02004039 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004040 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004041 o_free(&dest);
4042 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004043 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004044 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004045 /* (this makes bare "&" cmd a no-op.
4046 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004047 if (pi->num_cmds == 0
4048 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4049 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004050 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004051 pi = NULL;
4052 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004053#if !BB_MMU
4054 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4055 if (pstring)
4056 *pstring = ctx.as_string.data;
4057 else
4058 o_free_unsafe(&ctx.as_string);
4059#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004060 debug_leave();
4061 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004062 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004063 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004064 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004065
4066 next = '\0';
4067 if (ch != '\n')
4068 next = i_peek(input);
4069
4070 is_special = "{}<>;&|()#'" /* special outside of "str" */
4071 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4072 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004073 if (ctx.command->argv /* word [word]{... - non-special */
4074 || dest.length /* word{... - non-special */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004075 || dest.has_quoted_part /* ""{... - non-special */
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004076 || (next != ';' /* }; - special */
4077 && next != ')' /* }) - special */
4078 && next != '&' /* }& and }&& ... - special */
4079 && next != '|' /* }|| ... - special */
4080 && !strchr(defifs, next) /* {word - non-special */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02004081 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01004082 ) {
4083 /* They are not special, skip "{}" */
4084 is_special += 2;
4085 }
4086 is_special = strchr(is_special, ch);
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004087 is_blank = strchr(defifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004088
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004089 if (!is_special && !is_blank) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00004090 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004091 o_addQchr(&dest, ch);
4092 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4093 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004094 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004095 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00004096 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004097 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004098 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004099 continue;
4100 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004101
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004102 if (is_blank) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004103 if (done_word(&dest, &ctx)) {
4104 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004105 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004106 if (ch == '\n') {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004107 /* Is this a case when newline is simply ignored?
4108 * Some examples:
4109 * "cmd | <newline> cmd ..."
4110 * "case ... in <newline> word) ..."
4111 */
4112 if (IS_NULL_CMD(ctx.command)
4113 && dest.length == 0 && !dest.has_quoted_part
Denis Vlasenkof1736072008-07-31 10:09:26 +00004114 ) {
4115 continue;
4116 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004117 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004118 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004119 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4120 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004121 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004122 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004123 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004124 heredoc_cnt = 0;
4125 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004126 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004127 ch = ';';
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004128 /* note: if (is_blank) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004129 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004130 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004131 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004132
4133 /* "cmd}" or "cmd }..." without semicolon or &:
4134 * } is an ordinary char in this case, even inside { cmd; }
4135 * Pathological example: { ""}; } should exec "}" cmd
4136 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004137 if (ch == '}') {
4138 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4139 || dest.length != 0 /* word} */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004140 || dest.has_quoted_part /* ""} */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004141 ) {
4142 goto ordinary_char;
4143 }
4144 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4145 goto skip_end_trigger;
4146 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00004147 }
4148
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004149 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004150 && (ch != ';' || heredoc_cnt == 0)
4151#if ENABLE_HUSH_CASE
4152 && (ch != ')'
4153 || ctx.ctx_res_w != RES_MATCH
Denys Vlasenko38292b62010-09-05 14:49:40 +02004154 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004155 )
4156#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004157 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004158 if (heredoc_cnt) {
4159 /* This is technically valid:
4160 * { cat <<HERE; }; echo Ok
4161 * heredoc
4162 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004163 * HERE
4164 * but we don't support this.
4165 * We require heredoc to be in enclosing {}/(),
4166 * if any.
4167 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004168 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004169 goto parse_error;
4170 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004171 if (done_word(&dest, &ctx)) {
4172 goto parse_error;
4173 }
4174 done_pipe(&ctx, PIPE_SEQ);
4175 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004176 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004177 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004178 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004179 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004180 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004181#if !BB_MMU
4182 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4183 if (pstring)
4184 *pstring = ctx.as_string.data;
4185 else
4186 o_free_unsafe(&ctx.as_string);
4187#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004188 debug_leave();
4189 debug_printf_parse("parse_stream return %p: "
4190 "end_trigger char found\n",
4191 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004192 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004193 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004194 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00004195 skip_end_trigger:
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004196 if (is_blank)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004197 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004198
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004199 /* Catch <, > before deciding whether this word is
4200 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4201 switch (ch) {
4202 case '>':
4203 redir_fd = redirect_opt_num(&dest);
4204 if (done_word(&dest, &ctx)) {
4205 goto parse_error;
4206 }
4207 redir_style = REDIRECT_OVERWRITE;
4208 if (next == '>') {
4209 redir_style = REDIRECT_APPEND;
4210 ch = i_getch(input);
4211 nommu_addchr(&ctx.as_string, ch);
4212 }
4213#if 0
4214 else if (next == '(') {
4215 syntax_error(">(process) not supported");
4216 goto parse_error;
4217 }
4218#endif
4219 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4220 goto parse_error;
4221 continue; /* back to top of while (1) */
4222 case '<':
4223 redir_fd = redirect_opt_num(&dest);
4224 if (done_word(&dest, &ctx)) {
4225 goto parse_error;
4226 }
4227 redir_style = REDIRECT_INPUT;
4228 if (next == '<') {
4229 redir_style = REDIRECT_HEREDOC;
4230 heredoc_cnt++;
4231 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4232 ch = i_getch(input);
4233 nommu_addchr(&ctx.as_string, ch);
4234 } else if (next == '>') {
4235 redir_style = REDIRECT_IO;
4236 ch = i_getch(input);
4237 nommu_addchr(&ctx.as_string, ch);
4238 }
4239#if 0
4240 else if (next == '(') {
4241 syntax_error("<(process) not supported");
4242 goto parse_error;
4243 }
4244#endif
4245 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4246 goto parse_error;
4247 continue; /* back to top of while (1) */
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004248 case '#':
4249 if (dest.length == 0 && !dest.has_quoted_part) {
4250 /* skip "#comment" */
4251 while (1) {
4252 ch = i_peek(input);
4253 if (ch == EOF || ch == '\n')
4254 break;
4255 i_getch(input);
4256 /* note: we do not add it to &ctx.as_string */
4257 }
4258 nommu_addchr(&ctx.as_string, '\n');
4259 continue; /* back to top of while (1) */
4260 }
4261 break;
4262 case '\\':
4263 if (next == '\n') {
4264 /* It's "\<newline>" */
4265#if !BB_MMU
4266 /* Remove trailing '\' from ctx.as_string */
4267 ctx.as_string.data[--ctx.as_string.length] = '\0';
4268#endif
4269 ch = i_getch(input); /* eat it */
4270 continue; /* back to top of while (1) */
4271 }
4272 break;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004273 }
4274
4275 if (dest.o_assignment == MAYBE_ASSIGNMENT
4276 /* check that we are not in word in "a=1 2>word b=1": */
4277 && !ctx.pending_redirect
4278 ) {
4279 /* ch is a special char and thus this word
4280 * cannot be an assignment */
4281 dest.o_assignment = NOT_ASSIGNMENT;
4282 }
4283
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02004284 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4285
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004286 switch (ch) {
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004287 case '#': /* non-comment #: "echo a#b" etc */
4288 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004289 break;
4290 case '\\':
4291 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004292 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004293 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00004294 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004295 ch = i_getch(input);
Denys Vlasenko7b4c0fd2010-11-22 17:58:14 +01004296 /* note: ch != '\n' (that case does not reach this place) */
4297 o_addchr(&dest, '\\');
4298 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4299 o_addchr(&dest, ch);
4300 nommu_addchr(&ctx.as_string, ch);
4301 /* Example: echo Hello \2>file
4302 * we need to know that word 2 is quoted */
4303 dest.has_quoted_part = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004304 break;
4305 case '$':
Denys Vlasenko101a4e32010-09-09 14:04:57 +02004306 if (parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004307 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004308 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004309 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004310 }
Eric Andersen25f27032001-04-26 23:22:31 +00004311 break;
4312 case '\'':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004313 dest.has_quoted_part = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004314 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004315 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004316 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004317 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004318 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004319 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004320 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004321 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004322 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004323 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004324 }
Eric Andersen25f27032001-04-26 23:22:31 +00004325 break;
4326 case '"':
Denys Vlasenko38292b62010-09-05 14:49:40 +02004327 dest.has_quoted_part = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004328 if (dest.o_assignment == NOT_ASSIGNMENT)
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004329 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004330 if (encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004331 goto parse_error;
Denys Vlasenko5b6210c2010-09-09 13:32:21 +02004332 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
Eric Andersen25f27032001-04-26 23:22:31 +00004333 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004334#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004335 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004336 unsigned pos;
4337
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004338 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4339 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004340 pos = dest.length;
Denys Vlasenkoacd5bc82010-09-12 15:05:39 +02004341 add_till_backquote(&dest, input, /*in_dquote:*/ 0);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004342# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004343 o_addstr(&ctx.as_string, dest.data + pos);
4344 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004345# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004346 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4347 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004348 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004349 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004350#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004351 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004352#if ENABLE_HUSH_CASE
4353 case_semi:
4354#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004355 if (done_word(&dest, &ctx)) {
4356 goto parse_error;
4357 }
4358 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004359#if ENABLE_HUSH_CASE
4360 /* Eat multiple semicolons, detect
4361 * whether it means something special */
4362 while (1) {
4363 ch = i_peek(input);
4364 if (ch != ';')
4365 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004366 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004367 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004368 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004369 ctx.ctx_dsemicolon = 1;
4370 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004371 break;
4372 }
4373 }
4374#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004375 new_cmd:
4376 /* We just finished a cmd. New one may start
4377 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004378 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004379 break;
4380 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004381 if (done_word(&dest, &ctx)) {
4382 goto parse_error;
4383 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004384 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004385 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004386 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004387 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004388 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004389 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004390 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004391 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004392 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004393 if (done_word(&dest, &ctx)) {
4394 goto parse_error;
4395 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004396#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004397 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004398 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004399#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004400 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004401 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004402 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004403 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004404 } else {
4405 /* we could pick up a file descriptor choice here
4406 * with redirect_opt_num(), but bash doesn't do it.
4407 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004408 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004409#if !BB_MMU
4410 o_reset_to_empty_unquoted(&ctx.as_string);
4411#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004412 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004413 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004414 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004415#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004416 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004417 if (ctx.ctx_res_w == RES_MATCH
4418 && ctx.command->argv == NULL /* not (word|(... */
4419 && dest.length == 0 /* not word(... */
Denys Vlasenko38292b62010-09-05 14:49:40 +02004420 && dest.has_quoted_part == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004421 ) {
4422 continue;
4423 }
4424#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004425 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004426 if (parse_group(&dest, &ctx, input, ch) != 0) {
4427 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004428 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004429 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004430 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004431#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004432 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004433 goto case_semi;
4434#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004435 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004436 /* proper use of this character is caught by end_trigger:
4437 * if we see {, we call parse_group(..., end_trigger='}')
4438 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004439 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004440 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004441 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004442 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004443 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004444 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004445 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004446
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004447 parse_error:
4448 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004449 struct parse_context *pctx;
4450 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004451
4452 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02004453 * Sample for finding leaks on syntax error recovery path.
4454 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004455 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004456 * Samples to catch leaks at execution:
4457 * while if (true | {true;}); then echo ok; fi; do break; done
4458 * 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 +00004459 */
4460 pctx = &ctx;
4461 do {
4462 /* Update pipe/command counts,
4463 * otherwise freeing may miss some */
4464 done_pipe(pctx, PIPE_SEQ);
4465 debug_printf_clean("freeing list %p from ctx %p\n",
4466 pctx->list_head, pctx);
4467 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004468 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004469 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004470#if !BB_MMU
4471 o_free_unsafe(&pctx->as_string);
4472#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004473 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004474 if (pctx != &ctx) {
4475 free(pctx);
4476 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004477 IF_HAS_KEYWORDS(pctx = p2;)
4478 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004479 /* Free text, clear all dest fields */
4480 o_free(&dest);
4481 /* If we are not in top-level parse, we return,
4482 * our caller will propagate error.
4483 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004484 if (end_trigger != ';') {
4485#if !BB_MMU
4486 if (pstring)
4487 *pstring = NULL;
4488#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004489 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004490 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004491 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004492 /* Discard cached input, force prompt */
4493 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004494 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004495 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004496 }
Eric Andersen25f27032001-04-26 23:22:31 +00004497}
4498
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004499
4500/*** Execution routines ***/
4501
4502/* Expansion can recurse, need forward decls: */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004503#if !ENABLE_HUSH_BASH_COMPAT
4504/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4505#define expand_string_to_string(str, do_unbackslash) \
4506 expand_string_to_string(str)
4507#endif
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004508static char *expand_string_to_string(const char *str, int do_unbackslash);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004509#if ENABLE_HUSH_TICK
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004510static int process_command_subs(o_string *dest, const char *s);
Denys Vlasenko26777aa2010-11-22 23:49:10 +01004511#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004512
4513/* expand_strvec_to_strvec() takes a list of strings, expands
4514 * all variable references within and returns a pointer to
4515 * a list of expanded strings, possibly with larger number
4516 * of strings. (Think VAR="a b"; echo $VAR).
4517 * This new list is allocated as a single malloc block.
4518 * NULL-terminated list of char* pointers is at the beginning of it,
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004519 * followed by strings themselves.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004520 * Caller can deallocate entire list by single free(list). */
4521
Denys Vlasenko238081f2010-10-03 14:26:26 +02004522/* A horde of its helpers come first: */
4523
4524static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4525{
4526 while (--len >= 0) {
Denys Vlasenko9e800222010-10-03 14:28:04 +02004527 char c = *str++;
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004528
Denys Vlasenko9e800222010-10-03 14:28:04 +02004529#if ENABLE_HUSH_BRACE_EXPANSION
4530 if (c == '{' || c == '}') {
4531 /* { -> \{, } -> \} */
4532 o_addchr(o, '\\');
Denys Vlasenko957f79f2010-10-03 17:15:50 +02004533 /* And now we want to add { or } and continue:
4534 * o_addchr(o, c);
4535 * continue;
4536 * luckily, just falling throught achieves this.
4537 */
Denys Vlasenko9e800222010-10-03 14:28:04 +02004538 }
4539#endif
4540 o_addchr(o, c);
4541 if (c == '\\') {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004542 /* \z -> \\\z; \<eol> -> \\<eol> */
4543 o_addchr(o, '\\');
4544 if (len) {
4545 len--;
4546 o_addchr(o, '\\');
4547 o_addchr(o, *str++);
4548 }
4549 }
4550 }
4551}
4552
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004553/* Store given string, finalizing the word and starting new one whenever
4554 * we encounter IFS char(s). This is used for expanding variable values.
4555 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
4556static int expand_on_ifs(o_string *output, int n, const char *str)
4557{
4558 while (1) {
4559 int word_len = strcspn(str, G.ifs);
4560 if (word_len) {
Denys Vlasenko238081f2010-10-03 14:26:26 +02004561 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004562 o_addblock(output, str, word_len);
Denys Vlasenko238081f2010-10-03 14:26:26 +02004563 } else {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004564 /* Protect backslashes against globbing up :)
Denys Vlasenkoa769e022010-09-10 10:12:34 +02004565 * Example: "v='\*'; echo b$v" prints "b\*"
4566 * (and does not try to glob on "*")
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004567 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004568 o_addblock_duplicate_backslash(output, str, word_len);
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004569 /*/ Why can't we do it easier? */
4570 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4571 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4572 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004573 str += word_len;
4574 }
4575 if (!*str) /* EOL - do not finalize word */
4576 break;
4577 o_addchr(output, '\0');
4578 debug_print_list("expand_on_ifs", output, n);
4579 n = o_save_ptr(output, n);
4580 str += strspn(str, G.ifs); /* skip ifs chars */
4581 }
4582 debug_print_list("expand_on_ifs[1]", output, n);
4583 return n;
4584}
4585
4586/* Helper to expand $((...)) and heredoc body. These act as if
4587 * they are in double quotes, with the exception that they are not :).
4588 * Just the rules are similar: "expand only $var and `cmd`"
4589 *
4590 * Returns malloced string.
4591 * As an optimization, we return NULL if expansion is not needed.
4592 */
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004593#if !ENABLE_HUSH_BASH_COMPAT
4594/* only ${var/pattern/repl} (its pattern part) needs additional mode */
4595#define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4596 encode_then_expand_string(str)
4597#endif
4598static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004599{
4600 char *exp_str;
4601 struct in_str input;
4602 o_string dest = NULL_O_STRING;
4603
4604 if (!strchr(str, '$')
Denys Vlasenko77b32cc2010-09-06 11:27:32 +02004605 && !strchr(str, '\\')
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004606#if ENABLE_HUSH_TICK
4607 && !strchr(str, '`')
4608#endif
4609 ) {
4610 return NULL;
4611 }
4612
4613 /* We need to expand. Example:
4614 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4615 */
4616 setup_string_in_str(&input, str);
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004617 encode_string(NULL, &dest, &input, EOF, process_bkslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004618 //bb_error_msg("'%s' -> '%s'", str, dest.data);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02004619 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004620 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4621 o_free_unsafe(&dest);
4622 return exp_str;
4623}
4624
4625#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko063847d2010-09-15 13:33:02 +02004626static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004627{
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004628 arith_state_t math_state;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004629 arith_t res;
4630 char *exp_str;
4631
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004632 math_state.lookupvar = get_local_var_value;
4633 math_state.setvar = set_local_var_from_halves;
4634 //math_state.endofname = endofname;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004635 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenko06d44d72010-09-13 12:49:03 +02004636 res = arith(&math_state, exp_str ? exp_str : arg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004637 free(exp_str);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004638 if (errmsg_p)
4639 *errmsg_p = math_state.errmsg;
4640 if (math_state.errmsg)
4641 die_if_script(math_state.errmsg);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004642 return res;
4643}
4644#endif
4645
4646#if ENABLE_HUSH_BASH_COMPAT
4647/* ${var/[/]pattern[/repl]} helpers */
4648static char *strstr_pattern(char *val, const char *pattern, int *size)
4649{
4650 while (1) {
4651 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4652 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4653 if (end) {
4654 *size = end - val;
4655 return val;
4656 }
4657 if (*val == '\0')
4658 return NULL;
4659 /* Optimization: if "*pat" did not match the start of "string",
4660 * we know that "tring", "ring" etc will not match too:
4661 */
4662 if (pattern[0] == '*')
4663 return NULL;
4664 val++;
4665 }
4666}
4667static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4668{
4669 char *result = NULL;
4670 unsigned res_len = 0;
4671 unsigned repl_len = strlen(repl);
4672
4673 while (1) {
4674 int size;
4675 char *s = strstr_pattern(val, pattern, &size);
4676 if (!s)
4677 break;
4678
4679 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4680 memcpy(result + res_len, val, s - val);
4681 res_len += s - val;
4682 strcpy(result + res_len, repl);
4683 res_len += repl_len;
4684 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4685
4686 val = s + size;
4687 if (exp_op == '/')
4688 break;
4689 }
4690 if (val[0] && result) {
4691 result = xrealloc(result, res_len + strlen(val) + 1);
4692 strcpy(result + res_len, val);
4693 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4694 }
4695 debug_printf_varexp("result:'%s'\n", result);
4696 return result;
4697}
4698#endif
4699
4700/* Helper:
4701 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4702 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004703static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004704{
4705 const char *val = NULL;
4706 char *to_be_freed = NULL;
4707 char *p = *pp;
4708 char *var;
4709 char first_char;
4710 char exp_op;
4711 char exp_save = exp_save; /* for compiler */
4712 char *exp_saveptr; /* points to expansion operator */
4713 char *exp_word = exp_word; /* for compiler */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004714 char arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004715
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004716 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004717 var = arg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004718 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004719 arg0 = arg[0];
4720 first_char = arg[0] = arg0 & 0x7f;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004721 exp_op = 0;
4722
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004723 if (first_char == '#' /* ${#... */
4724 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4725 ) {
4726 /* It must be length operator: ${#var} */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004727 var++;
4728 exp_op = 'L';
4729 } else {
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004730 /* Maybe handle parameter expansion */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004731 if (exp_saveptr /* if 2nd char is one of expansion operators */
4732 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4733 ) {
4734 /* ${?:0}, ${#[:]%0} etc */
4735 exp_saveptr = var + 1;
4736 } else {
4737 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4738 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4739 }
4740 exp_op = exp_save = *exp_saveptr;
4741 if (exp_op) {
4742 exp_word = exp_saveptr + 1;
4743 if (exp_op == ':') {
4744 exp_op = *exp_word++;
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004745//TODO: try ${var:} and ${var:bogus} in non-bash config
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004746 if (ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004747 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004748 ) {
4749 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4750 exp_op = ':';
4751 exp_word--;
4752 }
4753 }
4754 *exp_saveptr = '\0';
4755 } /* else: it's not an expansion op, but bare ${var} */
4756 }
4757
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004758 /* Look up the variable in question */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004759 if (isdigit(var[0])) {
Denys Vlasenko77a7b552010-09-09 12:40:03 +02004760 /* parse_dollar should have vetted var for us */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004761 int n = xatoi_positive(var);
4762 if (n < G.global_argc)
4763 val = G.global_argv[n];
4764 /* else val remains NULL: $N with too big N */
4765 } else {
4766 switch (var[0]) {
4767 case '$': /* pid */
4768 val = utoa(G.root_pid);
4769 break;
4770 case '!': /* bg pid */
4771 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
4772 break;
4773 case '?': /* exitcode */
4774 val = utoa(G.last_exitcode);
4775 break;
4776 case '#': /* argc */
4777 val = utoa(G.global_argc ? G.global_argc-1 : 0);
4778 break;
4779 default:
4780 val = get_local_var_value(var);
4781 }
4782 }
4783
4784 /* Handle any expansions */
4785 if (exp_op == 'L') {
4786 debug_printf_expand("expand: length(%s)=", val);
4787 val = utoa(val ? strlen(val) : 0);
4788 debug_printf_expand("%s\n", val);
4789 } else if (exp_op) {
4790 if (exp_op == '%' || exp_op == '#') {
4791 /* Standard-mandated substring removal ops:
4792 * ${parameter%word} - remove smallest suffix pattern
4793 * ${parameter%%word} - remove largest suffix pattern
4794 * ${parameter#word} - remove smallest prefix pattern
4795 * ${parameter##word} - remove largest prefix pattern
4796 *
4797 * Word is expanded to produce a glob pattern.
4798 * Then var's value is matched to it and matching part removed.
4799 */
4800 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004801 char *t;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004802 char *exp_exp_word;
4803 char *loc;
4804 unsigned scan_flags = pick_scan(exp_op, *exp_word);
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +02004805 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004806 exp_word++;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004807 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004808 if (exp_exp_word)
4809 exp_word = exp_exp_word;
Denys Vlasenko4f870492010-09-10 11:06:01 +02004810 /* HACK ALERT. We depend here on the fact that
4811 * G.global_argv and results of utoa and get_local_var_value
4812 * are actually in writable memory:
4813 * scan_and_match momentarily stores NULs there. */
4814 t = (char*)val;
4815 loc = scan_and_match(t, exp_word, scan_flags);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004816 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
Denys Vlasenko4f870492010-09-10 11:06:01 +02004817 // exp_op, t, exp_word, loc);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004818 free(exp_exp_word);
4819 if (loc) { /* match was found */
4820 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004821 val = loc; /* take right part */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004822 else /* %[%] */
Denys Vlasenko4f870492010-09-10 11:06:01 +02004823 val = to_be_freed = xstrndup(val, loc - val); /* left */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004824 }
4825 }
4826 }
4827#if ENABLE_HUSH_BASH_COMPAT
4828 else if (exp_op == '/' || exp_op == '\\') {
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004829 /* It's ${var/[/]pattern[/repl]} thing.
4830 * Note that in encoded form it has TWO parts:
4831 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4f870492010-09-10 11:06:01 +02004832 * and if // is used, it is encoded as \:
4833 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004834 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004835 /* Empty variable always gives nothing: */
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004836 // "v=''; echo ${v/*/w}" prints "", not "w"
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004837 if (val && val[0]) {
Denys Vlasenko4f870492010-09-10 11:06:01 +02004838 /* pattern uses non-standard expansion.
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02004839 * repl should be unbackslashed and globbed
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02004840 * by the usual expansion rules:
4841 * >az; >bz;
4842 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
4843 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
4844 * v='a bz'; echo ${v/a*z/a*z} prints "az"
4845 * v='a bz'; echo ${v/a*z/\z} prints "z"
4846 * (note that a*z _pattern_ is never globbed!)
4847 */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004848 char *pattern, *repl, *t;
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004849 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004850 if (!pattern)
4851 pattern = xstrdup(exp_word);
4852 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
4853 *p++ = SPECIAL_VAR_SYMBOL;
4854 exp_word = p;
4855 p = strchr(p, SPECIAL_VAR_SYMBOL);
4856 *p = '\0';
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004857 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004858 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
4859 /* HACK ALERT. We depend here on the fact that
4860 * G.global_argv and results of utoa and get_local_var_value
4861 * are actually in writable memory:
4862 * replace_pattern momentarily stores NULs there. */
4863 t = (char*)val;
4864 to_be_freed = replace_pattern(t,
4865 pattern,
4866 (repl ? repl : exp_word),
4867 exp_op);
4868 if (to_be_freed) /* at least one replace happened */
4869 val = to_be_freed;
4870 free(pattern);
4871 free(repl);
4872 }
4873 }
4874#endif
4875 else if (exp_op == ':') {
4876#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
4877 /* It's ${var:N[:M]} bashism.
4878 * Note that in encoded form it has TWO parts:
4879 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
4880 */
4881 arith_t beg, len;
Denys Vlasenko063847d2010-09-15 13:33:02 +02004882 const char *errmsg;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004883
Denys Vlasenko063847d2010-09-15 13:33:02 +02004884 beg = expand_and_evaluate_arith(exp_word, &errmsg);
4885 if (errmsg)
4886 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004887 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
4888 *p++ = SPECIAL_VAR_SYMBOL;
4889 exp_word = p;
4890 p = strchr(p, SPECIAL_VAR_SYMBOL);
4891 *p = '\0';
Denys Vlasenko063847d2010-09-15 13:33:02 +02004892 len = expand_and_evaluate_arith(exp_word, &errmsg);
4893 if (errmsg)
4894 goto arith_err;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004895 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
Denys Vlasenko063847d2010-09-15 13:33:02 +02004896 if (len >= 0) { /* bash compat: len < 0 is illegal */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004897 if (beg < 0) /* bash compat */
4898 beg = 0;
4899 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004900 if (len == 0 || !val || beg >= strlen(val)) {
Denys Vlasenko063847d2010-09-15 13:33:02 +02004901 arith_err:
Denys Vlasenkob771c652010-09-13 00:34:26 +02004902 val = NULL;
4903 } else {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004904 /* Paranoia. What if user entered 9999999999999
4905 * which fits in arith_t but not int? */
4906 if (len >= INT_MAX)
4907 len = INT_MAX;
4908 val = to_be_freed = xstrndup(val + beg, len);
4909 }
4910 debug_printf_varexp("val:'%s'\n", val);
4911 } else
4912#endif
4913 {
4914 die_if_script("malformed ${%s:...}", var);
Denys Vlasenkob771c652010-09-13 00:34:26 +02004915 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004916 }
4917 } else { /* one of "-=+?" */
4918 /* Standard-mandated substitution ops:
4919 * ${var?word} - indicate error if unset
4920 * If var is unset, word (or a message indicating it is unset
4921 * if word is null) is written to standard error
4922 * and the shell exits with a non-zero exit status.
4923 * Otherwise, the value of var is substituted.
4924 * ${var-word} - use default value
4925 * If var is unset, word is substituted.
4926 * ${var=word} - assign and use default value
4927 * If var is unset, word is assigned to var.
4928 * In all cases, final value of var is substituted.
4929 * ${var+word} - use alternative value
4930 * If var is unset, null is substituted.
4931 * Otherwise, word is substituted.
4932 *
4933 * Word is subjected to tilde expansion, parameter expansion,
4934 * command substitution, and arithmetic expansion.
4935 * If word is not needed, it is not expanded.
4936 *
4937 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
4938 * but also treat null var as if it is unset.
4939 */
4940 int use_word = (!val || ((exp_save == ':') && !val[0]));
4941 if (exp_op == '+')
4942 use_word = !use_word;
4943 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
4944 (exp_save == ':') ? "true" : "false", use_word);
4945 if (use_word) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02004946 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004947 if (to_be_freed)
4948 exp_word = to_be_freed;
4949 if (exp_op == '?') {
4950 /* mimic bash message */
4951 die_if_script("%s: %s",
4952 var,
4953 exp_word[0] ? exp_word : "parameter null or not set"
4954 );
4955//TODO: how interactive bash aborts expansion mid-command?
4956 } else {
4957 val = exp_word;
4958 }
4959
4960 if (exp_op == '=') {
4961 /* ${var=[word]} or ${var:=[word]} */
4962 if (isdigit(var[0]) || var[0] == '#') {
4963 /* mimic bash message */
4964 die_if_script("$%s: cannot assign in this way", var);
4965 val = NULL;
4966 } else {
4967 char *new_var = xasprintf("%s=%s", var, val);
4968 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4969 }
4970 }
4971 }
4972 } /* one of "-=+?" */
4973
4974 *exp_saveptr = exp_save;
4975 } /* if (exp_op) */
4976
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004977 arg[0] = arg0;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004978
4979 *pp = p;
4980 *to_be_freed_pp = to_be_freed;
4981 return val;
4982}
4983
4984/* Expand all variable references in given string, adding words to list[]
4985 * at n, n+1,... positions. Return updated n (so that list[n] is next one
4986 * to be filled). This routine is extremely tricky: has to deal with
4987 * variables/parameters with whitespace, $* and $@, and constructs like
4988 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004989static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004990{
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004991 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004992 * expansion of right-hand side of assignment == 1-element expand.
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004993 */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02004994 char cant_be_null = 0; /* only bit 0x80 matters */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004995 char *p;
4996
Denys Vlasenko95d48f22010-09-08 13:58:55 +02004997 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
4998 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02004999 debug_print_list("expand_vars_to_list", output, n);
5000 n = o_save_ptr(output, n);
5001 debug_print_list("expand_vars_to_list[0]", output, n);
5002
5003 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5004 char first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005005 char *to_be_freed = NULL;
5006 const char *val = NULL;
5007#if ENABLE_HUSH_TICK
5008 o_string subst_result = NULL_O_STRING;
5009#endif
5010#if ENABLE_SH_MATH_SUPPORT
5011 char arith_buf[sizeof(arith_t)*3 + 2];
5012#endif
5013 o_addblock(output, arg, p - arg);
5014 debug_print_list("expand_vars_to_list[1]", output, n);
5015 arg = ++p;
5016 p = strchr(p, SPECIAL_VAR_SYMBOL);
5017
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005018 /* Fetch special var name (if it is indeed one of them)
5019 * and quote bit, force the bit on if singleword expansion -
5020 * important for not getting v=$@ expand to many words. */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005021 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005022
5023 /* Is this variable quoted and thus expansion can't be null?
5024 * "$@" is special. Even if quoted, it can still
5025 * expand to nothing (not even an empty string),
5026 * thus it is excluded. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005027 if ((first_ch & 0x7f) != '@')
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005028 cant_be_null |= first_ch;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005029
5030 switch (first_ch & 0x7f) {
5031 /* Highest bit in first_ch indicates that var is double-quoted */
5032 case '*':
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005033 case '@': {
5034 int i;
5035 if (!G.global_argv[1])
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005036 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005037 i = 1;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005038 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005039 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005040 while (G.global_argv[i]) {
5041 n = expand_on_ifs(output, n, G.global_argv[i]);
5042 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5043 if (G.global_argv[i++][0] && G.global_argv[i]) {
5044 /* this argv[] is not empty and not last:
5045 * put terminating NUL, start new word */
5046 o_addchr(output, '\0');
5047 debug_print_list("expand_vars_to_list[2]", output, n);
5048 n = o_save_ptr(output, n);
5049 debug_print_list("expand_vars_to_list[3]", output, n);
5050 }
5051 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005052 } else
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005053 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005054 * and in this case should treat it like '$*' - see 'else...' below */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005055 if (first_ch == ('@'|0x80) /* quoted $@ */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005056 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005057 ) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005058 while (1) {
5059 o_addQstr(output, G.global_argv[i]);
5060 if (++i >= G.global_argc)
5061 break;
5062 o_addchr(output, '\0');
5063 debug_print_list("expand_vars_to_list[4]", output, n);
5064 n = o_save_ptr(output, n);
5065 }
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005066 } else { /* quoted $* (or v="$@" case): add as one word */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005067 while (1) {
5068 o_addQstr(output, G.global_argv[i]);
5069 if (!G.global_argv[++i])
5070 break;
5071 if (G.ifs[0])
5072 o_addchr(output, G.ifs[0]);
5073 }
5074 }
5075 break;
Denys Vlasenkoc49d2d92010-09-06 10:26:37 +02005076 }
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005077 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5078 /* "Empty variable", used to make "" etc to not disappear */
5079 arg++;
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005080 cant_be_null = 0x80;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005081 break;
5082#if ENABLE_HUSH_TICK
5083 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005084 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005085 arg++;
5086 /* Can't just stuff it into output o_string,
5087 * expanded result may need to be globbed
5088 * and $IFS-splitted */
5089 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5090 G.last_exitcode = process_command_subs(&subst_result, arg);
5091 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5092 val = subst_result.data;
5093 goto store_val;
5094#endif
5095#if ENABLE_SH_MATH_SUPPORT
5096 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5097 arith_t res;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005098
5099 arg++; /* skip '+' */
5100 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5101 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko063847d2010-09-15 13:33:02 +02005102 res = expand_and_evaluate_arith(arg, NULL);
Denys Vlasenkobed7c812010-09-16 11:50:46 +02005103 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5104 sprintf(arith_buf, ARITH_FMT, res);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005105 val = arith_buf;
5106 break;
5107 }
5108#endif
5109 default:
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005110 val = expand_one_var(&to_be_freed, arg, &p);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005111 IF_HUSH_TICK(store_val:)
5112 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005113 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5114 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005115 if (val && val[0]) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005116 n = expand_on_ifs(output, n, val);
5117 val = NULL;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005118 }
5119 } else { /* quoted $VAR, val will be appended below */
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005120 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5121 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005122 }
5123 break;
5124
5125 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5126
5127 if (val && val[0]) {
5128 o_addQstr(output, val);
5129 }
5130 free(to_be_freed);
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005131
5132 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5133 * Do the check to avoid writing to a const string. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005134 if (*p != SPECIAL_VAR_SYMBOL)
5135 *p = SPECIAL_VAR_SYMBOL;
5136
5137#if ENABLE_HUSH_TICK
5138 o_free(&subst_result);
5139#endif
5140 arg = ++p;
5141 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5142
5143 if (arg[0]) {
5144 debug_print_list("expand_vars_to_list[a]", output, n);
5145 /* this part is literal, and it was already pre-quoted
5146 * if needed (much earlier), do not use o_addQstr here! */
5147 o_addstr_with_NUL(output, arg);
5148 debug_print_list("expand_vars_to_list[b]", output, n);
5149 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
Denys Vlasenkobfc02a72010-09-09 14:38:46 +02005150 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005151 ) {
5152 n--;
5153 /* allow to reuse list[n] later without re-growth */
5154 output->has_empty_slot = 1;
5155 } else {
5156 o_addchr(output, '\0');
5157 }
5158
5159 return n;
5160}
5161
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005162static char **expand_variables(char **argv, unsigned expflags)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005163{
5164 int n;
5165 char **list;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005166 o_string output = NULL_O_STRING;
5167
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005168 output.o_expflags = expflags;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005169
5170 n = 0;
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005171 while (*argv) {
Denys Vlasenko95d48f22010-09-08 13:58:55 +02005172 n = expand_vars_to_list(&output, n, *argv);
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005173 argv++;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005174 }
5175 debug_print_list("expand_variables", &output, n);
5176
5177 /* output.data (malloced in one block) gets returned in "list" */
5178 list = o_finalize_list(&output, n);
5179 debug_print_strings("expand_variables[1]", list);
5180 return list;
5181}
5182
5183static char **expand_strvec_to_strvec(char **argv)
5184{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005185 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005186}
5187
5188#if ENABLE_HUSH_BASH_COMPAT
5189static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5190{
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005191 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005192}
5193#endif
5194
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02005195/* Used for expansion of right hand of assignments,
5196 * $((...)), heredocs, variable espansion parts.
5197 *
5198 * NB: should NOT do globbing!
5199 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5200 */
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005201static char *expand_string_to_string(const char *str, int do_unbackslash)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005202{
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005203#if !ENABLE_HUSH_BASH_COMPAT
5204 const int do_unbackslash = 1;
5205#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005206 char *argv[2], **list;
5207
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005208 debug_printf_expand("string_to_string<='%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005209 /* This is generally an optimization, but it also
5210 * handles "", which otherwise trips over !list[0] check below.
5211 * (is this ever happens that we actually get str="" here?)
5212 */
5213 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5214 //TODO: Can use on strings with \ too, just unbackslash() them?
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005215 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005216 return xstrdup(str);
5217 }
5218
5219 argv[0] = (char*)str;
5220 argv[1] = NULL;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005221 list = expand_variables(argv, do_unbackslash
5222 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5223 : EXP_FLAG_SINGLEWORD
5224 );
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005225 if (HUSH_DEBUG)
5226 if (!list[0] || list[1])
5227 bb_error_msg_and_die("BUG in varexp2");
5228 /* actually, just move string 2*sizeof(char*) bytes back */
5229 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005230 if (do_unbackslash)
5231 unbackslash((char*)list);
5232 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005233 return (char*)list;
5234}
5235
5236/* Used for "eval" builtin */
5237static char* expand_strvec_to_string(char **argv)
5238{
5239 char **list;
5240
Denys Vlasenko5b686cb2010-09-08 13:44:34 +02005241 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005242 /* Convert all NULs to spaces */
5243 if (list[0]) {
5244 int n = 1;
5245 while (list[n]) {
5246 if (HUSH_DEBUG)
5247 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5248 bb_error_msg_and_die("BUG in varexp3");
5249 /* bash uses ' ' regardless of $IFS contents */
5250 list[n][-1] = ' ';
5251 n++;
5252 }
5253 }
5254 overlapping_strcpy((char*)list, list[0]);
5255 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5256 return (char*)list;
5257}
5258
5259static char **expand_assignments(char **argv, int count)
5260{
5261 int i;
5262 char **p;
5263
5264 G.expanded_assignments = p = NULL;
5265 /* Expand assignments into one string each */
5266 for (i = 0; i < count; i++) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005267 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005268 }
5269 G.expanded_assignments = NULL;
5270 return p;
5271}
5272
5273
5274#if BB_MMU
5275/* never called */
5276void re_execute_shell(char ***to_free, const char *s,
5277 char *g_argv0, char **g_argv,
5278 char **builtin_argv) NORETURN;
5279
5280static void reset_traps_to_defaults(void)
5281{
5282 /* This function is always called in a child shell
5283 * after fork (not vfork, NOMMU doesn't use this function).
5284 */
5285 unsigned sig;
5286 unsigned mask;
5287
5288 /* Child shells are not interactive.
5289 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5290 * Testcase: (while :; do :; done) + ^Z should background.
5291 * Same goes for SIGTERM, SIGHUP, SIGINT.
5292 */
5293 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
5294 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
5295
5296 /* Switching off SPECIAL_INTERACTIVE_SIGS.
5297 * Stupid. It can be done with *single* &= op, but we can't use
5298 * the fact that G.blocked_set is implemented as a bitmask
5299 * in libc... */
5300 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
5301 sig = 1;
5302 while (1) {
5303 if (mask & 1) {
5304 /* Careful. Only if no trap or trap is not "" */
5305 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
5306 sigdelset(&G.blocked_set, sig);
5307 }
5308 mask >>= 1;
5309 if (!mask)
5310 break;
5311 sig++;
5312 }
5313 /* Our homegrown sig mask is saner to work with :) */
5314 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5315
5316 /* Resetting all traps to default except empty ones */
5317 mask = G.non_DFL_mask;
5318 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
5319 if (!G.traps[sig] || !G.traps[sig][0])
5320 continue;
5321 free(G.traps[sig]);
5322 G.traps[sig] = NULL;
5323 /* There is no signal for 0 (EXIT) */
5324 if (sig == 0)
5325 continue;
5326 /* There was a trap handler, we just removed it.
5327 * But if sig still has non-DFL handling,
5328 * we should not unblock the sig. */
5329 if (mask & 1)
5330 continue;
5331 sigdelset(&G.blocked_set, sig);
5332 }
5333 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5334}
5335
5336#else /* !BB_MMU */
5337
5338static void re_execute_shell(char ***to_free, const char *s,
5339 char *g_argv0, char **g_argv,
5340 char **builtin_argv) NORETURN;
5341static void re_execute_shell(char ***to_free, const char *s,
5342 char *g_argv0, char **g_argv,
5343 char **builtin_argv)
5344{
5345# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5346 /* delims + 2 * (number of bytes in printed hex numbers) */
5347 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5348 char *heredoc_argv[4];
5349 struct variable *cur;
5350# if ENABLE_HUSH_FUNCTIONS
5351 struct function *funcp;
5352# endif
5353 char **argv, **pp;
5354 unsigned cnt;
5355 unsigned long long empty_trap_mask;
5356
5357 if (!g_argv0) { /* heredoc */
5358 argv = heredoc_argv;
5359 argv[0] = (char *) G.argv0_for_re_execing;
5360 argv[1] = (char *) "-<";
5361 argv[2] = (char *) s;
5362 argv[3] = NULL;
5363 pp = &argv[3]; /* used as pointer to empty environment */
5364 goto do_exec;
5365 }
5366
5367 cnt = 0;
5368 pp = builtin_argv;
5369 if (pp) while (*pp++)
5370 cnt++;
5371
5372 empty_trap_mask = 0;
5373 if (G.traps) {
5374 int sig;
5375 for (sig = 1; sig < NSIG; sig++) {
5376 if (G.traps[sig] && !G.traps[sig][0])
5377 empty_trap_mask |= 1LL << sig;
5378 }
5379 }
5380
5381 sprintf(param_buf, NOMMU_HACK_FMT
5382 , (unsigned) G.root_pid
5383 , (unsigned) G.root_ppid
5384 , (unsigned) G.last_bg_pid
5385 , (unsigned) G.last_exitcode
5386 , cnt
5387 , empty_trap_mask
5388 IF_HUSH_LOOPS(, G.depth_of_loop)
5389 );
5390# undef NOMMU_HACK_FMT
5391 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5392 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5393 */
5394 cnt += 6;
5395 for (cur = G.top_var; cur; cur = cur->next) {
5396 if (!cur->flg_export || cur->flg_read_only)
5397 cnt += 2;
5398 }
5399# if ENABLE_HUSH_FUNCTIONS
5400 for (funcp = G.top_func; funcp; funcp = funcp->next)
5401 cnt += 3;
5402# endif
5403 pp = g_argv;
5404 while (*pp++)
5405 cnt++;
5406 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5407 *pp++ = (char *) G.argv0_for_re_execing;
5408 *pp++ = param_buf;
5409 for (cur = G.top_var; cur; cur = cur->next) {
5410 if (strcmp(cur->varstr, hush_version_str) == 0)
5411 continue;
5412 if (cur->flg_read_only) {
5413 *pp++ = (char *) "-R";
5414 *pp++ = cur->varstr;
5415 } else if (!cur->flg_export) {
5416 *pp++ = (char *) "-V";
5417 *pp++ = cur->varstr;
5418 }
5419 }
5420# if ENABLE_HUSH_FUNCTIONS
5421 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5422 *pp++ = (char *) "-F";
5423 *pp++ = funcp->name;
5424 *pp++ = funcp->body_as_string;
5425 }
5426# endif
5427 /* We can pass activated traps here. Say, -Tnn:trap_string
5428 *
5429 * However, POSIX says that subshells reset signals with traps
5430 * to SIG_DFL.
5431 * I tested bash-3.2 and it not only does that with true subshells
5432 * of the form ( list ), but with any forked children shells.
5433 * I set trap "echo W" WINCH; and then tried:
5434 *
5435 * { echo 1; sleep 20; echo 2; } &
5436 * while true; do echo 1; sleep 20; echo 2; break; done &
5437 * true | { echo 1; sleep 20; echo 2; } | cat
5438 *
5439 * In all these cases sending SIGWINCH to the child shell
5440 * did not run the trap. If I add trap "echo V" WINCH;
5441 * _inside_ group (just before echo 1), it works.
5442 *
5443 * I conclude it means we don't need to pass active traps here.
5444 * Even if we would use signal handlers instead of signal masking
5445 * in order to implement trap handling,
5446 * exec syscall below resets signals to SIG_DFL for us.
5447 */
5448 *pp++ = (char *) "-c";
5449 *pp++ = (char *) s;
5450 if (builtin_argv) {
5451 while (*++builtin_argv)
5452 *pp++ = *builtin_argv;
5453 *pp++ = (char *) "";
5454 }
5455 *pp++ = g_argv0;
5456 while (*g_argv)
5457 *pp++ = *g_argv++;
5458 /* *pp = NULL; - is already there */
5459 pp = environ;
5460
5461 do_exec:
5462 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5463 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
5464 execve(bb_busybox_exec_path, argv, pp);
5465 /* Fallback. Useful for init=/bin/hush usage etc */
5466 if (argv[0][0] == '/')
5467 execve(argv[0], argv, pp);
5468 xfunc_error_retval = 127;
5469 bb_error_msg_and_die("can't re-execute the shell");
5470}
5471#endif /* !BB_MMU */
5472
5473
5474static int run_and_free_list(struct pipe *pi);
5475
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005476/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005477 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5478 * end_trigger controls how often we stop parsing
5479 * NUL: parse all, execute, return
5480 * ';': parse till ';' or newline, execute, repeat till EOF
5481 */
5482static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005483{
Denys Vlasenko00243b02009-11-16 02:00:03 +01005484 /* Why we need empty flag?
5485 * An obscure corner case "false; ``; echo $?":
5486 * empty command in `` should still set $? to 0.
5487 * But we can't just set $? to 0 at the start,
5488 * this breaks "false; echo `echo $?`" case.
5489 */
5490 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005491 while (1) {
5492 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005493
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005494 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005495 if (!pipe_list) { /* EOF */
5496 if (empty)
5497 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005498 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01005499 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005500 debug_print_tree(pipe_list, 0);
5501 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5502 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01005503 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005504 }
Eric Andersen25f27032001-04-26 23:22:31 +00005505}
5506
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005507static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005508{
5509 struct in_str input;
5510 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005511 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005512}
5513
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005514static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005515{
Eric Andersen25f27032001-04-26 23:22:31 +00005516 struct in_str input;
5517 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005518 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005519}
5520
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005521#if ENABLE_HUSH_TICK
5522static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5523{
5524 pid_t pid;
5525 int channel[2];
5526# if !BB_MMU
5527 char **to_free = NULL;
5528# endif
5529
5530 xpipe(channel);
5531 pid = BB_MMU ? xfork() : xvfork();
5532 if (pid == 0) { /* child */
5533 disable_restore_tty_pgrp_on_exit();
5534 /* Process substitution is not considered to be usual
5535 * 'command execution'.
5536 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5537 */
5538 bb_signals(0
5539 + (1 << SIGTSTP)
5540 + (1 << SIGTTIN)
5541 + (1 << SIGTTOU)
5542 , SIG_IGN);
5543 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5544 close(channel[0]); /* NB: close _first_, then move fd! */
5545 xmove_fd(channel[1], 1);
5546 /* Prevent it from trying to handle ctrl-z etc */
5547 IF_HUSH_JOB(G.run_list_level = 1;)
5548 /* Awful hack for `trap` or $(trap).
5549 *
5550 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5551 * contains an example where "trap" is executed in a subshell:
5552 *
5553 * save_traps=$(trap)
5554 * ...
5555 * eval "$save_traps"
5556 *
5557 * Standard does not say that "trap" in subshell shall print
5558 * parent shell's traps. It only says that its output
5559 * must have suitable form, but then, in the above example
5560 * (which is not supposed to be normative), it implies that.
5561 *
5562 * bash (and probably other shell) does implement it
5563 * (traps are reset to defaults, but "trap" still shows them),
5564 * but as a result, "trap" logic is hopelessly messed up:
5565 *
5566 * # trap
5567 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5568 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5569 * # true | trap <--- trap is in subshell - no output (ditto)
5570 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5571 * trap -- 'echo Ho' SIGWINCH
5572 * # echo `(trap)` <--- in subshell in subshell - output
5573 * trap -- 'echo Ho' SIGWINCH
5574 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5575 * trap -- 'echo Ho' SIGWINCH
5576 *
5577 * The rules when to forget and when to not forget traps
5578 * get really complex and nonsensical.
5579 *
5580 * Our solution: ONLY bare $(trap) or `trap` is special.
5581 */
5582 s = skip_whitespace(s);
5583 if (strncmp(s, "trap", 4) == 0
5584 && skip_whitespace(s + 4)[0] == '\0'
5585 ) {
5586 static const char *const argv[] = { NULL, NULL };
5587 builtin_trap((char**)argv);
5588 exit(0); /* not _exit() - we need to fflush */
5589 }
5590# if BB_MMU
5591 reset_traps_to_defaults();
5592 parse_and_run_string(s);
5593 _exit(G.last_exitcode);
5594# else
5595 /* We re-execute after vfork on NOMMU. This makes this script safe:
5596 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5597 * huge=`cat BIG` # was blocking here forever
5598 * echo OK
5599 */
5600 re_execute_shell(&to_free,
5601 s,
5602 G.global_argv[0],
5603 G.global_argv + 1,
5604 NULL);
5605# endif
5606 }
5607
5608 /* parent */
5609 *pid_p = pid;
5610# if ENABLE_HUSH_FAST
5611 G.count_SIGCHLD++;
5612//bb_error_msg("[%d] fork in generate_stream_from_string:"
5613// " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5614// getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5615# endif
5616 enable_restore_tty_pgrp_on_exit();
5617# if !BB_MMU
5618 free(to_free);
5619# endif
5620 close(channel[1]);
5621 close_on_exec_on(channel[0]);
5622 return xfdopen_for_read(channel[0]);
5623}
5624
5625/* Return code is exit status of the process that is run. */
5626static int process_command_subs(o_string *dest, const char *s)
5627{
5628 FILE *fp;
5629 struct in_str pipe_str;
5630 pid_t pid;
5631 int status, ch, eol_cnt;
5632
5633 fp = generate_stream_from_string(s, &pid);
5634
5635 /* Now send results of command back into original context */
5636 setup_file_in_str(&pipe_str, fp);
5637 eol_cnt = 0;
5638 while ((ch = i_getch(&pipe_str)) != EOF) {
5639 if (ch == '\n') {
5640 eol_cnt++;
5641 continue;
5642 }
5643 while (eol_cnt) {
5644 o_addchr(dest, '\n');
5645 eol_cnt--;
5646 }
5647 o_addQchr(dest, ch);
5648 }
5649
5650 debug_printf("done reading from `cmd` pipe, closing it\n");
5651 fclose(fp);
5652 /* We need to extract exitcode. Test case
5653 * "true; echo `sleep 1; false` $?"
5654 * should print 1 */
5655 safe_waitpid(pid, &status, 0);
5656 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5657 return WEXITSTATUS(status);
5658}
5659#endif /* ENABLE_HUSH_TICK */
5660
5661
5662static void setup_heredoc(struct redir_struct *redir)
5663{
5664 struct fd_pair pair;
5665 pid_t pid;
5666 int len, written;
5667 /* the _body_ of heredoc (misleading field name) */
5668 const char *heredoc = redir->rd_filename;
5669 char *expanded;
5670#if !BB_MMU
5671 char **to_free;
5672#endif
5673
5674 expanded = NULL;
5675 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
Denys Vlasenkod98e5c62010-09-10 10:44:23 +02005676 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005677 if (expanded)
5678 heredoc = expanded;
5679 }
5680 len = strlen(heredoc);
5681
5682 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5683 xpiped_pair(pair);
5684 xmove_fd(pair.rd, redir->rd_fd);
5685
5686 /* Try writing without forking. Newer kernels have
5687 * dynamically growing pipes. Must use non-blocking write! */
5688 ndelay_on(pair.wr);
5689 while (1) {
5690 written = write(pair.wr, heredoc, len);
5691 if (written <= 0)
5692 break;
5693 len -= written;
5694 if (len == 0) {
5695 close(pair.wr);
5696 free(expanded);
5697 return;
5698 }
5699 heredoc += written;
5700 }
5701 ndelay_off(pair.wr);
5702
5703 /* Okay, pipe buffer was not big enough */
5704 /* Note: we must not create a stray child (bastard? :)
5705 * for the unsuspecting parent process. Child creates a grandchild
5706 * and exits before parent execs the process which consumes heredoc
5707 * (that exec happens after we return from this function) */
5708#if !BB_MMU
5709 to_free = NULL;
5710#endif
5711 pid = xvfork();
5712 if (pid == 0) {
5713 /* child */
5714 disable_restore_tty_pgrp_on_exit();
5715 pid = BB_MMU ? xfork() : xvfork();
5716 if (pid != 0)
5717 _exit(0);
5718 /* grandchild */
5719 close(redir->rd_fd); /* read side of the pipe */
5720#if BB_MMU
5721 full_write(pair.wr, heredoc, len); /* may loop or block */
5722 _exit(0);
5723#else
5724 /* Delegate blocking writes to another process */
5725 xmove_fd(pair.wr, STDOUT_FILENO);
5726 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
5727#endif
5728 }
5729 /* parent */
5730#if ENABLE_HUSH_FAST
5731 G.count_SIGCHLD++;
5732//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5733#endif
5734 enable_restore_tty_pgrp_on_exit();
5735#if !BB_MMU
5736 free(to_free);
5737#endif
5738 close(pair.wr);
5739 free(expanded);
5740 wait(NULL); /* wait till child has died */
5741}
5742
5743/* squirrel != NULL means we squirrel away copies of stdin, stdout,
5744 * and stderr if they are redirected. */
5745static int setup_redirects(struct command *prog, int squirrel[])
5746{
5747 int openfd, mode;
5748 struct redir_struct *redir;
5749
5750 for (redir = prog->redirects; redir; redir = redir->next) {
5751 if (redir->rd_type == REDIRECT_HEREDOC2) {
5752 /* rd_fd<<HERE case */
5753 if (squirrel && redir->rd_fd < 3
5754 && squirrel[redir->rd_fd] < 0
5755 ) {
5756 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5757 }
5758 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
5759 * of the heredoc */
5760 debug_printf_parse("set heredoc '%s'\n",
5761 redir->rd_filename);
5762 setup_heredoc(redir);
5763 continue;
5764 }
5765
5766 if (redir->rd_dup == REDIRFD_TO_FILE) {
5767 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
5768 char *p;
5769 if (redir->rd_filename == NULL) {
5770 /* Something went wrong in the parse.
5771 * Pretend it didn't happen */
5772 bb_error_msg("bug in redirect parse");
5773 continue;
5774 }
5775 mode = redir_table[redir->rd_type].mode;
Denys Vlasenkoebee4102010-09-10 10:17:53 +02005776 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005777 openfd = open_or_warn(p, mode);
5778 free(p);
5779 if (openfd < 0) {
5780 /* this could get lost if stderr has been redirected, but
5781 * bash and ash both lose it as well (though zsh doesn't!) */
5782//what the above comment tries to say?
5783 return 1;
5784 }
5785 } else {
5786 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
5787 openfd = redir->rd_dup;
5788 }
5789
5790 if (openfd != redir->rd_fd) {
5791 if (squirrel && redir->rd_fd < 3
5792 && squirrel[redir->rd_fd] < 0
5793 ) {
5794 squirrel[redir->rd_fd] = dup(redir->rd_fd);
5795 }
5796 if (openfd == REDIRFD_CLOSE) {
5797 /* "n>-" means "close me" */
5798 close(redir->rd_fd);
5799 } else {
5800 xdup2(openfd, redir->rd_fd);
5801 if (redir->rd_dup == REDIRFD_TO_FILE)
5802 close(openfd);
5803 }
5804 }
5805 }
5806 return 0;
5807}
5808
5809static void restore_redirects(int squirrel[])
5810{
5811 int i, fd;
5812 for (i = 0; i < 3; i++) {
5813 fd = squirrel[i];
5814 if (fd != -1) {
5815 /* We simply die on error */
5816 xmove_fd(fd, i);
5817 }
5818 }
5819}
5820
5821static char *find_in_path(const char *arg)
5822{
5823 char *ret = NULL;
5824 const char *PATH = get_local_var_value("PATH");
5825
5826 if (!PATH)
5827 return NULL;
5828
5829 while (1) {
5830 const char *end = strchrnul(PATH, ':');
5831 int sz = end - PATH; /* must be int! */
5832
5833 free(ret);
5834 if (sz != 0) {
5835 ret = xasprintf("%.*s/%s", sz, PATH, arg);
5836 } else {
5837 /* We have xxx::yyyy in $PATH,
5838 * it means "use current dir" */
5839 ret = xstrdup(arg);
5840 }
5841 if (access(ret, F_OK) == 0)
5842 break;
5843
5844 if (*end == '\0') {
5845 free(ret);
5846 return NULL;
5847 }
5848 PATH = end + 1;
5849 }
5850
5851 return ret;
5852}
5853
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005854static const struct built_in_command *find_builtin_helper(const char *name,
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005855 const struct built_in_command *x,
5856 const struct built_in_command *end)
5857{
5858 while (x != end) {
5859 if (strcmp(name, x->b_cmd) != 0) {
5860 x++;
5861 continue;
5862 }
5863 debug_printf_exec("found builtin '%s'\n", name);
5864 return x;
5865 }
5866 return NULL;
5867}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005868static const struct built_in_command *find_builtin1(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005869{
5870 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
5871}
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02005872static const struct built_in_command *find_builtin(const char *name)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02005873{
5874 const struct built_in_command *x = find_builtin1(name);
5875 if (x)
5876 return x;
5877 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
5878}
5879
5880#if ENABLE_HUSH_FUNCTIONS
5881static struct function **find_function_slot(const char *name)
5882{
5883 struct function **funcpp = &G.top_func;
5884 while (*funcpp) {
5885 if (strcmp(name, (*funcpp)->name) == 0) {
5886 break;
5887 }
5888 funcpp = &(*funcpp)->next;
5889 }
5890 return funcpp;
5891}
5892
5893static const struct function *find_function(const char *name)
5894{
5895 const struct function *funcp = *find_function_slot(name);
5896 if (funcp)
5897 debug_printf_exec("found function '%s'\n", name);
5898 return funcp;
5899}
5900
5901/* Note: takes ownership on name ptr */
5902static struct function *new_function(char *name)
5903{
5904 struct function **funcpp = find_function_slot(name);
5905 struct function *funcp = *funcpp;
5906
5907 if (funcp != NULL) {
5908 struct command *cmd = funcp->parent_cmd;
5909 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
5910 if (!cmd) {
5911 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
5912 free(funcp->name);
5913 /* Note: if !funcp->body, do not free body_as_string!
5914 * This is a special case of "-F name body" function:
5915 * body_as_string was not malloced! */
5916 if (funcp->body) {
5917 free_pipe_list(funcp->body);
5918# if !BB_MMU
5919 free(funcp->body_as_string);
5920# endif
5921 }
5922 } else {
5923 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
5924 cmd->argv[0] = funcp->name;
5925 cmd->group = funcp->body;
5926# if !BB_MMU
5927 cmd->group_as_string = funcp->body_as_string;
5928# endif
5929 }
5930 } else {
5931 debug_printf_exec("remembering new function '%s'\n", name);
5932 funcp = *funcpp = xzalloc(sizeof(*funcp));
5933 /*funcp->next = NULL;*/
5934 }
5935
5936 funcp->name = name;
5937 return funcp;
5938}
5939
5940static void unset_func(const char *name)
5941{
5942 struct function **funcpp = find_function_slot(name);
5943 struct function *funcp = *funcpp;
5944
5945 if (funcp != NULL) {
5946 debug_printf_exec("freeing function '%s'\n", funcp->name);
5947 *funcpp = funcp->next;
5948 /* funcp is unlinked now, deleting it.
5949 * Note: if !funcp->body, the function was created by
5950 * "-F name body", do not free ->body_as_string
5951 * and ->name as they were not malloced. */
5952 if (funcp->body) {
5953 free_pipe_list(funcp->body);
5954 free(funcp->name);
5955# if !BB_MMU
5956 free(funcp->body_as_string);
5957# endif
5958 }
5959 free(funcp);
5960 }
5961}
5962
5963# if BB_MMU
5964#define exec_function(to_free, funcp, argv) \
5965 exec_function(funcp, argv)
5966# endif
5967static void exec_function(char ***to_free,
5968 const struct function *funcp,
5969 char **argv) NORETURN;
5970static void exec_function(char ***to_free,
5971 const struct function *funcp,
5972 char **argv)
5973{
5974# if BB_MMU
5975 int n = 1;
5976
5977 argv[0] = G.global_argv[0];
5978 G.global_argv = argv;
5979 while (*++argv)
5980 n++;
5981 G.global_argc = n;
5982 /* On MMU, funcp->body is always non-NULL */
5983 n = run_list(funcp->body);
5984 fflush_all();
5985 _exit(n);
5986# else
5987 re_execute_shell(to_free,
5988 funcp->body_as_string,
5989 G.global_argv[0],
5990 argv + 1,
5991 NULL);
5992# endif
5993}
5994
5995static int run_function(const struct function *funcp, char **argv)
5996{
5997 int rc;
5998 save_arg_t sv;
5999 smallint sv_flg;
6000
6001 save_and_replace_G_args(&sv, argv);
6002
6003 /* "we are in function, ok to use return" */
6004 sv_flg = G.flag_return_in_progress;
6005 G.flag_return_in_progress = -1;
6006# if ENABLE_HUSH_LOCAL
6007 G.func_nest_level++;
6008# endif
6009
6010 /* On MMU, funcp->body is always non-NULL */
6011# if !BB_MMU
6012 if (!funcp->body) {
6013 /* Function defined by -F */
6014 parse_and_run_string(funcp->body_as_string);
6015 rc = G.last_exitcode;
6016 } else
6017# endif
6018 {
6019 rc = run_list(funcp->body);
6020 }
6021
6022# if ENABLE_HUSH_LOCAL
6023 {
6024 struct variable *var;
6025 struct variable **var_pp;
6026
6027 var_pp = &G.top_var;
6028 while ((var = *var_pp) != NULL) {
6029 if (var->func_nest_level < G.func_nest_level) {
6030 var_pp = &var->next;
6031 continue;
6032 }
6033 /* Unexport */
6034 if (var->flg_export)
6035 bb_unsetenv(var->varstr);
6036 /* Remove from global list */
6037 *var_pp = var->next;
6038 /* Free */
6039 if (!var->max_len)
6040 free(var->varstr);
6041 free(var);
6042 }
6043 G.func_nest_level--;
6044 }
6045# endif
6046 G.flag_return_in_progress = sv_flg;
6047
6048 restore_G_args(&sv, argv);
6049
6050 return rc;
6051}
6052#endif /* ENABLE_HUSH_FUNCTIONS */
6053
6054
6055#if BB_MMU
6056#define exec_builtin(to_free, x, argv) \
6057 exec_builtin(x, argv)
6058#else
6059#define exec_builtin(to_free, x, argv) \
6060 exec_builtin(to_free, argv)
6061#endif
6062static void exec_builtin(char ***to_free,
6063 const struct built_in_command *x,
6064 char **argv) NORETURN;
6065static void exec_builtin(char ***to_free,
6066 const struct built_in_command *x,
6067 char **argv)
6068{
6069#if BB_MMU
6070 int rcode = x->b_function(argv);
6071 fflush_all();
6072 _exit(rcode);
6073#else
6074 /* On NOMMU, we must never block!
6075 * Example: { sleep 99 | read line; } & echo Ok
6076 */
6077 re_execute_shell(to_free,
6078 argv[0],
6079 G.global_argv[0],
6080 G.global_argv + 1,
6081 argv);
6082#endif
6083}
6084
6085
6086static void execvp_or_die(char **argv) NORETURN;
6087static void execvp_or_die(char **argv)
6088{
6089 debug_printf_exec("execing '%s'\n", argv[0]);
6090 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6091 execvp(argv[0], argv);
6092 bb_perror_msg("can't execute '%s'", argv[0]);
6093 _exit(127); /* bash compat */
6094}
6095
6096#if ENABLE_HUSH_MODE_X
6097static void dump_cmd_in_x_mode(char **argv)
6098{
6099 if (G_x_mode && argv) {
6100 /* We want to output the line in one write op */
6101 char *buf, *p;
6102 int len;
6103 int n;
6104
6105 len = 3;
6106 n = 0;
6107 while (argv[n])
6108 len += strlen(argv[n++]) + 1;
6109 buf = xmalloc(len);
6110 buf[0] = '+';
6111 p = buf + 1;
6112 n = 0;
6113 while (argv[n])
6114 p += sprintf(p, " %s", argv[n++]);
6115 *p++ = '\n';
6116 *p = '\0';
6117 fputs(buf, stderr);
6118 free(buf);
6119 }
6120}
6121#else
6122# define dump_cmd_in_x_mode(argv) ((void)0)
6123#endif
6124
6125#if BB_MMU
6126#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6127 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6128#define pseudo_exec(nommu_save, command, argv_expanded) \
6129 pseudo_exec(command, argv_expanded)
6130#endif
6131
6132/* Called after [v]fork() in run_pipe, or from builtin_exec.
6133 * Never returns.
6134 * Don't exit() here. If you don't exec, use _exit instead.
6135 * The at_exit handlers apparently confuse the calling process,
6136 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6137static void pseudo_exec_argv(nommu_save_t *nommu_save,
6138 char **argv, int assignment_cnt,
6139 char **argv_expanded) NORETURN;
6140static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6141 char **argv, int assignment_cnt,
6142 char **argv_expanded)
6143{
6144 char **new_env;
6145
6146 new_env = expand_assignments(argv, assignment_cnt);
6147 dump_cmd_in_x_mode(new_env);
6148
6149 if (!argv[assignment_cnt]) {
6150 /* Case when we are here: ... | var=val | ...
6151 * (note that we do not exit early, i.e., do not optimize out
6152 * expand_assignments(): think about ... | var=`sleep 1` | ...
6153 */
6154 free_strings(new_env);
6155 _exit(EXIT_SUCCESS);
6156 }
6157
6158#if BB_MMU
6159 set_vars_and_save_old(new_env);
6160 free(new_env); /* optional */
6161 /* we can also destroy set_vars_and_save_old's return value,
6162 * to save memory */
6163#else
6164 nommu_save->new_env = new_env;
6165 nommu_save->old_vars = set_vars_and_save_old(new_env);
6166#endif
6167
6168 if (argv_expanded) {
6169 argv = argv_expanded;
6170 } else {
6171 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6172#if !BB_MMU
6173 nommu_save->argv = argv;
6174#endif
6175 }
6176 dump_cmd_in_x_mode(argv);
6177
6178#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6179 if (strchr(argv[0], '/') != NULL)
6180 goto skip;
6181#endif
6182
6183 /* Check if the command matches any of the builtins.
6184 * Depending on context, this might be redundant. But it's
6185 * easier to waste a few CPU cycles than it is to figure out
6186 * if this is one of those cases.
6187 */
6188 {
6189 /* On NOMMU, it is more expensive to re-execute shell
6190 * just in order to run echo or test builtin.
6191 * It's better to skip it here and run corresponding
6192 * non-builtin later. */
6193 const struct built_in_command *x;
6194 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6195 if (x) {
6196 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6197 }
6198 }
6199#if ENABLE_HUSH_FUNCTIONS
6200 /* Check if the command matches any functions */
6201 {
6202 const struct function *funcp = find_function(argv[0]);
6203 if (funcp) {
6204 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6205 }
6206 }
6207#endif
6208
6209#if ENABLE_FEATURE_SH_STANDALONE
6210 /* Check if the command matches any busybox applets */
6211 {
6212 int a = find_applet_by_name(argv[0]);
6213 if (a >= 0) {
6214# if BB_MMU /* see above why on NOMMU it is not allowed */
6215 if (APPLET_IS_NOEXEC(a)) {
6216 debug_printf_exec("running applet '%s'\n", argv[0]);
6217 run_applet_no_and_exit(a, argv);
6218 }
6219# endif
6220 /* Re-exec ourselves */
6221 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6222 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
6223 execv(bb_busybox_exec_path, argv);
6224 /* If they called chroot or otherwise made the binary no longer
6225 * executable, fall through */
6226 }
6227 }
6228#endif
6229
6230#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6231 skip:
6232#endif
6233 execvp_or_die(argv);
6234}
6235
6236/* Called after [v]fork() in run_pipe
6237 */
6238static void pseudo_exec(nommu_save_t *nommu_save,
6239 struct command *command,
6240 char **argv_expanded) NORETURN;
6241static void pseudo_exec(nommu_save_t *nommu_save,
6242 struct command *command,
6243 char **argv_expanded)
6244{
6245 if (command->argv) {
6246 pseudo_exec_argv(nommu_save, command->argv,
6247 command->assignment_cnt, argv_expanded);
6248 }
6249
6250 if (command->group) {
6251 /* Cases when we are here:
6252 * ( list )
6253 * { list } &
6254 * ... | ( list ) | ...
6255 * ... | { list } | ...
6256 */
6257#if BB_MMU
6258 int rcode;
6259 debug_printf_exec("pseudo_exec: run_list\n");
6260 reset_traps_to_defaults();
6261 rcode = run_list(command->group);
6262 /* OK to leak memory by not calling free_pipe_list,
6263 * since this process is about to exit */
6264 _exit(rcode);
6265#else
6266 re_execute_shell(&nommu_save->argv_from_re_execing,
6267 command->group_as_string,
6268 G.global_argv[0],
6269 G.global_argv + 1,
6270 NULL);
6271#endif
6272 }
6273
6274 /* Case when we are here: ... | >file */
6275 debug_printf_exec("pseudo_exec'ed null command\n");
6276 _exit(EXIT_SUCCESS);
6277}
6278
6279#if ENABLE_HUSH_JOB
6280static const char *get_cmdtext(struct pipe *pi)
6281{
6282 char **argv;
6283 char *p;
6284 int len;
6285
6286 /* This is subtle. ->cmdtext is created only on first backgrounding.
6287 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6288 * On subsequent bg argv is trashed, but we won't use it */
6289 if (pi->cmdtext)
6290 return pi->cmdtext;
6291 argv = pi->cmds[0].argv;
6292 if (!argv || !argv[0]) {
6293 pi->cmdtext = xzalloc(1);
6294 return pi->cmdtext;
6295 }
6296
6297 len = 0;
6298 do {
6299 len += strlen(*argv) + 1;
6300 } while (*++argv);
6301 p = xmalloc(len);
6302 pi->cmdtext = p;
6303 argv = pi->cmds[0].argv;
6304 do {
6305 len = strlen(*argv);
6306 memcpy(p, *argv, len);
6307 p += len;
6308 *p++ = ' ';
6309 } while (*++argv);
6310 p[-1] = '\0';
6311 return pi->cmdtext;
6312}
6313
6314static void insert_bg_job(struct pipe *pi)
6315{
6316 struct pipe *job, **jobp;
6317 int i;
6318
6319 /* Linear search for the ID of the job to use */
6320 pi->jobid = 1;
6321 for (job = G.job_list; job; job = job->next)
6322 if (job->jobid >= pi->jobid)
6323 pi->jobid = job->jobid + 1;
6324
6325 /* Add job to the list of running jobs */
6326 jobp = &G.job_list;
6327 while ((job = *jobp) != NULL)
6328 jobp = &job->next;
6329 job = *jobp = xmalloc(sizeof(*job));
6330
6331 *job = *pi; /* physical copy */
6332 job->next = NULL;
6333 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6334 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6335 for (i = 0; i < pi->num_cmds; i++) {
6336 job->cmds[i].pid = pi->cmds[i].pid;
6337 /* all other fields are not used and stay zero */
6338 }
6339 job->cmdtext = xstrdup(get_cmdtext(pi));
6340
6341 if (G_interactive_fd)
6342 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6343 G.last_jobid = job->jobid;
6344}
6345
6346static void remove_bg_job(struct pipe *pi)
6347{
6348 struct pipe *prev_pipe;
6349
6350 if (pi == G.job_list) {
6351 G.job_list = pi->next;
6352 } else {
6353 prev_pipe = G.job_list;
6354 while (prev_pipe->next != pi)
6355 prev_pipe = prev_pipe->next;
6356 prev_pipe->next = pi->next;
6357 }
6358 if (G.job_list)
6359 G.last_jobid = G.job_list->jobid;
6360 else
6361 G.last_jobid = 0;
6362}
6363
6364/* Remove a backgrounded job */
6365static void delete_finished_bg_job(struct pipe *pi)
6366{
6367 remove_bg_job(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006368 free_pipe(pi);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006369}
6370#endif /* JOB */
6371
6372/* Check to see if any processes have exited -- if they
6373 * have, figure out why and see if a job has completed */
Denys Vlasenko27c56f12010-09-07 09:56:34 +02006374static int checkjobs(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006375{
6376 int attributes;
6377 int status;
6378#if ENABLE_HUSH_JOB
6379 struct pipe *pi;
6380#endif
6381 pid_t childpid;
6382 int rcode = 0;
6383
6384 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6385
6386 attributes = WUNTRACED;
6387 if (fg_pipe == NULL)
6388 attributes |= WNOHANG;
6389
6390 errno = 0;
6391#if ENABLE_HUSH_FAST
6392 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6393//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6394//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6395 /* There was neither fork nor SIGCHLD since last waitpid */
6396 /* Avoid doing waitpid syscall if possible */
6397 if (!G.we_have_children) {
6398 errno = ECHILD;
6399 return -1;
6400 }
6401 if (fg_pipe == NULL) { /* is WNOHANG set? */
6402 /* We have children, but they did not exit
6403 * or stop yet (we saw no SIGCHLD) */
6404 return 0;
6405 }
6406 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6407 }
6408#endif
6409
6410/* Do we do this right?
6411 * bash-3.00# sleep 20 | false
6412 * <ctrl-Z pressed>
6413 * [3]+ Stopped sleep 20 | false
6414 * bash-3.00# echo $?
6415 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6416 * [hush 1.14.0: yes we do it right]
6417 */
6418 wait_more:
6419 while (1) {
6420 int i;
6421 int dead;
6422
6423#if ENABLE_HUSH_FAST
6424 i = G.count_SIGCHLD;
6425#endif
6426 childpid = waitpid(-1, &status, attributes);
6427 if (childpid <= 0) {
6428 if (childpid && errno != ECHILD)
6429 bb_perror_msg("waitpid");
6430#if ENABLE_HUSH_FAST
6431 else { /* Until next SIGCHLD, waitpid's are useless */
6432 G.we_have_children = (childpid == 0);
6433 G.handled_SIGCHLD = i;
6434//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6435 }
6436#endif
6437 break;
6438 }
6439 dead = WIFEXITED(status) || WIFSIGNALED(status);
6440
6441#if DEBUG_JOBS
6442 if (WIFSTOPPED(status))
6443 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6444 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6445 if (WIFSIGNALED(status))
6446 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6447 childpid, WTERMSIG(status), WEXITSTATUS(status));
6448 if (WIFEXITED(status))
6449 debug_printf_jobs("pid %d exited, exitcode %d\n",
6450 childpid, WEXITSTATUS(status));
6451#endif
6452 /* Were we asked to wait for fg pipe? */
6453 if (fg_pipe) {
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006454 i = fg_pipe->num_cmds;
6455 while (--i >= 0) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006456 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6457 if (fg_pipe->cmds[i].pid != childpid)
6458 continue;
6459 if (dead) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006460 int ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006461 fg_pipe->cmds[i].pid = 0;
6462 fg_pipe->alive_cmds--;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006463 ex = WEXITSTATUS(status);
6464 /* bash prints killer signal's name for *last*
6465 * process in pipe (prints just newline for SIGINT).
6466 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6467 */
6468 if (WIFSIGNALED(status)) {
6469 int sig = WTERMSIG(status);
6470 if (i == fg_pipe->num_cmds-1)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006471 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006472 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6473 * Maybe we need to use sig | 128? */
6474 ex = sig + 128;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006475 }
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006476 fg_pipe->cmds[i].cmd_exitcode = ex;
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006477 } else {
6478 fg_pipe->cmds[i].is_stopped = 1;
6479 fg_pipe->stopped_cmds++;
6480 }
6481 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6482 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006483 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006484 /* All processes in fg pipe have exited or stopped */
Denys Vlasenko6696eac2010-11-14 02:01:50 +01006485 i = fg_pipe->num_cmds;
6486 while (--i >= 0) {
6487 rcode = fg_pipe->cmds[i].cmd_exitcode;
6488 /* usually last process gives overall exitstatus,
6489 * but with "set -o pipefail", last *failed* process does */
6490 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6491 break;
6492 }
6493 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006494/* Note: *non-interactive* bash does not continue if all processes in fg pipe
6495 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6496 * and "killall -STOP cat" */
6497 if (G_interactive_fd) {
6498#if ENABLE_HUSH_JOB
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006499 if (fg_pipe->alive_cmds != 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006500 insert_bg_job(fg_pipe);
6501#endif
6502 return rcode;
6503 }
Denys Vlasenkoc08c3f52010-11-14 01:59:55 +01006504 if (fg_pipe->alive_cmds == 0)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006505 return rcode;
6506 }
6507 /* There are still running processes in the fg pipe */
6508 goto wait_more; /* do waitpid again */
6509 }
6510 /* it wasnt fg_pipe, look for process in bg pipes */
6511 }
6512
6513#if ENABLE_HUSH_JOB
6514 /* We asked to wait for bg or orphaned children */
6515 /* No need to remember exitcode in this case */
6516 for (pi = G.job_list; pi; pi = pi->next) {
6517 for (i = 0; i < pi->num_cmds; i++) {
6518 if (pi->cmds[i].pid == childpid)
6519 goto found_pi_and_prognum;
6520 }
6521 }
6522 /* Happens when shell is used as init process (init=/bin/sh) */
6523 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6524 continue; /* do waitpid again */
6525
6526 found_pi_and_prognum:
6527 if (dead) {
6528 /* child exited */
6529 pi->cmds[i].pid = 0;
6530 pi->alive_cmds--;
6531 if (!pi->alive_cmds) {
6532 if (G_interactive_fd)
6533 printf(JOB_STATUS_FORMAT, pi->jobid,
6534 "Done", pi->cmdtext);
6535 delete_finished_bg_job(pi);
6536 }
6537 } else {
6538 /* child stopped */
6539 pi->cmds[i].is_stopped = 1;
6540 pi->stopped_cmds++;
6541 }
6542#endif
6543 } /* while (waitpid succeeds)... */
6544
6545 return rcode;
6546}
6547
6548#if ENABLE_HUSH_JOB
Denys Vlasenkoda463fb2010-09-07 09:53:50 +02006549static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006550{
6551 pid_t p;
6552 int rcode = checkjobs(fg_pipe);
6553 if (G_saved_tty_pgrp) {
6554 /* Job finished, move the shell to the foreground */
6555 p = getpgrp(); /* our process group id */
6556 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6557 tcsetpgrp(G_interactive_fd, p);
6558 }
6559 return rcode;
6560}
6561#endif
6562
6563/* Start all the jobs, but don't wait for anything to finish.
6564 * See checkjobs().
6565 *
6566 * Return code is normally -1, when the caller has to wait for children
6567 * to finish to determine the exit status of the pipe. If the pipe
6568 * is a simple builtin command, however, the action is done by the
6569 * time run_pipe returns, and the exit code is provided as the
6570 * return value.
6571 *
6572 * Returns -1 only if started some children. IOW: we have to
6573 * mask out retvals of builtins etc with 0xff!
6574 *
6575 * The only case when we do not need to [v]fork is when the pipe
6576 * is single, non-backgrounded, non-subshell command. Examples:
6577 * cmd ; ... { list } ; ...
6578 * cmd && ... { list } && ...
6579 * cmd || ... { list } || ...
6580 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
6581 * or (if SH_STANDALONE) an applet, and we can run the { list }
6582 * with run_list. If it isn't one of these, we fork and exec cmd.
6583 *
6584 * Cases when we must fork:
6585 * non-single: cmd | cmd
6586 * backgrounded: cmd & { list } &
6587 * subshell: ( list ) [&]
6588 */
6589#if !ENABLE_HUSH_MODE_X
Denys Vlasenko26777aa2010-11-22 23:49:10 +01006590#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006591 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6592#endif
6593static int redirect_and_varexp_helper(char ***new_env_p,
6594 struct variable **old_vars_p,
6595 struct command *command,
6596 int squirrel[3],
6597 char **argv_expanded)
6598{
6599 /* setup_redirects acts on file descriptors, not FILEs.
6600 * This is perfect for work that comes after exec().
6601 * Is it really safe for inline use? Experimentally,
6602 * things seem to work. */
6603 int rcode = setup_redirects(command, squirrel);
6604 if (rcode == 0) {
6605 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6606 *new_env_p = new_env;
6607 dump_cmd_in_x_mode(new_env);
6608 dump_cmd_in_x_mode(argv_expanded);
6609 if (old_vars_p)
6610 *old_vars_p = set_vars_and_save_old(new_env);
6611 }
6612 return rcode;
6613}
6614static NOINLINE int run_pipe(struct pipe *pi)
6615{
6616 static const char *const null_ptr = NULL;
6617
6618 int cmd_no;
6619 int next_infd;
6620 struct command *command;
6621 char **argv_expanded;
6622 char **argv;
6623 /* it is not always needed, but we aim to smaller code */
6624 int squirrel[] = { -1, -1, -1 };
6625 int rcode;
6626
6627 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6628 debug_enter();
6629
Denys Vlasenko1fd3d942010-09-08 13:31:53 +02006630 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6631 * Result should be 3 lines: q w e, qwe, q w e
6632 */
6633 G.ifs = get_local_var_value("IFS");
6634 if (!G.ifs)
6635 G.ifs = defifs;
6636
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006637 IF_HUSH_JOB(pi->pgrp = -1;)
6638 pi->stopped_cmds = 0;
6639 command = &pi->cmds[0];
6640 argv_expanded = NULL;
6641
6642 if (pi->num_cmds != 1
6643 || pi->followup == PIPE_BG
6644 || command->cmd_type == CMD_SUBSHELL
6645 ) {
6646 goto must_fork;
6647 }
6648
6649 pi->alive_cmds = 1;
6650
6651 debug_printf_exec(": group:%p argv:'%s'\n",
6652 command->group, command->argv ? command->argv[0] : "NONE");
6653
6654 if (command->group) {
6655#if ENABLE_HUSH_FUNCTIONS
6656 if (command->cmd_type == CMD_FUNCDEF) {
6657 /* "executing" func () { list } */
6658 struct function *funcp;
6659
6660 funcp = new_function(command->argv[0]);
6661 /* funcp->name is already set to argv[0] */
6662 funcp->body = command->group;
6663# if !BB_MMU
6664 funcp->body_as_string = command->group_as_string;
6665 command->group_as_string = NULL;
6666# endif
6667 command->group = NULL;
6668 command->argv[0] = NULL;
6669 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6670 funcp->parent_cmd = command;
6671 command->child_func = funcp;
6672
6673 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6674 debug_leave();
6675 return EXIT_SUCCESS;
6676 }
6677#endif
6678 /* { list } */
6679 debug_printf("non-subshell group\n");
6680 rcode = 1; /* exitcode if redir failed */
6681 if (setup_redirects(command, squirrel) == 0) {
6682 debug_printf_exec(": run_list\n");
6683 rcode = run_list(command->group) & 0xff;
6684 }
6685 restore_redirects(squirrel);
6686 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6687 debug_leave();
6688 debug_printf_exec("run_pipe: return %d\n", rcode);
6689 return rcode;
6690 }
6691
6692 argv = command->argv ? command->argv : (char **) &null_ptr;
6693 {
6694 const struct built_in_command *x;
6695#if ENABLE_HUSH_FUNCTIONS
6696 const struct function *funcp;
6697#else
6698 enum { funcp = 0 };
6699#endif
6700 char **new_env = NULL;
6701 struct variable *old_vars = NULL;
6702
6703 if (argv[command->assignment_cnt] == NULL) {
6704 /* Assignments, but no command */
6705 /* Ensure redirects take effect (that is, create files).
6706 * Try "a=t >file" */
6707#if 0 /* A few cases in testsuite fail with this code. FIXME */
6708 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
6709 /* Set shell variables */
6710 if (new_env) {
6711 argv = new_env;
6712 while (*argv) {
6713 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
6714 /* Do we need to flag set_local_var() errors?
6715 * "assignment to readonly var" and "putenv error"
6716 */
6717 argv++;
6718 }
6719 }
6720 /* Redirect error sets $? to 1. Otherwise,
6721 * if evaluating assignment value set $?, retain it.
6722 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6723 if (rcode == 0)
6724 rcode = G.last_exitcode;
6725 /* Exit, _skipping_ variable restoring code: */
6726 goto clean_up_and_ret0;
6727
6728#else /* Older, bigger, but more correct code */
6729
6730 rcode = setup_redirects(command, squirrel);
6731 restore_redirects(squirrel);
6732 /* Set shell variables */
6733 if (G_x_mode)
6734 bb_putchar_stderr('+');
6735 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02006736 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006737 if (G_x_mode)
6738 fprintf(stderr, " %s", p);
6739 debug_printf_exec("set shell var:'%s'->'%s'\n",
6740 *argv, p);
6741 set_local_var(p, /*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 if (G_x_mode)
6748 bb_putchar_stderr('\n');
6749 /* Redirect error sets $? to 1. Otherwise,
6750 * if evaluating assignment value set $?, retain it.
6751 * Try "false; q=`exit 2`; echo $?" - should print 2: */
6752 if (rcode == 0)
6753 rcode = G.last_exitcode;
6754 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6755 debug_leave();
6756 debug_printf_exec("run_pipe: return %d\n", rcode);
6757 return rcode;
6758#endif
6759 }
6760
6761 /* Expand the rest into (possibly) many strings each */
6762 if (0) {}
6763#if ENABLE_HUSH_BASH_COMPAT
6764 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
6765 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
6766 }
6767#endif
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006768 else {
6769 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
6770 }
6771
6772 /* if someone gives us an empty string: `cmd with empty output` */
6773 if (!argv_expanded[0]) {
6774 free(argv_expanded);
6775 debug_leave();
6776 return G.last_exitcode;
6777 }
6778
6779 x = find_builtin(argv_expanded[0]);
6780#if ENABLE_HUSH_FUNCTIONS
6781 funcp = NULL;
6782 if (!x)
6783 funcp = find_function(argv_expanded[0]);
6784#endif
6785 if (x || funcp) {
6786 if (!funcp) {
6787 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
6788 debug_printf("exec with redirects only\n");
6789 rcode = setup_redirects(command, NULL);
6790 goto clean_up_and_ret1;
6791 }
6792 }
6793 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6794 if (rcode == 0) {
6795 if (!funcp) {
6796 debug_printf_exec(": builtin '%s' '%s'...\n",
6797 x->b_cmd, argv_expanded[1]);
6798 rcode = x->b_function(argv_expanded) & 0xff;
6799 fflush_all();
6800 }
6801#if ENABLE_HUSH_FUNCTIONS
6802 else {
6803# if ENABLE_HUSH_LOCAL
6804 struct variable **sv;
6805 sv = G.shadowed_vars_pp;
6806 G.shadowed_vars_pp = &old_vars;
6807# endif
6808 debug_printf_exec(": function '%s' '%s'...\n",
6809 funcp->name, argv_expanded[1]);
6810 rcode = run_function(funcp, argv_expanded) & 0xff;
6811# if ENABLE_HUSH_LOCAL
6812 G.shadowed_vars_pp = sv;
6813# endif
6814 }
6815#endif
6816 }
6817 clean_up_and_ret:
6818 unset_vars(new_env);
6819 add_vars(old_vars);
6820/* clean_up_and_ret0: */
6821 restore_redirects(squirrel);
6822 clean_up_and_ret1:
6823 free(argv_expanded);
6824 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6825 debug_leave();
6826 debug_printf_exec("run_pipe return %d\n", rcode);
6827 return rcode;
6828 }
6829
6830 if (ENABLE_FEATURE_SH_STANDALONE) {
6831 int n = find_applet_by_name(argv_expanded[0]);
6832 if (n >= 0 && APPLET_IS_NOFORK(n)) {
6833 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
6834 if (rcode == 0) {
6835 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
6836 argv_expanded[0], argv_expanded[1]);
6837 rcode = run_nofork_applet(n, argv_expanded);
6838 }
6839 goto clean_up_and_ret;
6840 }
6841 }
6842 /* It is neither builtin nor applet. We must fork. */
6843 }
6844
6845 must_fork:
6846 /* NB: argv_expanded may already be created, and that
6847 * might include `cmd` runs! Do not rerun it! We *must*
6848 * use argv_expanded if it's non-NULL */
6849
6850 /* Going to fork a child per each pipe member */
6851 pi->alive_cmds = 0;
6852 next_infd = 0;
6853
6854 cmd_no = 0;
6855 while (cmd_no < pi->num_cmds) {
6856 struct fd_pair pipefds;
6857#if !BB_MMU
6858 volatile nommu_save_t nommu_save;
6859 nommu_save.new_env = NULL;
6860 nommu_save.old_vars = NULL;
6861 nommu_save.argv = NULL;
6862 nommu_save.argv_from_re_execing = NULL;
6863#endif
6864 command = &pi->cmds[cmd_no];
6865 cmd_no++;
6866 if (command->argv) {
6867 debug_printf_exec(": pipe member '%s' '%s'...\n",
6868 command->argv[0], command->argv[1]);
6869 } else {
6870 debug_printf_exec(": pipe member with no argv\n");
6871 }
6872
6873 /* pipes are inserted between pairs of commands */
6874 pipefds.rd = 0;
6875 pipefds.wr = 1;
6876 if (cmd_no < pi->num_cmds)
6877 xpiped_pair(pipefds);
6878
6879 command->pid = BB_MMU ? fork() : vfork();
6880 if (!command->pid) { /* child */
6881#if ENABLE_HUSH_JOB
6882 disable_restore_tty_pgrp_on_exit();
6883 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
6884
6885 /* Every child adds itself to new process group
6886 * with pgid == pid_of_first_child_in_pipe */
6887 if (G.run_list_level == 1 && G_interactive_fd) {
6888 pid_t pgrp;
6889 pgrp = pi->pgrp;
6890 if (pgrp < 0) /* true for 1st process only */
6891 pgrp = getpid();
6892 if (setpgid(0, pgrp) == 0
6893 && pi->followup != PIPE_BG
6894 && G_saved_tty_pgrp /* we have ctty */
6895 ) {
6896 /* We do it in *every* child, not just first,
6897 * to avoid races */
6898 tcsetpgrp(G_interactive_fd, pgrp);
6899 }
6900 }
6901#endif
6902 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
6903 /* 1st cmd in backgrounded pipe
6904 * should have its stdin /dev/null'ed */
6905 close(0);
6906 if (open(bb_dev_null, O_RDONLY))
6907 xopen("/", O_RDONLY);
6908 } else {
6909 xmove_fd(next_infd, 0);
6910 }
6911 xmove_fd(pipefds.wr, 1);
6912 if (pipefds.rd > 1)
6913 close(pipefds.rd);
6914 /* Like bash, explicit redirects override pipes,
6915 * and the pipe fd is available for dup'ing. */
6916 if (setup_redirects(command, NULL))
6917 _exit(1);
6918
6919 /* Restore default handlers just prior to exec */
6920 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
6921
6922 /* Stores to nommu_save list of env vars putenv'ed
6923 * (NOMMU, on MMU we don't need that) */
6924 /* cast away volatility... */
6925 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
6926 /* pseudo_exec() does not return */
6927 }
6928
6929 /* parent or error */
6930#if ENABLE_HUSH_FAST
6931 G.count_SIGCHLD++;
6932//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6933#endif
6934 enable_restore_tty_pgrp_on_exit();
6935#if !BB_MMU
6936 /* Clean up after vforked child */
6937 free(nommu_save.argv);
6938 free(nommu_save.argv_from_re_execing);
6939 unset_vars(nommu_save.new_env);
6940 add_vars(nommu_save.old_vars);
6941#endif
6942 free(argv_expanded);
6943 argv_expanded = NULL;
6944 if (command->pid < 0) { /* [v]fork failed */
6945 /* Clearly indicate, was it fork or vfork */
6946 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
6947 } else {
6948 pi->alive_cmds++;
6949#if ENABLE_HUSH_JOB
6950 /* Second and next children need to know pid of first one */
6951 if (pi->pgrp < 0)
6952 pi->pgrp = command->pid;
6953#endif
6954 }
6955
6956 if (cmd_no > 1)
6957 close(next_infd);
6958 if (cmd_no < pi->num_cmds)
6959 close(pipefds.wr);
6960 /* Pass read (output) pipe end to next iteration */
6961 next_infd = pipefds.rd;
6962 }
6963
6964 if (!pi->alive_cmds) {
6965 debug_leave();
6966 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
6967 return 1;
6968 }
6969
6970 debug_leave();
6971 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
6972 return -1;
6973}
6974
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006975/* NB: called by pseudo_exec, and therefore must not modify any
6976 * global data until exec/_exit (we can be a child after vfork!) */
6977static int run_list(struct pipe *pi)
6978{
6979#if ENABLE_HUSH_CASE
6980 char *case_word = NULL;
6981#endif
6982#if ENABLE_HUSH_LOOPS
6983 struct pipe *loop_top = NULL;
6984 char **for_lcur = NULL;
6985 char **for_list = NULL;
6986#endif
6987 smallint last_followup;
6988 smalluint rcode;
6989#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
6990 smalluint cond_code = 0;
6991#else
6992 enum { cond_code = 0 };
6993#endif
6994#if HAS_KEYWORDS
Denys Vlasenko9b782552010-09-08 13:33:26 +02006995 smallint rword; /* RES_foo */
Denys Vlasenkob36abf22010-09-05 14:50:59 +02006996 smallint last_rword; /* ditto */
6997#endif
6998
6999 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7000 debug_enter();
7001
7002#if ENABLE_HUSH_LOOPS
7003 /* Check syntax for "for" */
7004 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
7005 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7006 continue;
7007 /* current word is FOR or IN (BOLD in comments below) */
7008 if (cpipe->next == NULL) {
7009 syntax_error("malformed for");
7010 debug_leave();
7011 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7012 return 1;
7013 }
7014 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7015 if (cpipe->next->res_word == RES_DO)
7016 continue;
7017 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7018 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7019 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7020 ) {
7021 syntax_error("malformed for");
7022 debug_leave();
7023 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7024 return 1;
7025 }
7026 }
7027#endif
7028
7029 /* Past this point, all code paths should jump to ret: label
7030 * in order to return, no direct "return" statements please.
7031 * This helps to ensure that no memory is leaked. */
7032
7033#if ENABLE_HUSH_JOB
7034 G.run_list_level++;
7035#endif
7036
7037#if HAS_KEYWORDS
7038 rword = RES_NONE;
7039 last_rword = RES_XXXX;
7040#endif
7041 last_followup = PIPE_SEQ;
7042 rcode = G.last_exitcode;
7043
7044 /* Go through list of pipes, (maybe) executing them. */
7045 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7046 if (G.flag_SIGINT)
7047 break;
7048
7049 IF_HAS_KEYWORDS(rword = pi->res_word;)
7050 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7051 rword, cond_code, last_rword);
7052#if ENABLE_HUSH_LOOPS
7053 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7054 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7055 ) {
7056 /* start of a loop: remember where loop starts */
7057 loop_top = pi;
7058 G.depth_of_loop++;
7059 }
7060#endif
7061 /* Still in the same "if...", "then..." or "do..." branch? */
7062 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7063 if ((rcode == 0 && last_followup == PIPE_OR)
7064 || (rcode != 0 && last_followup == PIPE_AND)
7065 ) {
7066 /* It is "<true> || CMD" or "<false> && CMD"
7067 * and we should not execute CMD */
7068 debug_printf_exec("skipped cmd because of || or &&\n");
7069 last_followup = pi->followup;
7070 continue;
7071 }
7072 }
7073 last_followup = pi->followup;
7074 IF_HAS_KEYWORDS(last_rword = rword;)
7075#if ENABLE_HUSH_IF
7076 if (cond_code) {
7077 if (rword == RES_THEN) {
7078 /* if false; then ... fi has exitcode 0! */
7079 G.last_exitcode = rcode = EXIT_SUCCESS;
7080 /* "if <false> THEN cmd": skip cmd */
7081 continue;
7082 }
7083 } else {
7084 if (rword == RES_ELSE || rword == RES_ELIF) {
7085 /* "if <true> then ... ELSE/ELIF cmd":
7086 * skip cmd and all following ones */
7087 break;
7088 }
7089 }
7090#endif
7091#if ENABLE_HUSH_LOOPS
7092 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7093 if (!for_lcur) {
7094 /* first loop through for */
7095
7096 static const char encoded_dollar_at[] ALIGN1 = {
7097 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7098 }; /* encoded representation of "$@" */
7099 static const char *const encoded_dollar_at_argv[] = {
7100 encoded_dollar_at, NULL
7101 }; /* argv list with one element: "$@" */
7102 char **vals;
7103
7104 vals = (char**)encoded_dollar_at_argv;
7105 if (pi->next->res_word == RES_IN) {
7106 /* if no variable values after "in" we skip "for" */
7107 if (!pi->next->cmds[0].argv) {
7108 G.last_exitcode = rcode = EXIT_SUCCESS;
7109 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7110 break;
7111 }
7112 vals = pi->next->cmds[0].argv;
7113 } /* else: "for var; do..." -> assume "$@" list */
7114 /* create list of variable values */
7115 debug_print_strings("for_list made from", vals);
7116 for_list = expand_strvec_to_strvec(vals);
7117 for_lcur = for_list;
7118 debug_print_strings("for_list", for_list);
7119 }
7120 if (!*for_lcur) {
7121 /* "for" loop is over, clean up */
7122 free(for_list);
7123 for_list = NULL;
7124 for_lcur = NULL;
7125 break;
7126 }
7127 /* Insert next value from for_lcur */
7128 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7129 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7130 continue;
7131 }
7132 if (rword == RES_IN) {
7133 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7134 }
7135 if (rword == RES_DONE) {
7136 continue; /* "done" has no cmds too */
7137 }
7138#endif
7139#if ENABLE_HUSH_CASE
7140 if (rword == RES_CASE) {
7141 case_word = expand_strvec_to_string(pi->cmds->argv);
7142 continue;
7143 }
7144 if (rword == RES_MATCH) {
7145 char **argv;
7146
7147 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7148 break;
7149 /* all prev words didn't match, does this one match? */
7150 argv = pi->cmds->argv;
7151 while (*argv) {
Denys Vlasenkoebee4102010-09-10 10:17:53 +02007152 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
Denys Vlasenkob36abf22010-09-05 14:50:59 +02007153 /* TODO: which FNM_xxx flags to use? */
7154 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7155 free(pattern);
7156 if (cond_code == 0) { /* match! we will execute this branch */
7157 free(case_word); /* make future "word)" stop */
7158 case_word = NULL;
7159 break;
7160 }
7161 argv++;
7162 }
7163 continue;
7164 }
7165 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7166 if (cond_code != 0)
7167 continue; /* not matched yet, skip this pipe */
7168 }
7169#endif
7170 /* Just pressing <enter> in shell should check for jobs.
7171 * OTOH, in non-interactive shell this is useless
7172 * and only leads to extra job checks */
7173 if (pi->num_cmds == 0) {
7174 if (G_interactive_fd)
7175 goto check_jobs_and_continue;
7176 continue;
7177 }
7178
7179 /* After analyzing all keywords and conditions, we decided
7180 * to execute this pipe. NB: have to do checkjobs(NULL)
7181 * after run_pipe to collect any background children,
7182 * even if list execution is to be stopped. */
7183 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7184 {
7185 int r;
7186#if ENABLE_HUSH_LOOPS
7187 G.flag_break_continue = 0;
7188#endif
7189 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7190 if (r != -1) {
7191 /* We ran a builtin, function, or group.
7192 * rcode is already known
7193 * and we don't need to wait for anything. */
7194 G.last_exitcode = rcode;
7195 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7196 check_and_run_traps(0);
7197#if ENABLE_HUSH_LOOPS
7198 /* Was it "break" or "continue"? */
7199 if (G.flag_break_continue) {
7200 smallint fbc = G.flag_break_continue;
7201 /* We might fall into outer *loop*,
7202 * don't want to break it too */
7203 if (loop_top) {
7204 G.depth_break_continue--;
7205 if (G.depth_break_continue == 0)
7206 G.flag_break_continue = 0;
7207 /* else: e.g. "continue 2" should *break* once, *then* continue */
7208 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7209 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7210 goto check_jobs_and_break;
7211 /* "continue": simulate end of loop */
7212 rword = RES_DONE;
7213 continue;
7214 }
7215#endif
7216#if ENABLE_HUSH_FUNCTIONS
7217 if (G.flag_return_in_progress == 1) {
7218 /* same as "goto check_jobs_and_break" */
7219 checkjobs(NULL);
7220 break;
7221 }
7222#endif
7223 } else if (pi->followup == PIPE_BG) {
7224 /* What does bash do with attempts to background builtins? */
7225 /* even bash 3.2 doesn't do that well with nested bg:
7226 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7227 * I'm NOT treating inner &'s as jobs */
7228 check_and_run_traps(0);
7229#if ENABLE_HUSH_JOB
7230 if (G.run_list_level == 1)
7231 insert_bg_job(pi);
7232#endif
7233 /* Last command's pid goes to $! */
7234 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7235 G.last_exitcode = rcode = EXIT_SUCCESS;
7236 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7237 } else {
7238#if ENABLE_HUSH_JOB
7239 if (G.run_list_level == 1 && G_interactive_fd) {
7240 /* Waits for completion, then fg's main shell */
7241 rcode = checkjobs_and_fg_shell(pi);
7242 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7243 check_and_run_traps(0);
7244 } else
7245#endif
7246 { /* This one just waits for completion */
7247 rcode = checkjobs(pi);
7248 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7249 check_and_run_traps(0);
7250 }
7251 G.last_exitcode = rcode;
7252 }
7253 }
7254
7255 /* Analyze how result affects subsequent commands */
7256#if ENABLE_HUSH_IF
7257 if (rword == RES_IF || rword == RES_ELIF)
7258 cond_code = rcode;
7259#endif
7260#if ENABLE_HUSH_LOOPS
7261 /* Beware of "while false; true; do ..."! */
7262 if (pi->next && pi->next->res_word == RES_DO) {
7263 if (rword == RES_WHILE) {
7264 if (rcode) {
7265 /* "while false; do...done" - exitcode 0 */
7266 G.last_exitcode = rcode = EXIT_SUCCESS;
7267 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7268 goto check_jobs_and_break;
7269 }
7270 }
7271 if (rword == RES_UNTIL) {
7272 if (!rcode) {
7273 debug_printf_exec(": until expr is true: breaking\n");
7274 check_jobs_and_break:
7275 checkjobs(NULL);
7276 break;
7277 }
7278 }
7279 }
7280#endif
7281
7282 check_jobs_and_continue:
7283 checkjobs(NULL);
7284 } /* for (pi) */
7285
7286#if ENABLE_HUSH_JOB
7287 G.run_list_level--;
7288#endif
7289#if ENABLE_HUSH_LOOPS
7290 if (loop_top)
7291 G.depth_of_loop--;
7292 free(for_list);
7293#endif
7294#if ENABLE_HUSH_CASE
7295 free(case_word);
7296#endif
7297 debug_leave();
7298 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7299 return rcode;
7300}
7301
7302/* Select which version we will use */
7303static int run_and_free_list(struct pipe *pi)
7304{
7305 int rcode = 0;
7306 debug_printf_exec("run_and_free_list entered\n");
7307 if (!G.n_mode) {
7308 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7309 rcode = run_list(pi);
7310 }
7311 /* free_pipe_list has the side effect of clearing memory.
7312 * In the long run that function can be merged with run_list,
7313 * but doing that now would hobble the debugging effort. */
7314 free_pipe_list(pi);
7315 debug_printf_exec("run_and_free_list return %d\n", rcode);
7316 return rcode;
7317}
7318
7319
Denis Vlasenkof9375282009-04-05 19:13:39 +00007320/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007321static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007322{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007323 unsigned sig;
7324 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007325 sigset_t old_blocked_set;
7326
7327 if (!G.inherited_set_is_saved) {
7328 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7329 G.inherited_set = G.blocked_set;
7330 }
7331 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007332
Denis Vlasenkof9375282009-04-05 19:13:39 +00007333 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007334 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007335 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007336 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007337 mask |= SPECIAL_JOB_SIGS;
7338 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007339 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007340
Denis Vlasenkof9375282009-04-05 19:13:39 +00007341 sig = 0;
7342 while (mask) {
7343 if (mask & 1)
7344 sigaddset(&G.blocked_set, sig);
7345 mask >>= 1;
7346 sig++;
7347 }
7348 sigdelset(&G.blocked_set, SIGCHLD);
7349
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007350 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7351 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7352
Denis Vlasenkof9375282009-04-05 19:13:39 +00007353 /* POSIX allows shell to re-enable SIGCHLD
7354 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007355#if ENABLE_HUSH_FAST
7356 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007357 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007358 signal(SIGCHLD, SIGCHLD_handler);
7359#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007360 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007361 signal(SIGCHLD, SIG_DFL);
7362#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007363
7364 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007365}
7366
7367#if ENABLE_HUSH_JOB
7368/* helper */
7369static void maybe_set_to_sigexit(int sig)
7370{
7371 void (*handler)(int);
7372 /* non_DFL_mask'ed signals are, well, masked,
7373 * no need to set handler for them.
7374 */
7375 if (!((G.non_DFL_mask >> sig) & 1)) {
7376 handler = signal(sig, sigexit);
7377 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7378 signal(sig, handler);
7379 }
7380}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007381/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007382static void set_fatal_handlers(void)
7383{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007384 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007385 if (HUSH_DEBUG) {
7386 maybe_set_to_sigexit(SIGILL );
7387 maybe_set_to_sigexit(SIGFPE );
7388 maybe_set_to_sigexit(SIGBUS );
7389 maybe_set_to_sigexit(SIGSEGV);
7390 maybe_set_to_sigexit(SIGTRAP);
7391 } /* else: hush is perfect. what SEGV? */
7392 maybe_set_to_sigexit(SIGABRT);
7393 /* bash 3.2 seems to handle these just like 'fatal' ones */
7394 maybe_set_to_sigexit(SIGPIPE);
7395 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007396 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007397 * if we aren't interactive... but in this case
7398 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007399 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007400 /*maybe_set_to_sigexit(SIGTERM);*/
7401 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007402}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007403#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007404
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007405static int set_mode(int state, char mode, const char *o_opt)
Denis Vlasenkod5762932009-03-31 11:22:57 +00007406{
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007407 int idx;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007408 switch (mode) {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007409 case 'n':
7410 G.n_mode = state;
7411 break;
7412 case 'x':
7413 IF_HUSH_MODE_X(G_x_mode = state;)
7414 break;
7415 case 'o':
7416 if (!o_opt) {
7417 /* "set -+o" without parameter.
7418 * in bash, set -o produces this output:
7419 * pipefail off
7420 * and set +o:
7421 * set +o pipefail
7422 * We always use the second form.
7423 */
7424 const char *p = o_opt_strings;
7425 idx = 0;
7426 while (*p) {
7427 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7428 idx++;
7429 p += strlen(p) + 1;
7430 }
7431 break;
7432 }
7433 idx = index_in_strings(o_opt_strings, o_opt);
7434 if (idx >= 0) {
7435 G.o_opt[idx] = state;
7436 break;
7437 }
7438 default:
7439 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007440 }
7441 return EXIT_SUCCESS;
7442}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007443
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007444int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007445int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007446{
7447 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007448 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007449 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007450 struct variable *cur_var;
Denys Vlasenko52e460b2010-09-16 16:12:00 +02007451 struct variable shell_ver;
Eric Andersenbc604a22001-05-16 05:24:03 +00007452
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007453 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007454 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007455 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007456#if !BB_MMU
7457 G.argv0_for_re_execing = argv[0];
7458#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007459 /* Deal with HUSH_VERSION */
Denys Vlasenko52e460b2010-09-16 16:12:00 +02007460 memset(&shell_ver, 0, sizeof(shell_ver));
7461 shell_ver.flg_export = 1;
7462 shell_ver.flg_read_only = 1;
Denys Vlasenko4f870492010-09-10 11:06:01 +02007463 /* Code which handles ${var<op>...} needs writable values for all variables,
Denys Vlasenko36f774a2010-09-05 14:45:38 +02007464 * therefore we xstrdup: */
Denys Vlasenko52e460b2010-09-16 16:12:00 +02007465 shell_ver.varstr = xstrdup(hush_version_str),
7466 G.top_var = &shell_ver;
Denys Vlasenko605067b2010-09-06 12:10:51 +02007467 /* Create shell local variables from the values
7468 * currently living in the environment */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007469 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007470 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007471 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007472 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007473 if (e) while (*e) {
7474 char *value = strchr(*e, '=');
7475 if (value) { /* paranoia */
7476 cur_var->next = xzalloc(sizeof(*cur_var));
7477 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007478 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007479 cur_var->max_len = strlen(*e);
7480 cur_var->flg_export = 1;
7481 }
7482 e++;
7483 }
Denys Vlasenko605067b2010-09-06 12:10:51 +02007484 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
Denys Vlasenko52e460b2010-09-16 16:12:00 +02007485 debug_printf_env("putenv '%s'\n", shell_ver.varstr);
7486 putenv(shell_ver.varstr);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007487
7488 /* Export PWD */
7489 set_pwd_var(/*exp:*/ 1);
7490 /* bash also exports SHLVL and _,
7491 * and sets (but doesn't export) the following variables:
7492 * BASH=/bin/bash
7493 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7494 * BASH_VERSION='3.2.0(1)-release'
7495 * HOSTTYPE=i386
7496 * MACHTYPE=i386-pc-linux-gnu
7497 * OSTYPE=linux-gnu
7498 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007499 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007500 * EUID=<NNNNN>
7501 * UID=<NNNNN>
7502 * GROUPS=()
7503 * LINES=<NNN>
7504 * COLUMNS=<NNN>
7505 * BASH_ARGC=()
7506 * BASH_ARGV=()
7507 * BASH_LINENO=()
7508 * BASH_SOURCE=()
7509 * DIRSTACK=()
7510 * PIPESTATUS=([0]="0")
7511 * HISTFILE=/<xxx>/.bash_history
7512 * HISTFILESIZE=500
7513 * HISTSIZE=500
7514 * MAILCHECK=60
7515 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7516 * SHELL=/bin/bash
7517 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7518 * TERM=dumb
7519 * OPTERR=1
7520 * OPTIND=1
7521 * IFS=$' \t\n'
7522 * PS1='\s-\v\$ '
7523 * PS2='> '
7524 * PS4='+ '
7525 */
7526
Denis Vlasenko38f63192007-01-22 09:03:07 +00007527#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007528 G.line_input_state = new_line_input_t(FOR_SHELL);
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007529# if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_HUSH_SAVEHISTORY
7530 {
7531 const char *hp = get_local_var_value("HISTFILE");
7532 if (!hp) {
7533 hp = get_local_var_value("HOME");
7534 if (hp) {
7535 G.line_input_state->hist_file = concat_path_file(hp, ".hush_history");
7536 //set_local_var(xasprintf("HISTFILE=%s", ...));
7537 }
7538 }
7539 }
7540# endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007541#endif
Denys Vlasenko99862cb2010-09-12 17:34:13 +02007542
Denis Vlasenko87a86552008-07-29 19:43:10 +00007543 G.global_argc = argc;
7544 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007545 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007546 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007547
Denis Vlasenkoed782372009-04-10 00:45:02 +00007548 if (setjmp(die_jmp)) {
7549 /* xfunc has failed! die die die */
7550 /* no EXIT traps, this is an escape hatch! */
7551 G.exiting = 1;
7552 hush_exit(xfunc_error_retval);
7553 }
7554
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007555 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007556 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007557 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007558 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007559 * in order to intercept (more) signals.
7560 */
7561
7562 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007563 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007564 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007565 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007566 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007567#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007568 "<:$:R:V:"
7569# if ENABLE_HUSH_FUNCTIONS
7570 "F:"
7571# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007572#endif
7573 );
7574 if (opt <= 0)
7575 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007576 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007577 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007578 /* Possibilities:
7579 * sh ... -c 'script'
7580 * sh ... -c 'script' ARG0 [ARG1...]
7581 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007582 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007583 * "" needs to be replaced with NULL
7584 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007585 * Note: the form without ARG0 never happens:
7586 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007587 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007588 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007589 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007590 G.root_ppid = getppid();
7591 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007592 G.global_argv = argv + optind;
7593 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007594 if (builtin_argc) {
7595 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7596 const struct built_in_command *x;
7597
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007598 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007599 x = find_builtin(optarg);
7600 if (x) { /* paranoia */
7601 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7602 G.global_argv += builtin_argc;
7603 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007604 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007605 }
7606 goto final_return;
7607 }
7608 if (!G.global_argv[0]) {
7609 /* -c 'script' (no params): prevent empty $0 */
7610 G.global_argv--; /* points to argv[i] of 'script' */
7611 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007612 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007613 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007614 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007615 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007616 goto final_return;
7617 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007618 /* Well, we cannot just declare interactiveness,
7619 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007620 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007621 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007622 case 's':
7623 /* "-s" means "read from stdin", but this is how we always
7624 * operate, so simply do nothing here. */
7625 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007626#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007627 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007628 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007629 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007630 case '$': {
7631 unsigned long long empty_trap_mask;
7632
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007633 G.root_pid = bb_strtou(optarg, &optarg, 16);
7634 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007635 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7636 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007637 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7638 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007639 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007640 optarg++;
7641 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007642 optarg++;
7643 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7644 if (empty_trap_mask != 0) {
7645 int sig;
7646 init_sigmasks();
7647 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7648 for (sig = 1; sig < NSIG; sig++) {
7649 if (empty_trap_mask & (1LL << sig)) {
7650 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7651 sigaddset(&G.blocked_set, sig);
7652 }
7653 }
7654 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7655 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007656# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007657 optarg++;
7658 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007659# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007660 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007661 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007662 case 'R':
7663 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007664 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007665 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007666# if ENABLE_HUSH_FUNCTIONS
7667 case 'F': {
7668 struct function *funcp = new_function(optarg);
7669 /* funcp->name is already set to optarg */
7670 /* funcp->body is set to NULL. It's a special case. */
7671 funcp->body_as_string = argv[optind];
7672 optind++;
7673 break;
7674 }
7675# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007676#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007677 case 'n':
7678 case 'x':
Denys Vlasenko6696eac2010-11-14 02:01:50 +01007679 if (set_mode(1, opt, NULL) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007680 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007681 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007682#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007683 fprintf(stderr, "Usage: sh [FILE]...\n"
7684 " or: sh -c command [args]...\n\n");
7685 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007686#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007687 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007688#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007689 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007690 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007691
Denys Vlasenkodea47882009-10-09 15:40:49 +02007692 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007693 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007694 G.root_ppid = getppid();
7695 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007696
7697 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007698 if (argv[0] && argv[0][0] == '-') {
7699 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007700 debug_printf("sourcing /etc/profile\n");
7701 input = fopen_for_read("/etc/profile");
7702 if (input != NULL) {
7703 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007704 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007705 parse_and_run_file(input);
7706 fclose(input);
7707 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007708 /* bash: after sourcing /etc/profile,
7709 * tries to source (in the given order):
7710 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007711 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007712 * bash also sources ~/.bash_logout on exit.
7713 * If called as sh, skips .bash_XXX files.
7714 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007715 }
7716
Denis Vlasenkof9375282009-04-05 19:13:39 +00007717 if (argv[optind]) {
7718 FILE *input;
7719 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007720 * "bash <script>" (which is never interactive (unless -i?))
7721 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007722 * If called as sh, does the same but with $ENV.
7723 */
7724 debug_printf("running script '%s'\n", argv[optind]);
7725 G.global_argv = argv + optind;
7726 G.global_argc = argc - optind;
7727 input = xfopen_for_read(argv[optind]);
7728 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007729 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007730 parse_and_run_file(input);
7731#if ENABLE_FEATURE_CLEAN_UP
7732 fclose(input);
7733#endif
7734 goto final_return;
7735 }
7736
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007737 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007738 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007739 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007740
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007741 /* A shell is interactive if the '-i' flag was given,
7742 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007743 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007744 * no arguments remaining or the -s flag given
7745 * standard input is a terminal
7746 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007747 * Refer to Posix.2, the description of the 'sh' utility.
7748 */
7749#if ENABLE_HUSH_JOB
7750 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007751 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7752 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7753 if (G_saved_tty_pgrp < 0)
7754 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007755
7756 /* try to dup stdin to high fd#, >= 255 */
7757 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7758 if (G_interactive_fd < 0) {
7759 /* try to dup to any fd */
7760 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007761 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007762 /* give up */
7763 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007764 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007765 }
7766 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007767// TODO: track & disallow any attempts of user
7768// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007769 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007770 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007771 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007772 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007773
Mike Frysinger38478a62009-05-20 04:48:06 -04007774 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007775 /* If we were run as 'hush &', sleep until we are
7776 * in the foreground (tty pgrp == our pgrp).
7777 * If we get started under a job aware app (like bash),
7778 * make sure we are now in charge so we don't fight over
7779 * who gets the foreground */
7780 while (1) {
7781 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007782 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7783 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007784 break;
7785 /* send TTIN to ourself (should stop us) */
7786 kill(- shell_pgrp, SIGTTIN);
7787 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007788 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007789
Denis Vlasenkof9375282009-04-05 19:13:39 +00007790 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007791 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007792
Mike Frysinger38478a62009-05-20 04:48:06 -04007793 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007794 /* Set other signals to restore saved_tty_pgrp */
7795 set_fatal_handlers();
7796 /* Put ourselves in our own process group
7797 * (bash, too, does this only if ctty is available) */
7798 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7799 /* Grab control of the terminal */
7800 tcsetpgrp(G_interactive_fd, getpid());
7801 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007802 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007803 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007804 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007805 } else {
7806 init_sigmasks();
7807 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007808#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007809 /* No job control compiled in, only prompt/line editing */
7810 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007811 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7812 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007813 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007814 G_interactive_fd = dup(STDIN_FILENO);
7815 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007816 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007817 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007818 }
7819 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007820 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007821 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007822 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007823 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007824#else
7825 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007826 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007827#endif
7828 /* bash:
7829 * if interactive but not a login shell, sources ~/.bashrc
7830 * (--norc turns this off, --rcfile <file> overrides)
7831 */
7832
7833 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007834 /* note: ash and hush share this string */
7835 printf("\n\n%s %s\n"
7836 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7837 "\n",
7838 bb_banner,
7839 "hush - the humble shell"
7840 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007841 }
7842
Denis Vlasenkof9375282009-04-05 19:13:39 +00007843 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007844
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007845 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007846#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007847 if (G.cwd != bb_msg_unknown)
7848 free((char*)G.cwd);
7849 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007850 while (cur_var) {
7851 struct variable *tmp = cur_var;
7852 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007853 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007854 cur_var = cur_var->next;
7855 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007856 }
Eric Andersen25f27032001-04-26 23:22:31 +00007857#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007858 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007859}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007860
7861
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007862#if ENABLE_MSH
7863int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7864int msh_main(int argc, char **argv)
7865{
7866 //bb_error_msg("msh is deprecated, please use hush instead");
7867 return hush_main(argc, argv);
7868}
7869#endif
7870
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007871
7872/*
7873 * Built-ins
7874 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007875static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007876{
7877 return 0;
7878}
7879
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007880static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007881{
7882 int argc = 0;
7883 while (*argv) {
7884 argc++;
7885 argv++;
7886 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007887 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007888}
7889
7890static int FAST_FUNC builtin_test(char **argv)
7891{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007892 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007893}
7894
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007895static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007896{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007897 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007898}
7899
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007900#if ENABLE_PRINTF
7901static int FAST_FUNC builtin_printf(char **argv)
7902{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007903 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007904}
7905#endif
7906
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007907static char **skip_dash_dash(char **argv)
7908{
7909 argv++;
7910 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7911 argv++;
7912 return argv;
7913}
7914
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007915static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007916{
7917 int rcode = EXIT_SUCCESS;
7918
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007919 argv = skip_dash_dash(argv);
7920 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007921 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007922 /* bash:
7923 * eval "echo Hi; done" ("done" is syntax error):
7924 * "echo Hi" will not execute too.
7925 */
7926 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007927 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007928 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007929 }
7930 return rcode;
7931}
7932
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007933static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007934{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007935 const char *newdir;
7936
7937 argv = skip_dash_dash(argv);
7938 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007939 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007940 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007941 * bash says "bash: cd: HOME not set" and does nothing
7942 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007943 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007944 const char *home = get_local_var_value("HOME");
7945 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007946 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007947 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007948 /* Mimic bash message exactly */
7949 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007950 return EXIT_FAILURE;
7951 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007952 /* Read current dir (get_cwd(1) is inside) and set PWD.
7953 * Note: do not enforce exporting. If PWD was unset or unexported,
7954 * set it again, but do not export. bash does the same.
7955 */
7956 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007957 return EXIT_SUCCESS;
7958}
7959
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007960static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007961{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007962 argv = skip_dash_dash(argv);
7963 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007964 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007965
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007966 /* Careful: we can end up here after [v]fork. Do not restore
7967 * tty pgrp then, only top-level shell process does that */
7968 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7969 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7970
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007971 /* TODO: if exec fails, bash does NOT exit! We do.
7972 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7973 * and tcsetpgrp, and this is inherently racy.
7974 */
7975 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007976}
7977
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007978static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007979{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007980 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007981
7982 /* interactive bash:
7983 * # trap "echo EEE" EXIT
7984 * # exit
7985 * exit
7986 * There are stopped jobs.
7987 * (if there are _stopped_ jobs, running ones don't count)
7988 * # exit
7989 * exit
7990 # EEE (then bash exits)
7991 *
Denys Vlasenkoa110c902010-09-12 15:38:04 +02007992 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
Denis Vlasenko40e84372009-04-18 11:23:38 +00007993 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007994
7995 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007996 argv = skip_dash_dash(argv);
7997 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007998 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007999 /* mimic bash: exit 123abc == exit 255 + error msg */
8000 xfunc_error_retval = 255;
8001 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008002 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008003}
8004
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008005static void print_escaped(const char *s)
8006{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008007 if (*s == '\'')
8008 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008009 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008010 const char *p = strchrnul(s, '\'');
8011 /* print 'xxxx', possibly just '' */
8012 printf("'%.*s'", (int)(p - s), s);
8013 if (*p == '\0')
8014 break;
8015 s = p;
8016 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008017 /* s points to '; print "'''...'''" */
8018 putchar('"');
8019 do putchar('\''); while (*++s == '\'');
8020 putchar('"');
8021 } while (*s);
8022}
8023
Denys Vlasenko295fef82009-06-03 12:47:26 +02008024#if !ENABLE_HUSH_LOCAL
8025#define helper_export_local(argv, exp, lvl) \
8026 helper_export_local(argv, exp)
8027#endif
8028static void helper_export_local(char **argv, int exp, int lvl)
8029{
8030 do {
8031 char *name = *argv;
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008032 char *name_end = strchrnul(name, '=');
Denys Vlasenko295fef82009-06-03 12:47:26 +02008033
8034 /* So far we do not check that name is valid (TODO?) */
8035
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008036 if (*name_end == '\0') {
8037 struct variable *var, **vpp;
Denys Vlasenko295fef82009-06-03 12:47:26 +02008038
Denys Vlasenko27c56f12010-09-07 09:56:34 +02008039 vpp = get_ptr_to_local_var(name, name_end - name);
8040 var = vpp ? *vpp : NULL;
8041
Denys Vlasenko295fef82009-06-03 12:47:26 +02008042 if (exp == -1) { /* unexporting? */
8043 /* export -n NAME (without =VALUE) */
8044 if (var) {
8045 var->flg_export = 0;
8046 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8047 unsetenv(name);
8048 } /* else: export -n NOT_EXISTING_VAR: no-op */
8049 continue;
8050 }
8051 if (exp == 1) { /* exporting? */
8052 /* export NAME (without =VALUE) */
8053 if (var) {
8054 var->flg_export = 1;
8055 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8056 putenv(var->varstr);
8057 continue;
8058 }
8059 }
8060 /* Exporting non-existing variable.
8061 * bash does not put it in environment,
8062 * but remembers that it is exported,
8063 * and does put it in env when it is set later.
8064 * We just set it to "" and export. */
8065 /* Or, it's "local NAME" (without =VALUE).
8066 * bash sets the value to "". */
8067 name = xasprintf("%s=", name);
8068 } else {
8069 /* (Un)exporting/making local NAME=VALUE */
8070 name = xstrdup(name);
8071 }
8072 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8073 } while (*++argv);
8074}
8075
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008076static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008077{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00008078 unsigned opt_unexport;
8079
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02008080#if ENABLE_HUSH_EXPORT_N
8081 /* "!": do not abort on errors */
8082 opt_unexport = getopt32(argv, "!n");
8083 if (opt_unexport == (uint32_t)-1)
8084 return EXIT_FAILURE;
8085 argv += optind;
8086#else
8087 opt_unexport = 0;
8088 argv++;
8089#endif
8090
8091 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008092 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008093 if (e) {
8094 while (*e) {
8095#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008096 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008097#else
8098 /* ash emits: export VAR='VAL'
8099 * bash: declare -x VAR="VAL"
8100 * we follow ash example */
8101 const char *s = *e++;
8102 const char *p = strchr(s, '=');
8103
8104 if (!p) /* wtf? take next variable */
8105 continue;
8106 /* export var= */
8107 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008108 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008109 putchar('\n');
8110#endif
8111 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008112 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00008113 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008114 return EXIT_SUCCESS;
8115 }
8116
Denys Vlasenko295fef82009-06-03 12:47:26 +02008117 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008118
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008119 return EXIT_SUCCESS;
8120}
8121
Denys Vlasenko295fef82009-06-03 12:47:26 +02008122#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008123static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02008124{
8125 if (G.func_nest_level == 0) {
8126 bb_error_msg("%s: not in a function", argv[0]);
8127 return EXIT_FAILURE; /* bash compat */
8128 }
8129 helper_export_local(argv, 0, G.func_nest_level);
8130 return EXIT_SUCCESS;
8131}
8132#endif
8133
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008134static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008135{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008136 int sig;
8137 char *new_cmd;
8138
8139 if (!G.traps)
8140 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8141
8142 argv++;
8143 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008144 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008145 /* No args: print all trapped */
8146 for (i = 0; i < NSIG; ++i) {
8147 if (G.traps[i]) {
8148 printf("trap -- ");
8149 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02008150 /* note: bash adds "SIG", but only if invoked
8151 * as "bash". If called as "sh", or if set -o posix,
8152 * then it prints short signal names.
8153 * We are printing short names: */
8154 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008155 }
8156 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008157 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008158 return EXIT_SUCCESS;
8159 }
8160
8161 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008162 /* If first arg is a number: reset all specified signals */
8163 sig = bb_strtou(*argv, NULL, 10);
8164 if (errno == 0) {
8165 int ret;
8166 process_sig_list:
8167 ret = EXIT_SUCCESS;
8168 while (*argv) {
8169 sig = get_signum(*argv++);
8170 if (sig < 0 || sig >= NSIG) {
8171 ret = EXIT_FAILURE;
8172 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008173 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008174 continue;
8175 }
8176
8177 free(G.traps[sig]);
8178 G.traps[sig] = xstrdup(new_cmd);
8179
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01008180 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008181 get_signame(sig), sig, G.traps[sig]);
8182
8183 /* There is no signal for 0 (EXIT) */
8184 if (sig == 0)
8185 continue;
8186
8187 if (new_cmd) {
8188 sigaddset(&G.blocked_set, sig);
8189 } else {
8190 /* There was a trap handler, we are removing it
8191 * (if sig has non-DFL handling,
8192 * we don't need to do anything) */
8193 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
8194 continue;
8195 sigdelset(&G.blocked_set, sig);
8196 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008197 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00008198 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00008199 return ret;
8200 }
8201
8202 if (!argv[1]) { /* no second arg */
8203 bb_error_msg("trap: invalid arguments");
8204 return EXIT_FAILURE;
8205 }
8206
8207 /* First arg is "-": reset all specified to default */
8208 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8209 /* Everything else: set arg as signal handler
8210 * (includes "" case, which ignores signal) */
8211 if (argv[0][0] == '-') {
8212 if (argv[0][1] == '\0') { /* "-" */
8213 /* new_cmd remains NULL: "reset these sigs" */
8214 goto reset_traps;
8215 }
8216 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8217 argv++;
8218 }
8219 /* else: "-something", no special meaning */
8220 }
8221 new_cmd = *argv;
8222 reset_traps:
8223 argv++;
8224 goto process_sig_list;
8225}
8226
Mike Frysinger93cadc22009-05-27 17:06:25 -04008227/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008228static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04008229{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008230 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008231
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008232 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04008233 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02008234 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04008235
8236 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008237 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008238 type = "an alias";*/
8239#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008240 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008241 type = "a function";
8242#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008243 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04008244 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008245 else if ((path = find_in_path(*argv)) != NULL)
8246 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008247 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02008248 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008249 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008250 continue;
8251 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04008252
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02008253 printf("%s is %s\n", *argv, type);
8254 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04008255 }
8256
8257 return ret;
8258}
8259
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008260#if ENABLE_HUSH_JOB
8261/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008262static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008263{
8264 int i, jobnum;
8265 struct pipe *pi;
8266
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008267 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008268 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008269
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008270 /* If they gave us no args, assume they want the last backgrounded task */
8271 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008272 for (pi = G.job_list; pi; pi = pi->next) {
8273 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008274 goto found;
8275 }
8276 }
8277 bb_error_msg("%s: no current job", argv[0]);
8278 return EXIT_FAILURE;
8279 }
8280 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8281 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8282 return EXIT_FAILURE;
8283 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008284 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008285 if (pi->jobid == jobnum) {
8286 goto found;
8287 }
8288 }
8289 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8290 return EXIT_FAILURE;
8291 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008292 /* TODO: bash prints a string representation
8293 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008294 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008295 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008296 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008297 }
8298
8299 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008300 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8301 for (i = 0; i < pi->num_cmds; i++) {
8302 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8303 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008304 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008305 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008306
8307 i = kill(- pi->pgrp, SIGCONT);
8308 if (i < 0) {
8309 if (errno == ESRCH) {
8310 delete_finished_bg_job(pi);
8311 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008312 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008313 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008314 }
8315
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008316 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008317 remove_bg_job(pi);
8318 return checkjobs_and_fg_shell(pi);
8319 }
8320 return EXIT_SUCCESS;
8321}
8322#endif
8323
8324#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008325static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008326{
8327 const struct built_in_command *x;
8328
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008329 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008330 "Built-in commands:\n"
8331 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008332 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008333 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008334 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008335 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008336 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008337 return EXIT_SUCCESS;
8338}
8339#endif
8340
8341#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008342static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008343{
8344 struct pipe *job;
8345 const char *status_string;
8346
Denis Vlasenko87a86552008-07-29 19:43:10 +00008347 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008348 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008349 status_string = "Stopped";
8350 else
8351 status_string = "Running";
8352
8353 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8354 }
8355 return EXIT_SUCCESS;
8356}
8357#endif
8358
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008359#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008360static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008361{
8362 void *p;
8363 unsigned long l;
8364
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008365# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008366 /* Optional. Reduces probability of false positives */
8367 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008368# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008369 /* Crude attempt to find where "free memory" starts,
8370 * sans fragmentation. */
8371 p = malloc(240);
8372 l = (unsigned long)p;
8373 free(p);
8374 p = malloc(3400);
8375 if (l < (unsigned long)p) l = (unsigned long)p;
8376 free(p);
8377
8378 if (!G.memleak_value)
8379 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008380
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008381 l -= G.memleak_value;
8382 if ((long)l < 0)
8383 l = 0;
8384 l /= 1024;
8385 if (l > 127)
8386 l = 127;
8387
8388 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8389 return l;
8390}
8391#endif
8392
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008393static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008394{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008395 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008396 return EXIT_SUCCESS;
8397}
8398
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008399static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008400{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008401 const char *r;
8402 char *opt_n = NULL;
8403 char *opt_p = NULL;
8404 char *opt_t = NULL;
8405 char *opt_u = NULL;
8406 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008407
Denys Vlasenko03dad222010-01-12 23:29:57 +01008408 /* "!": do not abort on errors.
8409 * Option string must start with "sr" to match BUILTIN_READ_xxx
8410 */
8411 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8412 if (read_flags == (uint32_t)-1)
8413 return EXIT_FAILURE;
8414 argv += optind;
8415
8416 r = shell_builtin_read(set_local_var_from_halves,
8417 argv,
8418 get_local_var_value("IFS"), /* can be NULL */
8419 read_flags,
8420 opt_n,
8421 opt_p,
8422 opt_t,
8423 opt_u
8424 );
8425
8426 if ((uintptr_t)r > 1) {
8427 bb_error_msg("%s", r);
8428 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008429 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008430
Denys Vlasenko03dad222010-01-12 23:29:57 +01008431 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008432}
8433
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008434/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8435 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008436 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008437 * set [-abCefhmnuvx] [-o option] [argument...]
8438 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008439 * set -- [argument...]
8440 * set -o
8441 * set +o
8442 * Implementations shall support the options in both their hyphen and
8443 * plus-sign forms. These options can also be specified as options to sh.
8444 * Examples:
8445 * Write out all variables and their values: set
8446 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8447 * Turn on the -x and -v options: set -xv
8448 * Unset all positional parameters: set --
8449 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8450 * Set the positional parameters to the expansion of x, even if x expands
8451 * with a leading '-' or '+': set -- $x
8452 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008453 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008454 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008455static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008456{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008457 int n;
8458 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008459 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008460
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008461 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008462 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008463 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008464 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008465 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008466 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008467
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008468 do {
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008469 if (strcmp(arg, "--") == 0) {
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008470 ++argv;
8471 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008472 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008473 if (arg[0] != '+' && arg[0] != '-')
8474 break;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008475 for (n = 1; arg[n]; ++n) {
8476 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008477 goto error;
Denys Vlasenko6696eac2010-11-14 02:01:50 +01008478 if (arg[n] == 'o' && argv[1])
8479 argv++;
8480 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008481 } while ((arg = *++argv) != NULL);
8482 /* Now argv[0] is 1st argument */
8483
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008484 if (arg == NULL)
8485 return EXIT_SUCCESS;
8486 set_argv:
8487
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008488 /* NB: G.global_argv[0] ($0) is never freed/changed */
8489 g_argv = G.global_argv;
8490 if (G.global_args_malloced) {
8491 pp = g_argv;
8492 while (*++pp)
8493 free(*pp);
8494 g_argv[1] = NULL;
8495 } else {
8496 G.global_args_malloced = 1;
8497 pp = xzalloc(sizeof(pp[0]) * 2);
8498 pp[0] = g_argv[0]; /* retain $0 */
8499 g_argv = pp;
8500 }
8501 /* This realloc's G.global_argv */
8502 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8503
8504 n = 1;
8505 while (*++pp)
8506 n++;
8507 G.global_argc = n;
8508
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008509 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008510
8511 /* Nothing known, so abort */
8512 error:
8513 bb_error_msg("set: %s: invalid option", arg);
8514 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008515}
8516
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008517static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008518{
8519 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008520 argv = skip_dash_dash(argv);
8521 if (argv[0]) {
8522 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008523 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008524 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008525 if (G.global_args_malloced) {
8526 int m = 1;
8527 while (m <= n)
8528 free(G.global_argv[m++]);
8529 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008530 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008531 memmove(&G.global_argv[1], &G.global_argv[n+1],
8532 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008533 return EXIT_SUCCESS;
8534 }
8535 return EXIT_FAILURE;
8536}
8537
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008538static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008539{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008540 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008541 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008542 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008543#if ENABLE_HUSH_FUNCTIONS
8544 smallint sv_flg;
8545#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008546
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008547 argv = skip_dash_dash(argv);
8548 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008549 if (!filename) {
8550 /* bash says: "bash: .: filename argument required" */
8551 return 2; /* bash compat */
8552 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008553 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008554 if (!strchr(filename, '/')) {
8555 arg_path = find_in_path(filename);
8556 if (arg_path)
8557 filename = arg_path;
8558 }
8559 input = fopen_or_warn(filename, "r");
8560 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008561 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008562 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008563 return EXIT_FAILURE;
8564 }
8565 close_on_exec_on(fileno(input));
8566
Mike Frysinger885b6f22009-04-18 21:04:25 +00008567#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008568 sv_flg = G.flag_return_in_progress;
8569 /* "we are inside sourced file, ok to use return" */
8570 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008571#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008572 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008573
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008574 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008575 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008576
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008577 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008578#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008579 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008580#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008581
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008582 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008583}
8584
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008585static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008586{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008587 int rc;
8588 mode_t mask;
8589
8590 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008591 argv = skip_dash_dash(argv);
8592 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008593 mode_t old_mask = mask;
8594
8595 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008596 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008597 mask ^= 0777;
8598 if (rc == 0) {
8599 mask = old_mask;
8600 /* bash messages:
8601 * bash: umask: 'q': invalid symbolic mode operator
8602 * bash: umask: 999: octal number out of range
8603 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008604 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008605 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008606 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008607 rc = 1;
8608 /* Mimic bash */
8609 printf("%04o\n", (unsigned) mask);
8610 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008611 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008612 umask(mask);
8613
8614 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008615}
8616
Mike Frysingerd690f682009-03-30 06:50:54 +00008617/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008618static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008619{
Mike Frysingerd690f682009-03-30 06:50:54 +00008620 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008621 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008622
Denis Vlasenko28e67962009-04-26 23:22:40 +00008623 /* "!": do not abort on errors */
8624 /* "+": stop at 1st non-option */
8625 opts = getopt32(argv, "!+vf");
8626 if (opts == (unsigned)-1)
8627 return EXIT_FAILURE;
8628 if (opts == 3) {
8629 bb_error_msg("unset: -v and -f are exclusive");
8630 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008631 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008632 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008633
8634 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008635 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008636 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008637 if (unset_local_var(*argv)) {
8638 /* unset <nonexistent_var> doesn't fail.
8639 * Error is when one tries to unset RO var.
8640 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008641 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008642 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008643 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008644#if ENABLE_HUSH_FUNCTIONS
8645 else {
8646 unset_func(*argv);
8647 }
8648#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008649 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008650 }
8651 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008652}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008653
Mike Frysinger56bdea12009-03-28 20:01:58 +00008654/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008655static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008656{
8657 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008658 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008659
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008660 argv = skip_dash_dash(argv);
8661 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008662 /* Don't care about wait results */
8663 /* Note 1: must wait until there are no more children */
8664 /* Note 2: must be interruptible */
8665 /* Examples:
8666 * $ sleep 3 & sleep 6 & wait
8667 * [1] 30934 sleep 3
8668 * [2] 30935 sleep 6
8669 * [1] Done sleep 3
8670 * [2] Done sleep 6
8671 * $ sleep 3 & sleep 6 & wait
8672 * [1] 30936 sleep 3
8673 * [2] 30937 sleep 6
8674 * [1] Done sleep 3
8675 * ^C <-- after ~4 sec from keyboard
8676 * $
8677 */
8678 sigaddset(&G.blocked_set, SIGCHLD);
8679 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8680 while (1) {
8681 checkjobs(NULL);
8682 if (errno == ECHILD)
8683 break;
8684 /* Wait for SIGCHLD or any other signal of interest */
8685 /* sigtimedwait with infinite timeout: */
8686 sig = sigwaitinfo(&G.blocked_set, NULL);
8687 if (sig > 0) {
8688 sig = check_and_run_traps(sig);
8689 if (sig && sig != SIGCHLD) { /* see note 2 */
8690 ret = 128 + sig;
8691 break;
8692 }
8693 }
8694 }
8695 sigdelset(&G.blocked_set, SIGCHLD);
8696 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8697 return ret;
8698 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008699
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008700 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008701 while (*argv) {
8702 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008703 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008704 /* mimic bash message */
8705 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008706 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008707 }
8708 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008709 if (WIFSIGNALED(status))
8710 ret = 128 + WTERMSIG(status);
8711 else if (WIFEXITED(status))
8712 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008713 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008714 ret = EXIT_FAILURE;
8715 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008716 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008717 ret = 127;
8718 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008719 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008720 }
8721
8722 return ret;
8723}
8724
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008725#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8726static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8727{
8728 if (argv[1]) {
8729 def = bb_strtou(argv[1], NULL, 10);
8730 if (errno || def < def_min || argv[2]) {
8731 bb_error_msg("%s: bad arguments", argv[0]);
8732 def = UINT_MAX;
8733 }
8734 }
8735 return def;
8736}
8737#endif
8738
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008739#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008740static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008741{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008742 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008743 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008744 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008745 return EXIT_SUCCESS; /* bash compat */
8746 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008747 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008748
8749 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8750 if (depth == UINT_MAX)
8751 G.flag_break_continue = BC_BREAK;
8752 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008753 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008754
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008755 return EXIT_SUCCESS;
8756}
8757
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008758static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008759{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008760 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8761 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008762}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008763#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008764
8765#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008766static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008767{
8768 int rc;
8769
8770 if (G.flag_return_in_progress != -1) {
8771 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8772 return EXIT_FAILURE; /* bash compat */
8773 }
8774
8775 G.flag_return_in_progress = 1;
8776
8777 /* bash:
8778 * out of range: wraps around at 256, does not error out
8779 * non-numeric param:
8780 * f() { false; return qwe; }; f; echo $?
8781 * bash: return: qwe: numeric argument required <== we do this
8782 * 255 <== we also do this
8783 */
8784 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8785 return rc;
8786}
8787#endif