blob: d3dab586314032279f01366f6a8b83202a4b2f72 [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 *
11 * Credits:
12 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000013 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000016 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000017 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
21 * rewrites.
22 *
Eric Andersen25f27032001-04-26 23:22:31 +000023 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000024 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000025 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000026 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000028 *
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
39 *
Denys Vlasenko349ef962010-05-21 15:46:24 +020040 * TODOs:
41 * grep for "TODO" and fix (some of them are easy)
42 * special variables (done: PWD, PPID, RANDOM)
43 * tilde expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000044 * aliases
Denys Vlasenko349ef962010-05-21 15:46:24 +020045 * follow IFS rules more precisely, including update semantics
46 * builtins mandated by standards we don't support:
47 * [un]alias, command, fc, getopts, newgrp, readonly, times
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +020048 * make complex ${var%...} constructs support optional
49 * make here documents optional
Mike Frysinger25a6ca02009-03-28 13:59:26 +000050 *
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020051 * Bash compat TODO:
52 * redirection of stdout+stderr: &> and >&
Denys Vlasenko2e48d532010-05-22 17:30:39 +020053 * subst operator: ${var/[/]expr/expr}
Denys Vlasenkoadc0e202010-05-17 18:56:58 +020054 * brace expansion: one/{two,three,four}
55 * 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 Vlasenko08218012009-06-03 14:43:56 +020067 * export builtin should be special, its arguments are assignments
68 * and therefore expansion of them should be "one-word" expansion:
69 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
70 * compare with:
71 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
72 * ls: cannot access i=a: No such file or directory
73 * ls: cannot access b: No such file or directory
Denys Vlasenko9ca656b2009-06-10 13:39:35 +020074 * Note1: same applies to local builtin.
Denys Vlasenko08218012009-06-03 14:43:56 +020075 * Note2: bash 3.2.33(1) does this only if export word itself
76 * is not quoted:
77 * $ export i=`echo 'aaa bbb'`; echo "$i"
78 * aaa bbb
79 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
80 * aaa
Eric Andersen25f27032001-04-26 23:22:31 +000081 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +020082 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
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))
106//applet:IF_LASH(APPLET(lash, _BB_DIR_BIN, _BB_SUID_DROP))
107//applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, _BB_DIR_BIN, _BB_SUID_DROP, sh))
108//applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, _BB_DIR_BIN, _BB_SUID_DROP, bash))
109
110//kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
111//kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
112
113//config:config HUSH
114//config: bool "hush"
115//config: default y
116//config: help
Denys Vlasenko771f1992010-07-16 14:31:34 +0200117//config: hush is a small shell (25k). It handles the normal flow control
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200118//config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119//config: case/esac. Redirections, here documents, $((arithmetic))
120//config: and functions are supported.
121//config:
122//config: It will compile and work on no-mmu systems.
123//config:
124//config: It does not handle select, aliases, brace expansion,
125//config: tilde expansion, &>file and >&file redirection of stdout+stderr.
126//config:
127//config:config HUSH_BASH_COMPAT
128//config: bool "bash-compatible extensions"
129//config: default y
130//config: depends on HUSH
131//config: help
132//config: Enable bash-compatible extensions.
133//config:
134//config:config HUSH_HELP
135//config: bool "help builtin"
136//config: default y
137//config: depends on HUSH
138//config: help
139//config: Enable help builtin in hush. Code size + ~1 kbyte.
140//config:
141//config:config HUSH_INTERACTIVE
142//config: bool "Interactive mode"
143//config: default y
144//config: depends on HUSH
145//config: help
146//config: Enable interactive mode (prompt and command editing).
147//config: Without this, hush simply reads and executes commands
148//config: from stdin just like a shell script from a file.
149//config: No prompt, no PS1/PS2 magic shell variables.
150//config:
151//config:config HUSH_JOB
152//config: bool "Job control"
153//config: default y
154//config: depends on HUSH_INTERACTIVE
155//config: help
156//config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
157//config: command (not entire shell), fg/bg builtins work. Without this option,
158//config: "cmd &" still works by simply spawning a process and immediately
159//config: prompting for next command (or executing next command in a script),
160//config: but no separate process group is formed.
161//config:
162//config:config HUSH_TICK
163//config: bool "Process substitution"
164//config: default y
165//config: depends on HUSH
166//config: help
167//config: Enable process substitution `command` and $(command) in hush.
168//config:
169//config:config HUSH_IF
170//config: bool "Support if/then/elif/else/fi"
171//config: default y
172//config: depends on HUSH
173//config: help
174//config: Enable if/then/elif/else/fi in hush.
175//config:
176//config:config HUSH_LOOPS
177//config: bool "Support for, while and until loops"
178//config: default y
179//config: depends on HUSH
180//config: help
181//config: Enable for, while and until loops in hush.
182//config:
183//config:config HUSH_CASE
184//config: bool "Support case ... esac statement"
185//config: default y
186//config: depends on HUSH
187//config: help
188//config: Enable case ... esac statement in hush. +400 bytes.
189//config:
190//config:config HUSH_FUNCTIONS
191//config: bool "Support funcname() { commands; } syntax"
192//config: default y
193//config: depends on HUSH
194//config: help
195//config: Enable support for shell functions in hush. +800 bytes.
196//config:
197//config:config HUSH_LOCAL
198//config: bool "Support local builtin"
199//config: default y
200//config: depends on HUSH_FUNCTIONS
201//config: help
202//config: Enable support for local variables in functions.
203//config:
204//config:config HUSH_RANDOM_SUPPORT
205//config: bool "Pseudorandom generator and $RANDOM variable"
206//config: default y
207//config: depends on HUSH
208//config: help
209//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
210//config: Each read of "$RANDOM" will generate a new pseudorandom value.
211//config:
212//config:config HUSH_EXPORT_N
213//config: bool "Support 'export -n' option"
214//config: default y
215//config: depends on HUSH
216//config: help
217//config: export -n unexports variables. It is a bash extension.
218//config:
219//config:config HUSH_MODE_X
220//config: bool "Support 'hush -x' option and 'set -x' command"
221//config: default y
222//config: depends on HUSH
223//config: help
Denys Vlasenko29082232010-07-16 13:52:32 +0200224//config: This instructs hush to print commands before execution.
225//config: Adds ~300 bytes.
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200226//config:
Denys Vlasenko6adf2aa2010-07-16 19:26:38 +0200227//config:config LASH
228//config: bool "lash (deprecated: aliased to hush)"
229//config: default n
230//config: select HUSH
231//config: help
232//config: lash is deprecated and will be removed, please migrate to hush.
233//config:
234//config:config MSH
235//config: bool "msh (deprecated: aliased to hush)"
236//config: default n
237//config: select HUSH
238//config: help
239//config: msh is deprecated and will be removed, please migrate to hush.
240//config:
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200241
242//usage:#define hush_trivial_usage NOUSAGE_STR
243//usage:#define hush_full_usage ""
244//usage:#define lash_trivial_usage NOUSAGE_STR
245//usage:#define lash_full_usage ""
246//usage:#define msh_trivial_usage NOUSAGE_STR
247//usage:#define msh_full_usage ""
248
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000249
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200250/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000251#define LEAK_HUNTING 0
252#define BUILD_AS_NOMMU 0
253/* Enable/disable sanity checks. Ok to enable in production,
254 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
255 * Keeping 1 for now even in released versions.
256 */
257#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200258/* Slightly bigger (+200 bytes), but faster hush.
259 * So far it only enables a trick with counting SIGCHLDs and forks,
260 * which allows us to do fewer waitpid's.
261 * (we can detect a case where neither forks were done nor SIGCHLDs happened
262 * and therefore waitpid will return the same result as last time)
263 */
264#define ENABLE_HUSH_FAST 0
Denys Vlasenko9297dbc2010-07-05 21:37:12 +0200265/* TODO: implement simplified code for users which do not need ${var%...} ops
266 * So far ${var%...} ops are always enabled:
267 */
268#define ENABLE_HUSH_DOLLAR_OPS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000269
270
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000271#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000272# undef BB_MMU
273# undef USE_FOR_NOMMU
274# undef USE_FOR_MMU
275# define BB_MMU 0
276# define USE_FOR_NOMMU(...) __VA_ARGS__
277# define USE_FOR_MMU(...)
278#endif
279
Denys Vlasenko1fcbff22010-06-26 02:40:08 +0200280#include "NUM_APPLETS.h"
Denys Vlasenko14974842010-03-23 01:08:26 +0100281#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +0000282/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000283# undef CONFIG_FEATURE_SH_STANDALONE
284# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000285# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +0100286# undef IF_NOT_FEATURE_SH_STANDALONE
287# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000288# define IF_FEATURE_SH_STANDALONE(...)
289# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000290#endif
291
Denis Vlasenko05743d72008-02-10 12:10:08 +0000292#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000293# undef ENABLE_FEATURE_EDITING
294# define ENABLE_FEATURE_EDITING 0
295# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
296# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000297#endif
298
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000299/* Do we support ANY keywords? */
300#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000301# define HAS_KEYWORDS 1
302# define IF_HAS_KEYWORDS(...) __VA_ARGS__
303# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000304#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000305# define HAS_KEYWORDS 0
306# define IF_HAS_KEYWORDS(...)
307# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000308#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000309
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000310/* If you comment out one of these below, it will be #defined later
311 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000312#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000313/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000314#define debug_printf_parse(...) do {} while (0)
315#define debug_print_tree(a, b) do {} while (0)
316#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000317#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000318#define debug_printf_jobs(...) do {} while (0)
319#define debug_printf_expand(...) do {} while (0)
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200320#define debug_printf_varexp(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000321#define debug_printf_glob(...) do {} while (0)
322#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000323#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000324#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000325
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000326#define ERR_PTR ((void*)(long)1)
327
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200328#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000329
Denys Vlasenkoe85248a2010-05-22 06:20:26 +0200330#define _SPECIAL_VARS_STR "_*@$!?#"
331#define SPECIAL_VARS_STR ("_*@$!?#" + 1)
332#define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
333
334#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000335
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200336struct variable;
337
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000338static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
339
340/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000341 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000342 */
343#if !BB_MMU
344typedef struct nommu_save_t {
345 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200346 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000347 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000348 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000349} nommu_save_t;
350#endif
351
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000352typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000353 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000354#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000355 RES_IF ,
356 RES_THEN ,
357 RES_ELIF ,
358 RES_ELSE ,
359 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000360#endif
361#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000362 RES_FOR ,
363 RES_WHILE ,
364 RES_UNTIL ,
365 RES_DO ,
366 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000367#endif
368#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000369 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000370#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000371#if ENABLE_HUSH_CASE
372 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200373 /* three pseudo-keywords support contrived "case" syntax: */
374 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
375 RES_MATCH , /* "word)" */
376 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000377 RES_ESAC ,
378#endif
379 RES_XXXX ,
380 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000381} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000382
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000383typedef struct o_string {
384 char *data;
385 int length; /* position where data is appended */
386 int maxlen;
387 /* Protect newly added chars against globbing
388 * (by prepending \ to *, ?, [, \) */
389 smallint o_escape;
390 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000391 /* At least some part of the string was inside '' or "",
392 * possibly empty one: word"", wo''rd etc. */
Denys Vlasenkoe298ce62010-09-04 19:52:44 +0200393//TODO: rename to no_empty_expansion?
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000394 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000395 smallint has_empty_slot;
396 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
397} o_string;
398enum {
399 MAYBE_ASSIGNMENT = 0,
400 DEFINITELY_ASSIGNMENT = 1,
401 NOT_ASSIGNMENT = 2,
402 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
403};
404/* Used for initialization: o_string foo = NULL_O_STRING; */
405#define NULL_O_STRING { NULL }
406
407/* I can almost use ordinary FILE*. Is open_memstream() universally
408 * available? Where is it documented? */
409typedef struct in_str {
410 const char *p;
411 /* eof_flag=1: last char in ->p is really an EOF */
412 char eof_flag; /* meaningless if ->p == NULL */
413 char peek_buf[2];
414#if ENABLE_HUSH_INTERACTIVE
415 smallint promptme;
416 smallint promptmode; /* 0: PS1, 1: PS2 */
417#endif
418 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200419 int (*get) (struct in_str *) FAST_FUNC;
420 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000421} in_str;
422#define i_getch(input) ((input)->get(input))
423#define i_peek(input) ((input)->peek(input))
424
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200425/* The descrip member of this structure is only used to make
426 * debugging output pretty */
427static const struct {
428 int mode;
429 signed char default_fd;
430 char descrip[3];
431} redir_table[] = {
432 { O_RDONLY, 0, "<" },
433 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
434 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
435 { O_CREAT|O_RDWR, 1, "<>" },
436 { O_RDONLY, 0, "<<" },
437/* Should not be needed. Bogus default_fd helps in debugging */
438/* { O_RDONLY, 77, "<<" }, */
439};
440
Eric Andersen25f27032001-04-26 23:22:31 +0000441struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000442 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000443 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000444 int rd_fd; /* fd to redirect */
445 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
446 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000447 smallint rd_type; /* (enum redir_type) */
448 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000449 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200450 * bit 0: do we need to trim leading tabs?
451 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000452 */
Eric Andersen25f27032001-04-26 23:22:31 +0000453};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000454typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200455 REDIRECT_INPUT = 0,
456 REDIRECT_OVERWRITE = 1,
457 REDIRECT_APPEND = 2,
458 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000459 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200460 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000461
462 REDIRFD_CLOSE = -3,
463 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000464 REDIRFD_TO_FILE = -1,
465 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000466
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000467 HEREDOC_SKIPTABS = 1,
468 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000469} redir_type;
470
Eric Andersen25f27032001-04-26 23:22:31 +0000471
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000472struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000473 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000474 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000475 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200476 smallint cmd_type; /* CMD_xxx */
477#define CMD_NORMAL 0
478#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200479
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200480/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200481#if ENABLE_HUSH_BASH_COMPAT
482# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000483#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200484
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200485/* used for "export noglob=* glob* a=`echo a b`" */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +0200486//#define CMD_SINGLEWORD_NOGLOB_COND 3
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200487// It is hard to implement correctly, it adds significant amounts of tricky code,
488// and all this is only useful for really obscure export statements
489// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
490// guards the code which implements it, but I have doubts it works
491// in all cases (especially with mixed globbed/non-globbed arguments)
492
493#if ENABLE_HUSH_FUNCTIONS
494# define CMD_FUNCDEF 3
495#endif
496
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200497 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
498 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000499#if !BB_MMU
500 char *group_as_string;
501#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000502#if ENABLE_HUSH_FUNCTIONS
503 struct function *child_func;
504/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200505 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000506 * When we execute "f1() {a;}" cmd, we create new function and clear
507 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200508 * When we execute "f1() {b;}", we notice that f1 exists,
509 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000510 * we put those fields back into cmd->xxx
511 * (struct function has ->parent_cmd ptr to facilitate that).
512 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
513 * Without this trick, loop would execute a;b;b;b;...
514 * instead of correct sequence a;b;a;b;...
515 * When command is freed, it severs the link
516 * (sets ->child_func->parent_cmd to NULL).
517 */
518#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000519 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000520/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
521 * and on execution these are substituted with their values.
522 * Substitution can make _several_ words out of one argv[n]!
523 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000524 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000525 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000526 struct redir_struct *redirects; /* I/O redirections */
527};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000528/* Is there anything in this command at all? */
529#define IS_NULL_CMD(cmd) \
530 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
531
Eric Andersen25f27032001-04-26 23:22:31 +0000532
533struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000534 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000535 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000536 int alive_cmds; /* number of commands running (not exited) */
537 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000538#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000539 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000540 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000541 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000542#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000543 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000544 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000545 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
546 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000547};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000548typedef enum pipe_style {
549 PIPE_SEQ = 1,
550 PIPE_AND = 2,
551 PIPE_OR = 3,
552 PIPE_BG = 4,
553} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000554/* Is there anything in this pipe at all? */
555#define IS_NULL_PIPE(pi) \
556 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000557
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000558/* This holds pointers to the various results of parsing */
559struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000560 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000561 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000562 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000563 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000564 /* last command in pipe (being constructed right now) */
565 struct command *command;
566 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000567 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000568#if !BB_MMU
569 o_string as_string;
570#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000571#if HAS_KEYWORDS
572 smallint ctx_res_w;
573 smallint ctx_inverted; /* "! cmd | cmd" */
574#if ENABLE_HUSH_CASE
575 smallint ctx_dsemicolon; /* ";;" seen */
576#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000577 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
578 int old_flag;
579 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000580 * example: "if pipe1; pipe2; then pipe3; fi"
581 * when we see "if" or "then", we malloc and copy current context,
582 * and make ->stack point to it. then we parse pipeN.
583 * when closing "then" / fi" / whatever is found,
584 * we move list_head into ->stack->command->group,
585 * copy ->stack into current context, and delete ->stack.
586 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000587 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000588 struct parse_context *stack;
589#endif
590};
591
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000592/* On program start, environ points to initial environment.
593 * putenv adds new pointers into it, unsetenv removes them.
594 * Neither of these (de)allocates the strings.
595 * setenv allocates new strings in malloc space and does putenv,
596 * and thus setenv is unusable (leaky) for shell's purposes */
597#define setenv(...) setenv_is_leaky_dont_use()
598struct variable {
599 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000600 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200601#if ENABLE_HUSH_LOCAL
602 unsigned func_nest_level;
603#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000604 int max_len; /* if > 0, name is part of initial env; else name is malloced */
605 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000606 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000607};
608
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000609enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000610 BC_BREAK = 1,
611 BC_CONTINUE = 2,
612};
613
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000614#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000615struct function {
616 struct function *next;
617 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000618 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000619 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200620# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000621 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200622# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000623};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000624#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000625
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000626
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000627/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000628/* Sorted roughly by size (smaller offsets == smaller code) */
629struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000630 /* interactive_fd != 0 means we are an interactive shell.
631 * If we are, then saved_tty_pgrp can also be != 0, meaning
632 * that controlling tty is available. With saved_tty_pgrp == 0,
633 * job control still works, but terminal signals
634 * (^C, ^Z, ^Y, ^\) won't work at all, and background
635 * process groups can only be created with "cmd &".
636 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
637 * to give tty to the foreground process group,
638 * and will take it back when the group is stopped (^Z)
639 * or killed (^C).
640 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000641#if ENABLE_HUSH_INTERACTIVE
642 /* 'interactive_fd' is a fd# open to ctty, if we have one
643 * _AND_ if we decided to act interactively */
644 int interactive_fd;
645 const char *PS1;
646 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000647# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000648#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000649# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000650#endif
651#if ENABLE_FEATURE_EDITING
652 line_input_t *line_input_state;
653#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000654 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200655 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000656 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200657#if ENABLE_HUSH_RANDOM_SUPPORT
658 random_t random_gen;
659#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000660#if ENABLE_HUSH_JOB
661 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000662 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000663 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000664 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400665# define G_saved_tty_pgrp (G.saved_tty_pgrp)
666#else
667# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000668#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000669 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000670#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000671 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000672#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000673#if ENABLE_HUSH_FUNCTIONS
674 /* 0: outside of a function (or sourced file)
675 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000676 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000677 */
678 smallint flag_return_in_progress;
679#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200680 smallint n_mode;
681#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +0200682 smallint x_mode;
Denys Vlasenko29082232010-07-16 13:52:32 +0200683# define G_x_mode (G.x_mode)
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200684#else
685# define G_x_mode 0
686#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000687 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000688 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000689 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000690 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000691 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100692 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000693 /* how many non-NULL argv's we have. NB: $# + 1 */
694 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000695 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000696#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000697 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000698#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000699#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000700 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000701 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000702#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000703 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000704 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000705 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000706 struct variable shell_ver;
Denys Vlasenko29082232010-07-16 13:52:32 +0200707 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000708#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000709 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200710# if ENABLE_HUSH_LOCAL
711 struct variable **shadowed_vars_pp;
712 unsigned func_nest_level;
713# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000714#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000715 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200716#if ENABLE_HUSH_FAST
717 unsigned count_SIGCHLD;
718 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200719 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200720#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000721 /* which signals have non-DFL handler (even with no traps set)? */
722 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000723 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000724 sigset_t blocked_set;
725 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000726#if HUSH_DEBUG
727 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000728 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000729#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200730 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000731};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000732#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000733/* Not #defining name to G.name - this quickly gets unwieldy
734 * (too many defines). Also, I actually prefer to see when a variable
735 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000736#define INIT_G() do { \
737 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
738} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000739
740
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000741/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200742static int builtin_cd(char **argv) FAST_FUNC;
743static int builtin_echo(char **argv) FAST_FUNC;
744static int builtin_eval(char **argv) FAST_FUNC;
745static int builtin_exec(char **argv) FAST_FUNC;
746static int builtin_exit(char **argv) FAST_FUNC;
747static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000748#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200749static int builtin_fg_bg(char **argv) FAST_FUNC;
750static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000751#endif
752#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200753static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000754#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200755#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200756static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200757#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000758#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200759static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000760#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400761#if ENABLE_PRINTF
762static int builtin_printf(char **argv) FAST_FUNC;
763#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200764static int builtin_pwd(char **argv) FAST_FUNC;
765static int builtin_read(char **argv) FAST_FUNC;
766static int builtin_set(char **argv) FAST_FUNC;
767static int builtin_shift(char **argv) FAST_FUNC;
768static int builtin_source(char **argv) FAST_FUNC;
769static int builtin_test(char **argv) FAST_FUNC;
770static int builtin_trap(char **argv) FAST_FUNC;
771static int builtin_type(char **argv) FAST_FUNC;
772static int builtin_true(char **argv) FAST_FUNC;
773static int builtin_umask(char **argv) FAST_FUNC;
774static int builtin_unset(char **argv) FAST_FUNC;
775static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000776#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200777static int builtin_break(char **argv) FAST_FUNC;
778static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000779#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000780#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200781static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000782#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000783
784/* Table of built-in functions. They can be forked or not, depending on
785 * context: within pipes, they fork. As simple commands, they do not.
786 * When used in non-forking context, they can change global variables
787 * in the parent shell process. If forked, of course they cannot.
788 * For example, 'unset foo | whatever' will parse and run, but foo will
789 * still be set at the end. */
790struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100791 const char *b_cmd;
792 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000793#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100794 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200795# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000796#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200797# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000798#endif
799};
800
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200801static const struct built_in_command bltins1[] = {
802 BLTIN("." , builtin_source , "Run commands in a file"),
803 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000804#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200805 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000806#endif
807#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200808 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000809#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200810 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000811#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200812 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000813#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200814 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
815 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
816 BLTIN("exit" , builtin_exit , "Exit"),
817 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000818#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200819 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000820#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000821#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200822 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000823#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000824#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200825 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000826#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200827#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200828 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200829#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000830#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200831 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000832#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200833 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000834#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200835 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000836#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200837 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
838 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200839#if ENABLE_HUSH_BASH_COMPAT
840 BLTIN("source" , builtin_source , "Run commands in a file"),
841#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200842 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100843 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100844 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200845 BLTIN("umask" , builtin_umask , "Set file creation mask"),
846 BLTIN("unset" , builtin_unset , "Unset variables"),
847 BLTIN("wait" , builtin_wait , "Wait for process"),
848};
849/* For now, echo and test are unconditionally enabled.
850 * Maybe make it configurable? */
851static const struct built_in_command bltins2[] = {
852 BLTIN("[" , builtin_test , NULL),
853 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400854#if ENABLE_PRINTF
855 BLTIN("printf" , builtin_printf , NULL),
856#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200857 BLTIN("pwd" , builtin_pwd , NULL),
858 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000859};
860
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000861
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000862/* Debug printouts.
863 */
864#if HUSH_DEBUG
865/* prevent disasters with G.debug_indent < 0 */
866# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
867# define debug_enter() (G.debug_indent++)
868# define debug_leave() (G.debug_indent--)
869#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200870# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000871# define debug_enter() ((void)0)
872# define debug_leave() ((void)0)
873#endif
874
875#ifndef debug_printf
876# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
877#endif
878
879#ifndef debug_printf_parse
880# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
881#endif
882
883#ifndef debug_printf_exec
884#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
885#endif
886
887#ifndef debug_printf_env
888# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
889#endif
890
891#ifndef debug_printf_jobs
892# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
893# define DEBUG_JOBS 1
894#else
895# define DEBUG_JOBS 0
896#endif
897
898#ifndef debug_printf_expand
899# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
900# define DEBUG_EXPAND 1
901#else
902# define DEBUG_EXPAND 0
903#endif
904
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200905#ifndef debug_printf_varexp
906# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
907#endif
908
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000909#ifndef debug_printf_glob
910# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
911# define DEBUG_GLOB 1
912#else
913# define DEBUG_GLOB 0
914#endif
915
916#ifndef debug_printf_list
917# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
918#endif
919
920#ifndef debug_printf_subst
921# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
922#endif
923
924#ifndef debug_printf_clean
925# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
926# define DEBUG_CLEAN 1
927#else
928# define DEBUG_CLEAN 0
929#endif
930
931#if DEBUG_EXPAND
932static void debug_print_strings(const char *prefix, char **vv)
933{
934 indent();
935 fprintf(stderr, "%s:\n", prefix);
936 while (*vv)
937 fprintf(stderr, " '%s'\n", *vv++);
938}
939#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200940# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000941#endif
942
943
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000944/* Leak hunting. Use hush_leaktool.sh for post-processing.
945 */
946#if LEAK_HUNTING
947static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000948{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000949 void *ptr = xmalloc((size + 0xff) & ~0xff);
950 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
951 return ptr;
952}
953static void *xxrealloc(int lineno, void *ptr, size_t size)
954{
955 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
956 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
957 return ptr;
958}
959static char *xxstrdup(int lineno, const char *str)
960{
961 char *ptr = xstrdup(str);
962 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
963 return ptr;
964}
965static void xxfree(void *ptr)
966{
967 fdprintf(2, "free %p\n", ptr);
968 free(ptr);
969}
Denys Vlasenko8391c482010-05-22 17:50:43 +0200970# define xmalloc(s) xxmalloc(__LINE__, s)
971# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
972# define xstrdup(s) xxstrdup(__LINE__, s)
973# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000974#endif
975
976
977/* Syntax and runtime errors. They always abort scripts.
978 * In interactive use they usually discard unparsed and/or unexecuted commands
979 * and return to the prompt.
980 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
981 */
982#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200983# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000984# define syntax_error(lineno, msg) syntax_error(msg)
985# define syntax_error_at(lineno, msg) syntax_error_at(msg)
986# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
987# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
988# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000989#endif
990
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000991static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000992{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000993 va_list p;
994
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000995#if HUSH_DEBUG >= 2
996 bb_error_msg("hush.c:%u", lineno);
997#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000998 va_start(p, fmt);
999 bb_verror_msg(fmt, p, NULL);
1000 va_end(p);
1001 if (!G_interactive_fd)
1002 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001003}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001004
1005static void syntax_error(unsigned lineno, const char *msg)
1006{
1007 if (msg)
1008 die_if_script(lineno, "syntax error: %s", msg);
1009 else
1010 die_if_script(lineno, "syntax error", NULL);
1011}
1012
1013static void syntax_error_at(unsigned lineno, const char *msg)
1014{
1015 die_if_script(lineno, "syntax error at '%s'", msg);
1016}
1017
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001018static void syntax_error_unterm_str(unsigned lineno, const char *s)
1019{
1020 die_if_script(lineno, "syntax error: unterminated %s", s);
1021}
1022
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001023/* It so happens that all such cases are totally fatal
1024 * even if shell is interactive: EOF while looking for closing
1025 * delimiter. There is nowhere to read stuff from after that,
1026 * it's EOF! The only choice is to terminate.
1027 */
1028static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001029static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001030{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001031 char msg[2] = { ch, '\0' };
1032 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001033 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001034}
1035
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001036static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001037{
1038 char msg[2];
1039 msg[0] = ch;
1040 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001041 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001042}
1043
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001044#if HUSH_DEBUG < 2
1045# undef die_if_script
1046# undef syntax_error
1047# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001048# undef syntax_error_unterm_ch
1049# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001050# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001051#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001052# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001053# define syntax_error(msg) syntax_error(__LINE__, msg)
1054# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1055# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1056# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1057# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001058#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001059
Denis Vlasenko552433b2009-04-04 19:29:21 +00001060
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001061#if ENABLE_HUSH_INTERACTIVE
1062static void cmdedit_update_prompt(void);
1063#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001064# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001065#endif
1066
1067
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001068/* Utility functions
1069 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001070/* Replace each \x with x in place, return ptr past NUL. */
1071static char *unbackslash(char *src)
1072{
Denys Vlasenko71885402009-09-24 01:44:13 +02001073 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001074 while (1) {
1075 if (*src == '\\')
1076 src++;
1077 if ((*dst++ = *src++) == '\0')
1078 break;
1079 }
1080 return dst;
1081}
1082
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001083static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001084{
1085 int i;
1086 unsigned count1;
1087 unsigned count2;
1088 char **v;
1089
1090 v = strings;
1091 count1 = 0;
1092 if (v) {
1093 while (*v) {
1094 count1++;
1095 v++;
1096 }
1097 }
1098 count2 = 0;
1099 v = add;
1100 while (*v) {
1101 count2++;
1102 v++;
1103 }
1104 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1105 v[count1 + count2] = NULL;
1106 i = count2;
1107 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001108 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001109 return v;
1110}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001111#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001112static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1113{
1114 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1115 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1116 return ptr;
1117}
1118#define add_strings_to_strings(strings, add, need_to_dup) \
1119 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1120#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001121
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001122/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001123static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001124{
1125 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001126 v[0] = add;
1127 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001128 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001129}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001130#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001131static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1132{
1133 char **ptr = add_string_to_strings(strings, add);
1134 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1135 return ptr;
1136}
1137#define add_string_to_strings(strings, add) \
1138 xx_add_string_to_strings(__LINE__, strings, add)
1139#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001140
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001141static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001142{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001143 char **v;
1144
1145 if (!strings)
1146 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001147 v = strings;
1148 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001149 free(*v);
1150 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001151 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001152 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001153}
1154
Denis Vlasenko76d50412008-06-10 16:19:39 +00001155
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001156/* Helpers for setting new $n and restoring them back
1157 */
1158typedef struct save_arg_t {
1159 char *sv_argv0;
1160 char **sv_g_argv;
1161 int sv_g_argc;
1162 smallint sv_g_malloced;
1163} save_arg_t;
1164
1165static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1166{
1167 int n;
1168
1169 sv->sv_argv0 = argv[0];
1170 sv->sv_g_argv = G.global_argv;
1171 sv->sv_g_argc = G.global_argc;
1172 sv->sv_g_malloced = G.global_args_malloced;
1173
1174 argv[0] = G.global_argv[0]; /* retain $0 */
1175 G.global_argv = argv;
1176 G.global_args_malloced = 0;
1177
1178 n = 1;
1179 while (*++argv)
1180 n++;
1181 G.global_argc = n;
1182}
1183
1184static void restore_G_args(save_arg_t *sv, char **argv)
1185{
1186 char **pp;
1187
1188 if (G.global_args_malloced) {
1189 /* someone ran "set -- arg1 arg2 ...", undo */
1190 pp = G.global_argv;
1191 while (*++pp) /* note: does not free $0 */
1192 free(*pp);
1193 free(G.global_argv);
1194 }
1195 argv[0] = sv->sv_argv0;
1196 G.global_argv = sv->sv_g_argv;
1197 G.global_argc = sv->sv_g_argc;
1198 G.global_args_malloced = sv->sv_g_malloced;
1199}
1200
1201
Denis Vlasenkod5762932009-03-31 11:22:57 +00001202/* Basic theory of signal handling in shell
1203 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001204 * This does not describe what hush does, rather, it is current understanding
1205 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001206 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1207 *
1208 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1209 * is finished or backgrounded. It is the same in interactive and
1210 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001211 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001212 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001213 * backgrounds (i.e. stops) or kills all members of currently running
1214 * pipe.
1215 *
1216 * Wait builtin in interruptible by signals for which user trap is set
1217 * or by SIGINT in interactive shell.
1218 *
1219 * Trap handlers will execute even within trap handlers. (right?)
1220 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001221 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1222 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001223 *
1224 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001225 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001226 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001227 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001228 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001229 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001230 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001231 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001232 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001233 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001234 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001235 *
1236 * SIGQUIT: ignore
1237 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001238 * SIGHUP (interactive):
1239 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001240 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001241 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1242 * that all pipe members are stopped. Try this in bash:
1243 * while :; do :; done - ^Z does not background it
1244 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001245 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001246 * of the command line, show prompt. NB: ^C does not send SIGINT
1247 * to interactive shell while shell is waiting for a pipe,
1248 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001249 * Example 1: this waits 5 sec, but does not execute ls:
1250 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1251 * Example 2: this does not wait and does not execute ls:
1252 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1253 * Example 3: this does not wait 5 sec, but executes ls:
1254 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001255 *
1256 * (What happens to signals which are IGN on shell start?)
1257 * (What happens with signal mask on shell start?)
1258 *
1259 * Implementation in hush
1260 * ======================
1261 * We use in-kernel pending signal mask to determine which signals were sent.
1262 * We block all signals which we don't want to take action immediately,
1263 * i.e. we block all signals which need to have special handling as described
1264 * above, and all signals which have traps set.
1265 * After each pipe execution, we extract any pending signals via sigtimedwait()
1266 * and act on them.
1267 *
1268 * unsigned non_DFL_mask: a mask of such "special" signals
1269 * sigset_t blocked_set: current blocked signal set
1270 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001271 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001272 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001273 * "trap 'cmd' SIGxxx":
1274 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001275 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001276 * unblock signals with special interactive handling
1277 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001278 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001279 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001280 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001281 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001282 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001283 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001284 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001285 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001286 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001287 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001288 * Standard says "When a subshell is entered, traps that are not being ignored
1289 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001290 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001291 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001292enum {
1293 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001294 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001295 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001296 | (1 << SIGHUP)
1297 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001298 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001299#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001300 | (1 << SIGTTIN)
1301 | (1 << SIGTTOU)
1302 | (1 << SIGTSTP)
1303#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001304};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001305
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001306#if ENABLE_HUSH_FAST
1307static void SIGCHLD_handler(int sig UNUSED_PARAM)
1308{
1309 G.count_SIGCHLD++;
1310//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1311}
1312#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001313
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001314#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001315
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001316/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001317# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001318/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001319# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001320
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001321/* Restores tty foreground process group, and exits.
1322 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001323 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001324 * or called directly with -EXITCODE.
1325 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001326static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001327static void sigexit(int sig)
1328{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001329 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001330 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001331
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001332 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001333 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001334 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1335 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001336
1337 /* Not a signal, just exit */
1338 if (sig <= 0)
1339 _exit(- sig);
1340
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001341 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001342}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001343#else
1344
Denys Vlasenko8391c482010-05-22 17:50:43 +02001345# define disable_restore_tty_pgrp_on_exit() ((void)0)
1346# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001347
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001348#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001349
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001350/* Restores tty foreground process group, and exits. */
1351static void hush_exit(int exitcode) NORETURN;
1352static void hush_exit(int exitcode)
1353{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001354 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1355 /* Prevent recursion:
1356 * trap "echo Hi; exit" EXIT; exit
1357 */
1358 char *argv[] = { NULL, G.traps[0], NULL };
1359 G.traps[0] = NULL;
1360 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001361 builtin_eval(argv);
1362 free(argv[1]);
1363 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001364
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001365#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001366 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001367 sigexit(- (exitcode & 0xff));
1368#else
1369 exit(exitcode);
1370#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001371}
1372
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001373static int check_and_run_traps(int sig)
1374{
Dan Fandrichfdd7b562010-06-18 22:37:42 -07001375 static const struct timespec zero_timespec;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001376 smalluint save_rcode;
1377 int last_sig = 0;
1378
1379 if (sig)
1380 goto jump_in;
1381 while (1) {
1382 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1383 if (sig <= 0)
1384 break;
1385 jump_in:
1386 last_sig = sig;
1387 if (G.traps && G.traps[sig]) {
1388 if (G.traps[sig][0]) {
1389 /* We have user-defined handler */
1390 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1391 save_rcode = G.last_exitcode;
1392 builtin_eval(argv);
1393 free(argv[1]);
1394 G.last_exitcode = save_rcode;
1395 } /* else: "" trap, ignoring signal */
1396 continue;
1397 }
1398 /* not a trap: special action */
1399 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001400#if ENABLE_HUSH_FAST
1401 case SIGCHLD:
1402 G.count_SIGCHLD++;
1403//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1404 break;
1405#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001406 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001407 /* Builtin was ^C'ed, make it look prettier: */
1408 bb_putchar('\n');
1409 G.flag_SIGINT = 1;
1410 break;
1411#if ENABLE_HUSH_JOB
1412 case SIGHUP: {
1413 struct pipe *job;
1414 /* bash is observed to signal whole process groups,
1415 * not individual processes */
1416 for (job = G.job_list; job; job = job->next) {
1417 if (job->pgrp <= 0)
1418 continue;
1419 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1420 if (kill(- job->pgrp, SIGHUP) == 0)
1421 kill(- job->pgrp, SIGCONT);
1422 }
1423 sigexit(SIGHUP);
1424 }
1425#endif
1426 default: /* ignored: */
1427 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1428 break;
1429 }
1430 }
1431 return last_sig;
1432}
1433
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001434
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001435static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001436{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001437 if (force || G.cwd == NULL) {
1438 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1439 * we must not try to free(bb_msg_unknown) */
1440 if (G.cwd == bb_msg_unknown)
1441 G.cwd = NULL;
1442 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1443 if (!G.cwd)
1444 G.cwd = bb_msg_unknown;
1445 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001446 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001447}
1448
Denis Vlasenko83506862007-11-23 13:11:42 +00001449
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001450/*
1451 * Shell and environment variable support
1452 */
1453static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001454{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001455 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001456 struct variable *cur;
1457 int len;
1458
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001459 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001460 pp = &G.top_var;
1461 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001462 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001463 return pp;
1464 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001465 }
1466 return NULL;
1467}
1468
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001469static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001470{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001471 struct variable **pp = get_ptr_to_local_var(name);
1472 if (pp)
1473 return *pp;
1474 return NULL;
1475}
1476
Denys Vlasenko03dad222010-01-12 23:29:57 +01001477static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001478{
Denys Vlasenko29082232010-07-16 13:52:32 +02001479 struct variable **vpp;
1480
1481 if (G.expanded_assignments) {
1482 char **cpp = G.expanded_assignments;
1483 int len = strlen(name);
1484 while (*cpp) {
1485 char *cp = *cpp;
1486 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1487 return cp + len + 1;
1488 cpp++;
1489 }
1490 }
1491
1492 vpp = get_ptr_to_local_var(name);
1493 if (vpp)
1494 return strchr((*vpp)->varstr, '=') + 1;
1495
Denys Vlasenkodea47882009-10-09 15:40:49 +02001496 if (strcmp(name, "PPID") == 0)
1497 return utoa(G.root_ppid);
1498 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001499#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001500 if (strcmp(name, "RANDOM") == 0) {
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001501 return utoa(next_random(&G.random_gen));
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001502 }
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001503#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001504 return NULL;
1505}
1506
1507/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001508 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001509 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001510 * 0: do not change export flag
1511 * (if creating new variable, flag will be 0)
1512 * 1: set export flag and putenv the variable
1513 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001514 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001515 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001516#if !BB_MMU && ENABLE_HUSH_LOCAL
1517/* all params are used */
1518#elif BB_MMU && ENABLE_HUSH_LOCAL
1519#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1520 set_local_var(str, flg_export, local_lvl)
1521#elif BB_MMU && !ENABLE_HUSH_LOCAL
1522#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001523 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001524#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1525#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1526 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001527#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001528static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001529{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001530 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001531 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001532 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001533 int name_len;
1534
Denis Vlasenko950bd722009-04-21 11:23:56 +00001535 eq_sign = strchr(str, '=');
1536 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001537 free(str);
1538 return -1;
1539 }
1540
Denis Vlasenko950bd722009-04-21 11:23:56 +00001541 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001542 var_pp = &G.top_var;
1543 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001544 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001545 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001546 continue;
1547 }
1548 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001549 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001550#if !BB_MMU
1551 if (!flg_read_only)
1552#endif
1553 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001554 free(str);
1555 return -1;
1556 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001557 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001558 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1559 *eq_sign = '\0';
1560 unsetenv(str);
1561 *eq_sign = '=';
1562 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001563#if ENABLE_HUSH_LOCAL
1564 if (cur->func_nest_level < local_lvl) {
1565 /* New variable is declared as local,
1566 * and existing one is global, or local
1567 * from enclosing function.
1568 * Remove and save old one: */
1569 *var_pp = cur->next;
1570 cur->next = *G.shadowed_vars_pp;
1571 *G.shadowed_vars_pp = cur;
1572 /* bash 3.2.33(1) and exported vars:
1573 * # export z=z
1574 * # f() { local z=a; env | grep ^z; }
1575 * # f
1576 * z=a
1577 * # env | grep ^z
1578 * z=z
1579 */
1580 if (cur->flg_export)
1581 flg_export = 1;
1582 break;
1583 }
1584#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001585 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001586 free_and_exp:
1587 free(str);
1588 goto exp;
1589 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001590 if (cur->max_len != 0) {
1591 if (cur->max_len >= strlen(str)) {
1592 /* This one is from startup env, reuse space */
1593 strcpy(cur->varstr, str);
1594 goto free_and_exp;
1595 }
1596 } else {
1597 /* max_len == 0 signifies "malloced" var, which we can
1598 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001599 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001600 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001601 cur->max_len = 0;
1602 goto set_str_and_exp;
1603 }
1604
Denys Vlasenko295fef82009-06-03 12:47:26 +02001605 /* Not found - create new variable struct */
1606 cur = xzalloc(sizeof(*cur));
1607#if ENABLE_HUSH_LOCAL
1608 cur->func_nest_level = local_lvl;
1609#endif
1610 cur->next = *var_pp;
1611 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001612
1613 set_str_and_exp:
1614 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001615#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001616 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001617#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001618 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001619 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001620 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001621 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1622 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001623 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001624 if (flg_export == -1) {
1625 cur->flg_export = 0;
1626 /* unsetenv was already done */
1627 } else {
1628 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1629 return putenv(cur->varstr);
1630 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001631 }
1632 return 0;
1633}
1634
Denys Vlasenko6db47842009-09-05 20:15:17 +02001635/* Used at startup and after each cd */
1636static void set_pwd_var(int exp)
1637{
1638 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1639 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1640}
1641
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001642static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001643{
1644 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001645 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001646
1647 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001648 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001649 var_pp = &G.top_var;
1650 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001651 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1652 if (cur->flg_read_only) {
1653 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001654 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001655 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001656 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001657 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1658 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001659 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1660 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001661 if (!cur->max_len)
1662 free(cur->varstr);
1663 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001664 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001665 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001666 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001667 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001668 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001669}
1670
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001671static int unset_local_var(const char *name)
1672{
1673 return unset_local_var_len(name, strlen(name));
1674}
1675
1676static void unset_vars(char **strings)
1677{
1678 char **v;
1679
1680 if (!strings)
1681 return;
1682 v = strings;
1683 while (*v) {
1684 const char *eq = strchrnul(*v, '=');
1685 unset_local_var_len(*v, (int)(eq - *v));
1686 v++;
1687 }
1688 free(strings);
1689}
1690
Mike Frysinger98c52642009-04-02 10:02:37 +00001691#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko8391c482010-05-22 17:50:43 +02001692# define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1693# define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denys Vlasenko03dad222010-01-12 23:29:57 +01001694static char* FAST_FUNC endofname(const char *name)
Mike Frysinger98c52642009-04-02 10:02:37 +00001695{
1696 char *p;
1697
1698 p = (char *) name;
1699 if (!is_name(*p))
1700 return p;
1701 while (*++p) {
1702 if (!is_in_name(*p))
1703 break;
1704 }
1705 return p;
1706}
Denys Vlasenko6b01b712010-01-24 22:52:21 +01001707#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001708
Denys Vlasenko03dad222010-01-12 23:29:57 +01001709static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001710{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001711 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001712 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001713}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001714
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001715
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001716/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001717 * Helpers for "var1=val1 var2=val2 cmd" feature
1718 */
1719static void add_vars(struct variable *var)
1720{
1721 struct variable *next;
1722
1723 while (var) {
1724 next = var->next;
1725 var->next = G.top_var;
1726 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001727 if (var->flg_export) {
1728 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001729 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001730 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001731 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001732 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001733 var = next;
1734 }
1735}
1736
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001737static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001738{
1739 char **s;
1740 struct variable *old = NULL;
1741
1742 if (!strings)
1743 return old;
1744 s = strings;
1745 while (*s) {
1746 struct variable *var_p;
1747 struct variable **var_pp;
1748 char *eq;
1749
1750 eq = strchr(*s, '=');
1751 if (eq) {
1752 *eq = '\0';
1753 var_pp = get_ptr_to_local_var(*s);
1754 *eq = '=';
1755 if (var_pp) {
1756 /* Remove variable from global linked list */
1757 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001758 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001759 *var_pp = var_p->next;
1760 /* Add it to returned list */
1761 var_p->next = old;
1762 old = var_p;
1763 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001764 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001765 }
1766 s++;
1767 }
1768 return old;
1769}
1770
1771
1772/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001773 * in_str support
1774 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001775static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001776{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001777 int ch = *i->p;
1778 if (ch != '\0') {
1779 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001780 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001781 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001782 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001783}
1784
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001785static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001786{
1787 return *i->p;
1788}
1789
1790#if ENABLE_HUSH_INTERACTIVE
1791
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001792static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001793{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001794 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001795 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001796 if (G.PS1 == NULL)
1797 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001798 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001799 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001800 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001801 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001802 if (G.PS2 == NULL)
1803 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001804}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001805
1806static const char* setup_prompt_string(int promptmode)
1807{
1808 const char *prompt_str;
1809 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001810 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1811 /* Set up the prompt */
1812 if (promptmode == 0) { /* PS1 */
1813 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001814 /* bash uses $PWD value, even if it is set by user.
1815 * It uses current dir only if PWD is unset.
1816 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001817 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001818 prompt_str = G.PS1;
1819 } else
1820 prompt_str = G.PS2;
1821 } else
1822 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001823 debug_printf("result '%s'\n", prompt_str);
1824 return prompt_str;
1825}
1826
1827static void get_user_input(struct in_str *i)
1828{
1829 int r;
1830 const char *prompt_str;
1831
1832 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001833# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001834 /* Enable command line editing only while a command line
1835 * is actually being read */
1836 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001837 G.flag_SIGINT = 0;
1838 /* buglet: SIGINT will not make new prompt to appear _at once_,
1839 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001840 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 +00001841 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001842 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001843 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001844 i->eof_flag = (r < 0);
1845 if (i->eof_flag) { /* EOF/error detected */
1846 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1847 G.user_input_buf[1] = '\0';
1848 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001849# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001850 do {
1851 G.flag_SIGINT = 0;
1852 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001853 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001854 G.user_input_buf[0] = r = fgetc(i->file);
1855 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001856//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001857 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001858 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001859# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001860 i->p = G.user_input_buf;
1861}
1862
1863#endif /* INTERACTIVE */
1864
1865/* This is the magic location that prints prompts
1866 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001867static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001868{
1869 int ch;
1870
1871 /* If there is data waiting, eat it up */
1872 if (i->p && *i->p) {
1873#if ENABLE_HUSH_INTERACTIVE
1874 take_cached:
1875#endif
1876 ch = *i->p++;
1877 if (i->eof_flag && !*i->p)
1878 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001879 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001880 } else {
1881 /* need to double check i->file because we might be doing something
1882 * more complicated by now, like sourcing or substituting. */
1883#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001884 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001885 do {
1886 get_user_input(i);
1887 } while (!*i->p); /* need non-empty line */
1888 i->promptmode = 1; /* PS2 */
1889 i->promptme = 0;
1890 goto take_cached;
1891 }
1892#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001893 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001894 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001895 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001896#if ENABLE_HUSH_INTERACTIVE
1897 if (ch == '\n')
1898 i->promptme = 1;
1899#endif
1900 return ch;
1901}
1902
Denis Vlasenko913a2012009-04-05 22:17:04 +00001903/* All callers guarantee this routine will never
1904 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001905 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001906static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001907{
1908 int ch;
1909 if (i->p && *i->p) {
1910 if (i->eof_flag && !i->p[1])
1911 return EOF;
1912 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001913 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001914 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001915 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001916 i->eof_flag = (ch == EOF);
1917 i->peek_buf[0] = ch;
1918 i->peek_buf[1] = '\0';
1919 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001920 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001921 return ch;
1922}
1923
1924static void setup_file_in_str(struct in_str *i, FILE *f)
1925{
1926 i->peek = file_peek;
1927 i->get = file_get;
1928#if ENABLE_HUSH_INTERACTIVE
1929 i->promptme = 1;
1930 i->promptmode = 0; /* PS1 */
1931#endif
1932 i->file = f;
1933 i->p = NULL;
1934}
1935
1936static void setup_string_in_str(struct in_str *i, const char *s)
1937{
1938 i->peek = static_peek;
1939 i->get = static_get;
1940#if ENABLE_HUSH_INTERACTIVE
1941 i->promptme = 1;
1942 i->promptmode = 0; /* PS1 */
1943#endif
1944 i->p = s;
1945 i->eof_flag = 0;
1946}
1947
1948
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001949/*
1950 * o_string support
1951 */
1952#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001953
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001954static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001955{
1956 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001957 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001958 if (o->data)
1959 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001960}
1961
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001962static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001963{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001964 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001965 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001966}
1967
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001968static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1969{
1970 free(o->data);
1971}
1972
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001973static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001974{
1975 if (o->length + len > o->maxlen) {
1976 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1977 o->data = xrealloc(o->data, 1 + o->maxlen);
1978 }
1979}
1980
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001981static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001982{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001983 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1984 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001985 o->data[o->length] = ch;
1986 o->length++;
1987 o->data[o->length] = '\0';
1988}
1989
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001990static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001991{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001992 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001993 memcpy(&o->data[o->length], str, len);
1994 o->length += len;
1995 o->data[o->length] = '\0';
1996}
1997
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001998static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001999{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002000 o_addblock(o, str, strlen(str));
2001}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002002
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002003#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002004static void nommu_addchr(o_string *o, int ch)
2005{
2006 if (o)
2007 o_addchr(o, ch);
2008}
2009#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002010# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002011#endif
2012
2013static void o_addstr_with_NUL(o_string *o, const char *str)
2014{
2015 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002016}
2017
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002018static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00002019{
2020 while (len) {
2021 o_addchr(o, *str);
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002022 if (*str == '\\') {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002023 o_addchr(o, '\\');
2024 }
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002025 str++;
Denis Vlasenko55789c62008-06-18 16:30:42 +00002026 len--;
2027 }
2028}
2029
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002030#undef HUSH_BRACE_EXP
2031/*
2032 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
2033 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2034 * Apparently, on unquoted $v bash still does globbing
2035 * ("v='*.txt'; echo $v" prints all .txt files),
2036 * but NOT brace expansion! Thus, there should be TWO independent
2037 * quoting mechanisms on $v expansion side: one protects
2038 * $v from brace expansion, and other additionally protects "$v" against globbing.
2039 * We have only second one.
2040 */
2041
2042#ifdef HUSH_BRACE_EXP
2043# define MAYBE_BRACES "{}"
2044#else
2045# define MAYBE_BRACES ""
2046#endif
2047
Eric Andersen25f27032001-04-26 23:22:31 +00002048/* My analysis of quoting semantics tells me that state information
2049 * is associated with a destination, not a source.
2050 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002051static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00002052{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002053 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002054 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002055 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002056 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002057 o_grow_by(o, sz);
2058 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002059 o->data[o->length] = '\\';
2060 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00002061 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002062 o->data[o->length] = ch;
2063 o->length++;
2064 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002065}
2066
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002067static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002068{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002069 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002070 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002071 sz++;
2072 o->data[o->length] = '\\';
2073 o->length++;
2074 }
2075 o_grow_by(o, sz);
2076 o->data[o->length] = ch;
2077 o->length++;
2078 o->data[o->length] = '\0';
2079}
2080
2081static void o_addQstr(o_string *o, const char *str, int len)
2082{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002083 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002084 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002085 return;
2086 }
2087 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002088 char ch;
2089 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002090 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002091 if (ordinary_cnt > len) /* paranoia */
2092 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002093 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002094 if (ordinary_cnt == len)
2095 return;
2096 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002097 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002098
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002099 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002100 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002101 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002102 sz++;
2103 o->data[o->length] = '\\';
2104 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002105 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00002106 o_grow_by(o, sz);
2107 o->data[o->length] = ch;
2108 o->length++;
2109 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002110 }
2111}
2112
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002113/* A special kind of o_string for $VAR and `cmd` expansion.
2114 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002115 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002116 * list[i] contains an INDEX (int!) into this string data.
2117 * It means that if list[] needs to grow, data needs to be moved higher up
2118 * but list[i]'s need not be modified.
2119 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002120 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002121 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2122 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002123#if DEBUG_EXPAND || DEBUG_GLOB
2124static void debug_print_list(const char *prefix, o_string *o, int n)
2125{
2126 char **list = (char**)o->data;
2127 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2128 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002129
2130 indent();
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002131 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2132 prefix, list, n, string_start, o->length, o->maxlen, o->o_glob, o->o_quoted, o->o_escape);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002133 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002134 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002135 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
2136 o->data + (int)list[i] + string_start,
2137 o->data + (int)list[i] + string_start);
2138 i++;
2139 }
2140 if (n) {
2141 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002142 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002143 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002144 }
2145}
2146#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002147# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002148#endif
2149
2150/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2151 * in list[n] so that it points past last stored byte so far.
2152 * It returns n+1. */
2153static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002154{
2155 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00002156 int string_start;
2157 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002158
2159 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00002160 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2161 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002162 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002163 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002164 /* list[n] points to string_start, make space for 16 more pointers */
2165 o->maxlen += 0x10 * sizeof(list[0]);
2166 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00002167 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002168 memmove(list + n + 0x10, list + n, string_len);
2169 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002170 } else {
2171 debug_printf_list("list[%d]=%d string_start=%d\n",
2172 n, string_len, string_start);
2173 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002174 } else {
2175 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00002176 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2177 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002178 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2179 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002180 o->has_empty_slot = 0;
2181 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002182 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002183 return n + 1;
2184}
2185
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002186/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002187static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002188{
2189 char **list = (char**)o->data;
2190 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2191
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002192 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002193}
2194
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002195#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002196/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2197 * first, it processes even {a} (no commas), second,
2198 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002199 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002200 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002201
2202/* Helper */
2203static int glob_needed(const char *s)
2204{
2205 while (*s) {
2206 if (*s == '\\') {
2207 if (!s[1])
2208 return 0;
2209 s += 2;
2210 continue;
2211 }
2212 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2213 return 1;
2214 s++;
2215 }
2216 return 0;
2217}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002218/* Return pointer to next closing brace or to comma */
2219static const char *next_brace_sub(const char *cp)
2220{
2221 unsigned depth = 0;
2222 cp++;
2223 while (*cp != '\0') {
2224 if (*cp == '\\') {
2225 if (*++cp == '\0')
2226 break;
2227 cp++;
2228 continue;
Denys Vlasenko3581c622010-01-25 13:39:24 +01002229 }
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002230 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2231 break;
2232 if (*cp++ == '{') /*}*/
2233 depth++;
2234 }
2235
2236 return *cp != '\0' ? cp : NULL;
2237}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002238/* Recursive brace globber. Note: may garble pattern[]. */
2239static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002240{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002241 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002242 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002243 const char *next;
2244 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002245 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002246 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002247
2248 debug_printf_glob("glob_brace('%s')\n", pattern);
2249
2250 begin = pattern;
2251 while (1) {
2252 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002253 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002254 if (*begin == '{') /*}*/ {
2255 /* Find the first sub-pattern and at the same time
2256 * find the rest after the closing brace */
2257 next = next_brace_sub(begin);
2258 if (next == NULL) {
2259 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002260 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002261 }
2262 /*{*/ if (*next == '}') {
2263 /* "{abc}" with no commas - illegal
2264 * brace expr, disregard and skip it */
2265 begin = next + 1;
2266 continue;
2267 }
2268 break;
2269 }
2270 if (*begin == '\\' && begin[1] != '\0')
2271 begin++;
2272 begin++;
2273 }
2274 debug_printf_glob("begin:%s\n", begin);
2275 debug_printf_glob("next:%s\n", next);
2276
2277 /* Now find the end of the whole brace expression */
2278 rest = next;
2279 /*{*/ while (*rest != '}') {
2280 rest = next_brace_sub(rest);
2281 if (rest == NULL) {
2282 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002283 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002284 }
2285 debug_printf_glob("rest:%s\n", rest);
2286 }
2287 rest_len = strlen(++rest) + 1;
2288
2289 /* We are sure the brace expression is well-formed */
2290
2291 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002292 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002293
2294 /* We have a brace expression. BEGIN points to the opening {,
2295 * NEXT points past the terminator of the first element, and REST
2296 * points past the final }. We will accumulate result names from
2297 * recursive runs for each brace alternative in the buffer using
2298 * GLOB_APPEND. */
2299
2300 p = begin + 1;
2301 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002302 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002303 memcpy(
2304 mempcpy(
2305 mempcpy(new_pattern_buf,
2306 /* We know the prefix for all sub-patterns */
2307 pattern, begin - pattern),
2308 p, next - p),
2309 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002310
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002311 /* Note: glob_brace() may garble new_pattern_buf[].
2312 * That's why we re-copy prefix every time (1st memcpy above).
2313 */
2314 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002315 /*{*/ if (*next == '}') {
2316 /* We saw the last entry */
2317 break;
2318 }
2319 p = next + 1;
2320 next = next_brace_sub(next);
2321 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002322 free(new_pattern_buf);
2323 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002324
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002325 simple_glob:
2326 {
2327 int gr;
2328 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002329
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002330 memset(&globdata, 0, sizeof(globdata));
2331 gr = glob(pattern, 0, NULL, &globdata);
2332 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2333 if (gr != 0) {
2334 if (gr == GLOB_NOMATCH) {
2335 globfree(&globdata);
2336 /* NB: garbles parameter */
2337 unbackslash(pattern);
2338 o_addstr_with_NUL(o, pattern);
2339 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2340 return o_save_ptr_helper(o, n);
2341 }
2342 if (gr == GLOB_NOSPACE)
2343 bb_error_msg_and_die(bb_msg_memory_exhausted);
2344 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2345 * but we didn't specify it. Paranoia again. */
2346 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2347 }
2348 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2349 char **argv = globdata.gl_pathv;
2350 while (1) {
2351 o_addstr_with_NUL(o, *argv);
2352 n = o_save_ptr_helper(o, n);
2353 argv++;
2354 if (!*argv)
2355 break;
2356 }
2357 }
2358 globfree(&globdata);
2359 }
2360 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002361}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002362/* Performs globbing on last list[],
2363 * saving each result as a new list[].
2364 */
2365static int o_glob(o_string *o, int n)
2366{
2367 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002368
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002369 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2370 if (!o->data)
2371 return o_save_ptr_helper(o, n);
2372 pattern = o->data + o_get_last_ptr(o, n);
2373 debug_printf_glob("glob pattern '%s'\n", pattern);
2374 if (!glob_needed(pattern)) {
2375 /* unbackslash last string in o in place, fix length */
2376 o->length = unbackslash(pattern) - o->data;
2377 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2378 return o_save_ptr_helper(o, n);
2379 }
2380
2381 copy = xstrdup(pattern);
2382 /* "forget" pattern in o */
2383 o->length = pattern - o->data;
2384 n = glob_brace(copy, o, n);
2385 free(copy);
2386 if (DEBUG_GLOB)
2387 debug_print_list("o_glob returning", o, n);
2388 return n;
2389}
2390
Denys Vlasenko8391c482010-05-22 17:50:43 +02002391#else /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002392
2393/* Helper */
2394static int glob_needed(const char *s)
2395{
2396 while (*s) {
2397 if (*s == '\\') {
2398 if (!s[1])
2399 return 0;
2400 s += 2;
2401 continue;
2402 }
2403 if (*s == '*' || *s == '[' || *s == '?')
2404 return 1;
2405 s++;
2406 }
2407 return 0;
2408}
2409/* Performs globbing on last list[],
2410 * saving each result as a new list[].
2411 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002412static int o_glob(o_string *o, int n)
2413{
2414 glob_t globdata;
2415 int gr;
2416 char *pattern;
2417
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002418 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002419 if (!o->data)
2420 return o_save_ptr_helper(o, n);
2421 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002422 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002423 if (!glob_needed(pattern)) {
2424 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002425 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002426 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002427 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002428 return o_save_ptr_helper(o, n);
2429 }
2430
2431 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002432 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2433 * If we glob "*.\*" and don't find anything, we need
2434 * to fall back to using literal "*.*", but GLOB_NOCHECK
2435 * will return "*.\*"!
2436 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002437 gr = glob(pattern, 0, NULL, &globdata);
2438 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002439 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002440 if (gr == GLOB_NOMATCH) {
2441 globfree(&globdata);
2442 goto literal;
2443 }
2444 if (gr == GLOB_NOSPACE)
2445 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002446 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2447 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002448 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002449 }
2450 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2451 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002452 /* "forget" pattern in o */
2453 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002454 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002455 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002456 n = o_save_ptr_helper(o, n);
2457 argv++;
2458 if (!*argv)
2459 break;
2460 }
2461 }
2462 globfree(&globdata);
2463 if (DEBUG_GLOB)
2464 debug_print_list("o_glob returning", o, n);
2465 return n;
2466}
2467
Denys Vlasenko8391c482010-05-22 17:50:43 +02002468#endif /* !HUSH_BRACE_EXP */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002469
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002470/* If o->o_glob == 1, glob the string so far remembered.
2471 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002472static int o_save_ptr(o_string *o, int n)
2473{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002474 if (o->o_glob) { /* if globbing is requested */
2475 /* If o->has_empty_slot, list[n] was already globbed
2476 * (if it was requested back then when it was filled)
2477 * so don't do that again! */
2478 if (!o->has_empty_slot)
2479 return o_glob(o, n); /* o_save_ptr_helper is inside */
2480 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002481 return o_save_ptr_helper(o, n);
2482}
2483
2484/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002485static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002486{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002487 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002488 int string_start;
2489
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002490 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2491 if (DEBUG_EXPAND)
2492 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002493 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002494 list = (char**)o->data;
2495 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2496 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002497 while (n) {
2498 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002499 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002500 }
2501 return list;
2502}
2503
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002504
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002505/* Expansion can recurse */
2506#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002507static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002508#endif
2509static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002510#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002511#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002512 parse_stream_dquoted(dest, input, dquote_end)
2513#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002514static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002515 o_string *dest,
2516 struct in_str *input,
2517 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002518
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002519/* expand_strvec_to_strvec() takes a list of strings, expands
2520 * all variable references within and returns a pointer to
2521 * a list of expanded strings, possibly with larger number
2522 * of strings. (Think VAR="a b"; echo $VAR).
2523 * This new list is allocated as a single malloc block.
2524 * NULL-terminated list of char* pointers is at the beginning of it,
2525 * followed by strings themself.
2526 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002527
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002528/* Store given string, finalizing the word and starting new one whenever
2529 * we encounter IFS char(s). This is used for expanding variable values.
2530 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2531static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002532{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002533 while (1) {
2534 int word_len = strcspn(str, G.ifs);
2535 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002536 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002537 o_addQstr(output, str, word_len);
2538 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002539 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002540 str += word_len;
2541 }
2542 if (!*str) /* EOL - do not finalize word */
2543 break;
2544 o_addchr(output, '\0');
2545 debug_print_list("expand_on_ifs", output, n);
2546 n = o_save_ptr(output, n);
2547 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002548 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002549 debug_print_list("expand_on_ifs[1]", output, n);
2550 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002551}
2552
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002553/* Helper to expand $((...)) and heredoc body. These act as if
2554 * they are in double quotes, with the exception that they are not :).
2555 * Just the rules are similar: "expand only $var and `cmd`"
2556 *
2557 * Returns malloced string.
2558 * As an optimization, we return NULL if expansion is not needed.
2559 */
2560static char *expand_pseudo_dquoted(const char *str)
2561{
2562 char *exp_str;
2563 struct in_str input;
2564 o_string dest = NULL_O_STRING;
2565
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002566 if (!strchr(str, '$')
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002567#if ENABLE_HUSH_TICK
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002568 && !strchr(str, '`')
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002569#endif
2570 ) {
2571 return NULL;
2572 }
2573
2574 /* We need to expand. Example:
2575 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2576 */
2577 setup_string_in_str(&input, str);
2578 parse_stream_dquoted(NULL, &dest, &input, EOF);
2579 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2580 exp_str = expand_string_to_string(dest.data);
2581 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2582 o_free_unsafe(&dest);
2583 return exp_str;
2584}
2585
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002586#if ENABLE_SH_MATH_SUPPORT
2587static arith_t expand_and_evaluate_arith(const char *arg, int *errcode_p)
2588{
2589 arith_eval_hooks_t hooks;
2590 arith_t res;
2591 char *exp_str;
2592
2593 hooks.lookupvar = get_local_var_value;
2594 hooks.setvar = set_local_var_from_halves;
2595 hooks.endofname = endofname;
2596 exp_str = expand_pseudo_dquoted(arg);
2597 res = arith(exp_str ? exp_str : arg, errcode_p, &hooks);
2598 free(exp_str);
2599 return res;
2600}
2601#endif
2602
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002603/* Expand all variable references in given string, adding words to list[]
2604 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2605 * to be filled). This routine is extremely tricky: has to deal with
2606 * variables/parameters with whitespace, $* and $@, and constructs like
2607 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02002608static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002609{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002610 /* or_mask is either 0 (normal case) or 0x80 -
2611 * expansion of right-hand side of assignment == 1-element expand.
2612 * It will also do no globbing, and thus we must not backslash-quote!
2613 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002614 char ored_ch;
2615 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002616
2617 ored_ch = 0;
2618
Denys Vlasenkof37eb392009-10-18 11:46:35 +02002619 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002620 debug_print_list("expand_vars_to_list", output, n);
2621 n = o_save_ptr(output, n);
2622 debug_print_list("expand_vars_to_list[0]", output, n);
2623
2624 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002625 char first_ch;
2626 int i;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002627 char *to_be_freed = NULL;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002628 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002629#if ENABLE_HUSH_TICK
2630 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002631#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002632#if ENABLE_SH_MATH_SUPPORT
2633 char arith_buf[sizeof(arith_t)*3 + 2];
2634#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002635 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002636 debug_print_list("expand_vars_to_list[1]", output, n);
2637 arg = ++p;
2638 p = strchr(p, SPECIAL_VAR_SYMBOL);
2639
2640 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2641 /* "$@" is special. Even if quoted, it can still
2642 * expand to nothing (not even an empty string) */
2643 if ((first_ch & 0x7f) != '@')
2644 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002645
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002646 switch (first_ch & 0x7f) {
2647 /* Highest bit in first_ch indicates that var is double-quoted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002648 case '*':
2649 case '@':
2650 i = 1;
2651 if (!G.global_argv[i])
2652 break;
2653 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2654 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002655 smallint sv = output->o_escape;
2656 /* unquoted var's contents should be globbed, so don't escape */
2657 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002658 while (G.global_argv[i]) {
2659 n = expand_on_ifs(output, n, G.global_argv[i]);
2660 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2661 if (G.global_argv[i++][0] && G.global_argv[i]) {
2662 /* this argv[] is not empty and not last:
2663 * put terminating NUL, start new word */
2664 o_addchr(output, '\0');
2665 debug_print_list("expand_vars_to_list[2]", output, n);
2666 n = o_save_ptr(output, n);
2667 debug_print_list("expand_vars_to_list[3]", output, n);
2668 }
2669 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002670 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002671 } else
2672 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2673 * and in this case should treat it like '$*' - see 'else...' below */
2674 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2675 while (1) {
2676 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2677 if (++i >= G.global_argc)
2678 break;
2679 o_addchr(output, '\0');
2680 debug_print_list("expand_vars_to_list[4]", output, n);
2681 n = o_save_ptr(output, n);
2682 }
2683 } else { /* quoted $*: add as one word */
2684 while (1) {
2685 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2686 if (!G.global_argv[++i])
2687 break;
2688 if (G.ifs[0])
2689 o_addchr(output, G.ifs[0]);
2690 }
2691 }
2692 break;
2693 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2694 /* "Empty variable", used to make "" etc to not disappear */
2695 arg++;
2696 ored_ch = 0x80;
2697 break;
2698#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002699 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002700 *p = '\0';
2701 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002702 /* Can't just stuff it into output o_string,
2703 * expanded result may need to be globbed
2704 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002705 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko647553a2009-11-15 19:58:19 +01002706 G.last_exitcode = process_command_subs(&subst_result, arg);
Denys Vlasenkocddbb612010-05-20 14:27:09 +02002707 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002708 val = subst_result.data;
2709 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002710#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002711#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002712 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002713 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002714 int errcode;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002715
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002716 arg++; /* skip '+' */
2717 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002718 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002719 res = expand_and_evaluate_arith(arg, &errcode);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002720
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002721 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002722 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002723 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002724 case -3:
2725 msg = "exponent less than 0";
2726 break;
2727 case -2:
2728 msg = "divide by 0";
2729 break;
2730 case -5:
2731 msg = "expression recursion loop detected";
2732 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002733 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002734 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002735 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002736 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002737 sprintf(arith_buf, arith_t_fmt, res);
2738 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002739 break;
2740 }
2741#endif
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002742 default: { /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02002743//TODO: move to a subroutine?
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002744 char *var;
2745 char first_char;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002746 char exp_op;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002747 char exp_save = exp_save; /* for compiler */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002748 char *exp_saveptr; /* points to expansion operator */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002749 char *exp_word = exp_word; /* for compiler */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002750
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002751 var = arg;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002752 *p = '\0';
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002753 exp_saveptr = arg[1] ? strchr("%#:-=+?", arg[1]) : NULL;
2754 first_char = arg[0] = first_ch & 0x7f;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002755 exp_op = 0;
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002756
2757 if (first_char == '#' && arg[1] && !exp_saveptr) {
Mike Frysinger6379bb42009-03-28 18:55:03 +00002758 /* handle length expansion ${#var} */
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002759 var++;
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002760 exp_op = 'L';
Mike Frysinger6379bb42009-03-28 18:55:03 +00002761 } else {
2762 /* maybe handle parameter expansion */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002763 if (exp_saveptr /* if 2nd char is one of expansion operators */
2764 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2765 ) {
2766 /* ${?:0}, ${#[:]%0} etc */
2767 exp_saveptr = var + 1;
2768 } else {
2769 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2770 exp_saveptr = var+1 + strcspn(var+1, "%#:-=+?");
2771 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002772 exp_op = exp_save = *exp_saveptr;
2773 if (exp_op) {
2774 exp_word = exp_saveptr + 1;
2775 if (exp_op == ':') {
2776 exp_op = *exp_word++;
2777 if (ENABLE_HUSH_BASH_COMPAT
2778 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2779 ) {
2780 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2781 exp_op = ':';
2782 exp_word--;
2783 }
2784 }
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002785 *exp_saveptr = '\0';
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002786 } /* else: it's not an expansion op, but bare ${var} */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002787 }
2788
2789 /* lookup the variable in question */
2790 if (isdigit(var[0])) {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002791 /* parse_dollar() should have vetted var for us */
Denys Vlasenko77832482010-08-12 14:14:45 +02002792 i = xatoi_positive(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002793 if (i < G.global_argc)
2794 val = G.global_argv[i];
2795 /* else val remains NULL: $N with too big N */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002796 } else {
2797 switch (var[0]) {
2798 case '$': /* pid */
2799 val = utoa(G.root_pid);
2800 break;
2801 case '!': /* bg pid */
2802 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2803 break;
2804 case '?': /* exitcode */
2805 val = utoa(G.last_exitcode);
2806 break;
2807 case '#': /* argc */
2808 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2809 break;
2810 default:
2811 val = get_local_var_value(var);
2812 }
2813 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002814
2815 /* handle any expansions */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002816 if (exp_op == 'L') {
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002817 debug_printf_expand("expand: length(%s)=", val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002818 val = utoa(val ? strlen(val) : 0);
2819 debug_printf_expand("%s\n", val);
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002820 } else if (exp_op) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002821 if (exp_op == '%' || exp_op == '#') {
Denys Vlasenko53b51332010-05-20 21:46:45 +02002822 /* Standard-mandated substring removal ops:
2823 * ${parameter%word} - remove smallest suffix pattern
2824 * ${parameter%%word} - remove largest suffix pattern
2825 * ${parameter#word} - remove smallest prefix pattern
2826 * ${parameter##word} - remove largest prefix pattern
2827 *
2828 * Word is expanded to produce a glob pattern.
2829 * Then var's value is matched to it and matching part removed.
2830 */
Mike Frysinger57e74672009-04-09 23:00:33 +00002831 if (val) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002832 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002833 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002834 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002835 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002836 exp_word++;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002837 val = to_be_freed = xstrdup(val);
Denys Vlasenko74369502010-05-21 19:52:01 +02002838 {
2839 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2840 if (exp_exp_word)
2841 exp_word = exp_exp_word;
2842 loc = scan(to_be_freed, exp_word, match_at_left);
2843 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2844 // exp_op, to_be_freed, exp_word, loc);
2845 free(exp_exp_word);
2846 }
2847 if (loc) { /* match was found */
2848 if (match_at_left) /* # or ## */
2849 val = loc;
2850 else /* % or %% */
2851 *loc = '\0';
2852 }
Mike Frysinger57e74672009-04-09 23:00:33 +00002853 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002854 } else if (exp_op == ':') {
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02002855#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002856 /* It's ${var:N[:M]} bashism.
2857 * Note that in encoded form it has TWO parts:
2858 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002859 */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002860 arith_t beg, len;
2861 int errcode = 0;
2862
2863 beg = expand_and_evaluate_arith(exp_word, &errcode);
2864 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2865 *p++ = SPECIAL_VAR_SYMBOL;
2866 exp_word = p;
2867 p = strchr(p, SPECIAL_VAR_SYMBOL);
2868 *p = '\0';
2869 len = expand_and_evaluate_arith(exp_word, &errcode);
2870 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2871
2872 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2873 if (beg < 0) /* bash compat */
2874 beg = 0;
2875 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002876 if (len == 0 || !val || beg >= strlen(val))
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002877 val = "";
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002878 else {
2879 /* Paranoia. What if user entered 9999999999999
2880 * which fits in arith_t but not int? */
2881 if (len >= INT_MAX)
2882 len = INT_MAX;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002883 val = to_be_freed = xstrndup(val + beg, len);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002884 }
2885 debug_printf_varexp("val:'%s'\n", val);
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002886 } else
2887#endif
2888 {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002889 die_if_script("malformed ${%s:...}", var);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002890 val = "";
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002891 }
2892 } else { /* one of "-=+?" */
Denys Vlasenko53b51332010-05-20 21:46:45 +02002893 /* Standard-mandated substitution ops:
2894 * ${var?word} - indicate error if unset
2895 * If var is unset, word (or a message indicating it is unset
2896 * if word is null) is written to standard error
2897 * and the shell exits with a non-zero exit status.
2898 * Otherwise, the value of var is substituted.
2899 * ${var-word} - use default value
2900 * If var is unset, word is substituted.
2901 * ${var=word} - assign and use default value
2902 * If var is unset, word is assigned to var.
2903 * In all cases, final value of var is substituted.
2904 * ${var+word} - use alternative value
2905 * If var is unset, null is substituted.
2906 * Otherwise, word is substituted.
2907 *
2908 * Word is subjected to tilde expansion, parameter expansion,
2909 * command substitution, and arithmetic expansion.
2910 * If word is not needed, it is not expanded.
2911 *
2912 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2913 * but also treat null var as if it is unset.
2914 */
2915 int use_word = (!val || ((exp_save == ':') && !val[0]));
Mike Frysingera4f331d2009-04-07 06:03:22 +00002916 if (exp_op == '+')
Denys Vlasenko53b51332010-05-20 21:46:45 +02002917 use_word = !use_word;
Mike Frysingera4f331d2009-04-07 06:03:22 +00002918 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
Denys Vlasenko53b51332010-05-20 21:46:45 +02002919 (exp_save == ':') ? "true" : "false", use_word);
2920 if (use_word) {
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002921 to_be_freed = expand_pseudo_dquoted(exp_word);
2922 if (to_be_freed)
2923 exp_word = to_be_freed;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002924 if (exp_op == '?') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002925 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002926 die_if_script("%s: %s",
2927 var,
2928 exp_word[0] ? exp_word : "parameter null or not set"
2929 );
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002930//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002931 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002932 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002933 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002934
Mike Frysingera4f331d2009-04-07 06:03:22 +00002935 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002936 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002937 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002938 /* mimic bash message */
2939 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002940 val = NULL;
2941 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002942 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002943 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002944 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002945 }
2946 }
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002947 } /* one of "-=+?" */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002948
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002949 *exp_saveptr = exp_save;
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002950 } /* if (exp_op) */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002951
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002952 arg[0] = first_ch;
2953#if ENABLE_HUSH_TICK
2954 store_val:
2955#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002956 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002957 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002958 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002959 /* unquoted var's contents should be globbed, so don't escape */
2960 smallint sv = output->o_escape;
2961 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002962 n = expand_on_ifs(output, n, val);
2963 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002964 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002965 }
2966 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002967 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002968 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002969 } /* default: */
2970 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002971
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002972 if (val) {
2973 o_addQstr(output, val, strlen(val));
2974 }
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002975 free(to_be_freed);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002976 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002977 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002978 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002979
2980#if ENABLE_HUSH_TICK
2981 o_free(&subst_result);
2982#endif
2983 arg = ++p;
2984 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2985
2986 if (arg[0]) {
2987 debug_print_list("expand_vars_to_list[a]", output, n);
2988 /* this part is literal, and it was already pre-quoted
2989 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002990 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002991 debug_print_list("expand_vars_to_list[b]", output, n);
2992 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2993 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2994 ) {
2995 n--;
2996 /* allow to reuse list[n] later without re-growth */
2997 output->has_empty_slot = 1;
2998 } else {
2999 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00003000 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003001 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00003002}
3003
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02003004enum {
3005 EXPVAR_FLAG_GLOB = 0x200,
3006 EXPVAR_FLAG_ESCAPE_VARS = 0x100,
3007 EXPVAR_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
3008};
3009static char **expand_variables(char **argv, unsigned or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003010{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003011 int n;
3012 char **list;
3013 char **v;
3014 o_string output = NULL_O_STRING;
3015
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02003016 /* protect against globbing for "$var"? */
3017 /* (unquoted $var will temporarily switch it off) */
3018 output.o_escape = 1 & (or_mask / EXPVAR_FLAG_ESCAPE_VARS);
3019 output.o_glob = 1 & (or_mask / EXPVAR_FLAG_GLOB);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003020
3021 n = 0;
3022 v = argv;
3023 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003024 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003025 v++;
3026 }
3027 debug_print_list("expand_variables", &output, n);
3028
3029 /* output.data (malloced in one block) gets returned in "list" */
3030 list = o_finalize_list(&output, n);
3031 debug_print_strings("expand_variables[1]", list);
3032 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00003033}
3034
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003035static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003036{
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02003037 return expand_variables(argv, EXPVAR_FLAG_GLOB | EXPVAR_FLAG_ESCAPE_VARS);
Eric Andersen25f27032001-04-26 23:22:31 +00003038}
3039
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003040#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003041static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
3042{
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02003043 return expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003044}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003045#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003046
3047#ifdef CMD_SINGLEWORD_NOGLOB_COND
3048static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
3049{
3050 int n;
3051 char **list;
3052 char **v;
3053 o_string output = NULL_O_STRING;
3054
3055 n = 0;
3056 v = argv;
3057 while (*v) {
3058 int is_var = is_well_formed_var_name(*v, '=');
3059 /* is_var * 0x80: singleword expansion for vars */
3060 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
3061
3062 /* Subtle! expand_vars_to_list did not glob last word yet.
3063 * It does this only when fed with further data.
3064 * Therefore we set globbing flags AFTER it, not before:
3065 */
3066
3067 /* if it is not recognizably abc=...; then: */
3068 output.o_escape = !is_var; /* protect against globbing for "$var" */
3069 /* (unquoted $var will temporarily switch it off) */
3070 output.o_glob = !is_var; /* and indeed do globbing */
3071 v++;
3072 }
3073 debug_print_list("expand_cond", &output, n);
3074
3075 /* output.data (malloced in one block) gets returned in "list" */
3076 list = o_finalize_list(&output, n);
3077 debug_print_strings("expand_cond[1]", list);
3078 return list;
3079}
3080#endif
3081
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003082/* Used for expansion of right hand of assignments */
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02003083/* NB: should NOT do globbing!
3084 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003085static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00003086{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003087 char *argv[2], **list;
3088
3089 argv[0] = (char*)str;
3090 argv[1] = NULL;
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02003091 list = expand_variables(argv, EXPVAR_FLAG_ESCAPE_VARS | EXPVAR_FLAG_SINGLEWORD);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003092 if (HUSH_DEBUG)
3093 if (!list[0] || list[1])
3094 bb_error_msg_and_die("BUG in varexp2");
3095 /* actually, just move string 2*sizeof(char*) bytes back */
3096 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003097 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003098 debug_printf_expand("string_to_string='%s'\n", (char*)list);
3099 return (char*)list;
3100}
3101
3102/* Used for "eval" builtin */
3103static char* expand_strvec_to_string(char **argv)
3104{
3105 char **list;
3106
Denys Vlasenkoe298ce62010-09-04 19:52:44 +02003107 list = expand_variables(argv, EXPVAR_FLAG_SINGLEWORD);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003108 /* Convert all NULs to spaces */
3109 if (list[0]) {
3110 int n = 1;
3111 while (list[n]) {
3112 if (HUSH_DEBUG)
3113 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
3114 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00003115 /* bash uses ' ' regardless of $IFS contents */
3116 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003117 n++;
3118 }
3119 }
3120 overlapping_strcpy((char*)list, list[0]);
3121 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
3122 return (char*)list;
3123}
3124
3125static char **expand_assignments(char **argv, int count)
3126{
3127 int i;
Denys Vlasenko29082232010-07-16 13:52:32 +02003128 char **p;
3129
3130 G.expanded_assignments = p = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003131 /* Expand assignments into one string each */
3132 for (i = 0; i < count; i++) {
Denys Vlasenko29082232010-07-16 13:52:32 +02003133 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003134 }
Denys Vlasenko29082232010-07-16 13:52:32 +02003135 G.expanded_assignments = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003136 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00003137}
3138
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003139
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003140#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003141/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003142void re_execute_shell(char ***to_free, const char *s,
3143 char *g_argv0, char **g_argv,
3144 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003145
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003146static void reset_traps_to_defaults(void)
3147{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003148 /* This function is always called in a child shell
3149 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003150 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003151 unsigned sig;
3152 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003153
Denys Vlasenko67f71862009-09-25 14:21:06 +02003154 /* Child shells are not interactive.
3155 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
3156 * Testcase: (while :; do :; done) + ^Z should background.
3157 * Same goes for SIGTERM, SIGHUP, SIGINT.
3158 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003159 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02003160 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003161
Denys Vlasenko67f71862009-09-25 14:21:06 +02003162 /* Switching off SPECIAL_INTERACTIVE_SIGS.
3163 * Stupid. It can be done with *single* &= op, but we can't use
3164 * the fact that G.blocked_set is implemented as a bitmask
3165 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003166 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
3167 sig = 1;
3168 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02003169 if (mask & 1) {
3170 /* Careful. Only if no trap or trap is not "" */
3171 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
3172 sigdelset(&G.blocked_set, sig);
3173 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003174 mask >>= 1;
3175 if (!mask)
3176 break;
3177 sig++;
3178 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02003179 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003180 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003181
3182 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003183 mask = G.non_DFL_mask;
3184 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02003185 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003186 continue;
3187 free(G.traps[sig]);
3188 G.traps[sig] = NULL;
3189 /* There is no signal for 0 (EXIT) */
3190 if (sig == 0)
3191 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003192 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003193 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02003194 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003195 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003196 continue;
3197 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003198 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003199 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003200}
3201
3202#else /* !BB_MMU */
3203
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003204static void re_execute_shell(char ***to_free, const char *s,
3205 char *g_argv0, char **g_argv,
3206 char **builtin_argv) NORETURN;
3207static void re_execute_shell(char ***to_free, const char *s,
3208 char *g_argv0, char **g_argv,
3209 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003210{
Denys Vlasenko8391c482010-05-22 17:50:43 +02003211# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003212 /* delims + 2 * (number of bytes in printed hex numbers) */
3213 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003214 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003215 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003216# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003217 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003218# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003219 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003220 unsigned cnt;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003221 unsigned long long empty_trap_mask;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003222
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003223 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003224 argv = heredoc_argv;
3225 argv[0] = (char *) G.argv0_for_re_execing;
3226 argv[1] = (char *) "-<";
3227 argv[2] = (char *) s;
3228 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00003229 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003230 goto do_exec;
3231 }
3232
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003233 cnt = 0;
3234 pp = builtin_argv;
3235 if (pp) while (*pp++)
3236 cnt++;
3237
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003238 empty_trap_mask = 0;
3239 if (G.traps) {
3240 int sig;
3241 for (sig = 1; sig < NSIG; sig++) {
3242 if (G.traps[sig] && !G.traps[sig][0])
3243 empty_trap_mask |= 1LL << sig;
3244 }
3245 }
3246
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003247 sprintf(param_buf, NOMMU_HACK_FMT
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003248 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02003249 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003250 , (unsigned) G.last_bg_pid
3251 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003252 , cnt
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003253 , empty_trap_mask
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003254 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003255 );
Denys Vlasenko8391c482010-05-22 17:50:43 +02003256# undef NOMMU_HACK_FMT
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003257 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003258 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003259 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003260 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003261 for (cur = G.top_var; cur; cur = cur->next) {
3262 if (!cur->flg_export || cur->flg_read_only)
3263 cnt += 2;
3264 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003265# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003266 for (funcp = G.top_func; funcp; funcp = funcp->next)
3267 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003268# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003269 pp = g_argv;
3270 while (*pp++)
3271 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003272 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003273 *pp++ = (char *) G.argv0_for_re_execing;
3274 *pp++ = param_buf;
3275 for (cur = G.top_var; cur; cur = cur->next) {
3276 if (cur->varstr == hush_version_str)
3277 continue;
3278 if (cur->flg_read_only) {
3279 *pp++ = (char *) "-R";
3280 *pp++ = cur->varstr;
3281 } else if (!cur->flg_export) {
3282 *pp++ = (char *) "-V";
3283 *pp++ = cur->varstr;
3284 }
3285 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003286# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003287 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3288 *pp++ = (char *) "-F";
3289 *pp++ = funcp->name;
3290 *pp++ = funcp->body_as_string;
3291 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003292# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003293 /* We can pass activated traps here. Say, -Tnn:trap_string
3294 *
3295 * However, POSIX says that subshells reset signals with traps
3296 * to SIG_DFL.
3297 * I tested bash-3.2 and it not only does that with true subshells
3298 * of the form ( list ), but with any forked children shells.
3299 * I set trap "echo W" WINCH; and then tried:
3300 *
3301 * { echo 1; sleep 20; echo 2; } &
3302 * while true; do echo 1; sleep 20; echo 2; break; done &
3303 * true | { echo 1; sleep 20; echo 2; } | cat
3304 *
3305 * In all these cases sending SIGWINCH to the child shell
3306 * did not run the trap. If I add trap "echo V" WINCH;
3307 * _inside_ group (just before echo 1), it works.
3308 *
3309 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003310 * Even if we would use signal handlers instead of signal masking
3311 * in order to implement trap handling,
3312 * exec syscall below resets signals to SIG_DFL for us.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003313 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003314 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003315 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003316 if (builtin_argv) {
3317 while (*++builtin_argv)
3318 *pp++ = *builtin_argv;
3319 *pp++ = (char *) "";
3320 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003321 *pp++ = g_argv0;
3322 while (*g_argv)
3323 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003324 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003325 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003326
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003327 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003328 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3329 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003330 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003331 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003332 if (argv[0][0] == '/')
3333 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003334 xfunc_error_retval = 127;
3335 bb_error_msg_and_die("can't re-execute the shell");
3336}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003337#endif /* !BB_MMU */
3338
3339
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003340static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003341{
3342 struct fd_pair pair;
3343 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003344 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003345 /* the _body_ of heredoc (misleading field name) */
3346 const char *heredoc = redir->rd_filename;
3347 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003348#if !BB_MMU
3349 char **to_free;
3350#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003351
3352 expanded = NULL;
3353 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3354 expanded = expand_pseudo_dquoted(heredoc);
3355 if (expanded)
3356 heredoc = expanded;
3357 }
3358 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003359
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003360 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003361 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003362 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003363
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003364 /* Try writing without forking. Newer kernels have
3365 * dynamically growing pipes. Must use non-blocking write! */
3366 ndelay_on(pair.wr);
3367 while (1) {
3368 written = write(pair.wr, heredoc, len);
3369 if (written <= 0)
3370 break;
3371 len -= written;
3372 if (len == 0) {
3373 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00003374 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003375 return;
3376 }
3377 heredoc += written;
3378 }
3379 ndelay_off(pair.wr);
3380
3381 /* Okay, pipe buffer was not big enough */
3382 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003383 * for the unsuspecting parent process. Child creates a grandchild
3384 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003385 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003386#if !BB_MMU
3387 to_free = NULL;
3388#endif
Pascal Bellard926031b2010-07-04 15:32:38 +02003389 pid = xvfork();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003390 if (pid == 0) {
3391 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003392 disable_restore_tty_pgrp_on_exit();
Pascal Bellard926031b2010-07-04 15:32:38 +02003393 pid = BB_MMU ? xfork() : xvfork();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003394 if (pid != 0)
3395 _exit(0);
3396 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003397 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003398#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003399 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003400 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003401#else
3402 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003403 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003404 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003405#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003406 }
3407 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003408#if ENABLE_HUSH_FAST
3409 G.count_SIGCHLD++;
3410//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3411#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003412 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003413#if !BB_MMU
3414 free(to_free);
3415#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003416 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003417 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003418 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003419}
3420
Eric Andersen25f27032001-04-26 23:22:31 +00003421/* squirrel != NULL means we squirrel away copies of stdin, stdout,
3422 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003423static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00003424{
3425 int openfd, mode;
3426 struct redir_struct *redir;
3427
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003428 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003429 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003430 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003431 if (squirrel && redir->rd_fd < 3
3432 && squirrel[redir->rd_fd] < 0
3433 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003434 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003435 }
3436 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3437 * of the heredoc */
3438 debug_printf_parse("set heredoc '%s'\n",
3439 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003440 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00003441 continue;
3442 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003443
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003444 if (redir->rd_dup == REDIRFD_TO_FILE) {
3445 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003446 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003447 if (redir->rd_filename == NULL) {
3448 /* Something went wrong in the parse.
3449 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003450 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003451 continue;
3452 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003453 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003454 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003455 openfd = open_or_warn(p, mode);
3456 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00003457 if (openfd < 0) {
3458 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003459 * bash and ash both lose it as well (though zsh doesn't!) */
3460//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00003461 return 1;
3462 }
3463 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003464 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003465 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00003466 }
3467
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003468 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003469 if (squirrel && redir->rd_fd < 3
3470 && squirrel[redir->rd_fd] < 0
3471 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003472 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00003473 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003474 if (openfd == REDIRFD_CLOSE) {
3475 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003476 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003477 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003478 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003479 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003480 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003481 }
Eric Andersen25f27032001-04-26 23:22:31 +00003482 }
3483 }
3484 return 0;
3485}
3486
3487static void restore_redirects(int squirrel[])
3488{
3489 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003490 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00003491 fd = squirrel[i];
3492 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003493 /* We simply die on error */
3494 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00003495 }
3496 }
3497}
3498
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003499
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003500static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003501
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003502/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003503static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003504{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003505 char **p;
3506 struct command *command;
3507 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003508 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003509
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003510 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003511 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003512 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003513 for (i = 0; i < pi->num_cmds; i++) {
3514 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003515 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003516 if (command->argv) {
3517 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003518 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003519 }
3520 free_strings(command->argv);
3521 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003522 }
3523 /* not "else if": on syntax error, we may have both! */
3524 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003525 debug_printf_clean(" begin group (cmd_type:%d)\n",
3526 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003527 free_pipe_list(command->group);
3528 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003529 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003530 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003531 /* else is crucial here.
3532 * If group != NULL, child_func is meaningless */
3533#if ENABLE_HUSH_FUNCTIONS
3534 else if (command->child_func) {
3535 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3536 command->child_func->parent_cmd = NULL;
3537 }
3538#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003539#if !BB_MMU
3540 free(command->group_as_string);
3541 command->group_as_string = NULL;
3542#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003543 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003544 debug_printf_clean(" redirect %d%s",
3545 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003546 /* guard against the case >$FOO, where foo is unset or blank */
3547 if (r->rd_filename) {
3548 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3549 free(r->rd_filename);
3550 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003551 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003552 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003553 rnext = r->next;
3554 free(r);
3555 }
3556 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003557 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003558 free(pi->cmds); /* children are an array, they get freed all at once */
3559 pi->cmds = NULL;
3560#if ENABLE_HUSH_JOB
3561 free(pi->cmdtext);
3562 pi->cmdtext = NULL;
3563#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003564}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003565
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003566static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003567{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003568 struct pipe *pi, *next;
3569
3570 for (pi = head; pi; pi = next) {
3571#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003572 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003573#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003574 free_pipe(pi);
3575 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003576 next = pi->next;
3577 /*pi->next = NULL;*/
3578 free(pi);
3579 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003580}
3581
3582
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003583static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003584#if BB_MMU
3585#define parse_stream(pstring, input, end_trigger) \
3586 parse_stream(input, end_trigger)
3587#endif
3588static struct pipe *parse_stream(char **pstring,
3589 struct in_str *input,
3590 int end_trigger);
3591static void parse_and_run_string(const char *s);
3592
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003593
Mike Frysinger93cadc22009-05-27 17:06:25 -04003594static char *find_in_path(const char *arg)
3595{
3596 char *ret = NULL;
3597 const char *PATH = get_local_var_value("PATH");
3598
3599 if (!PATH)
3600 return NULL;
3601
3602 while (1) {
3603 const char *end = strchrnul(PATH, ':');
3604 int sz = end - PATH; /* must be int! */
3605
3606 free(ret);
3607 if (sz != 0) {
3608 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3609 } else {
3610 /* We have xxx::yyyy in $PATH,
3611 * it means "use current dir" */
3612 ret = xstrdup(arg);
3613 }
3614 if (access(ret, F_OK) == 0)
3615 break;
3616
3617 if (*end == '\0') {
3618 free(ret);
3619 return NULL;
3620 }
3621 PATH = end + 1;
3622 }
3623
3624 return ret;
3625}
3626
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003627static const struct built_in_command* find_builtin_helper(const char *name,
3628 const struct built_in_command *x,
3629 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003630{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003631 while (x != end) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01003632 if (strcmp(name, x->b_cmd) != 0) {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003633 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003634 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003635 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003636 debug_printf_exec("found builtin '%s'\n", name);
3637 return x;
3638 }
3639 return NULL;
3640}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003641static const struct built_in_command* find_builtin1(const char *name)
3642{
3643 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3644}
3645static const struct built_in_command* find_builtin(const char *name)
3646{
3647 const struct built_in_command *x = find_builtin1(name);
3648 if (x)
3649 return x;
3650 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3651}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003652
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003653#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003654static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003655{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003656 struct function **funcpp = &G.top_func;
3657 while (*funcpp) {
3658 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003659 break;
3660 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003661 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003662 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003663 return funcpp;
3664}
3665
3666static const struct function *find_function(const char *name)
3667{
3668 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003669 if (funcp)
3670 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003671 return funcp;
3672}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003673
Denis Vlasenkobc569742009-04-12 20:35:19 +00003674/* Note: takes ownership on name ptr */
3675static struct function *new_function(char *name)
3676{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003677 struct function **funcpp = find_function_slot(name);
3678 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003679
Denys Vlasenko873273d2009-09-12 14:47:41 +02003680 if (funcp != NULL) {
3681 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003682 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3683 if (!cmd) {
3684 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3685 free(funcp->name);
3686 /* Note: if !funcp->body, do not free body_as_string!
3687 * This is a special case of "-F name body" function:
3688 * body_as_string was not malloced! */
3689 if (funcp->body) {
3690 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003691# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003692 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003693# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003694 }
3695 } else {
3696 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3697 cmd->argv[0] = funcp->name;
3698 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003699# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003700 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003701# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003702 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003703 } else {
3704 debug_printf_exec("remembering new function '%s'\n", name);
3705 funcp = *funcpp = xzalloc(sizeof(*funcp));
3706 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003707 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003708
Denis Vlasenkobc569742009-04-12 20:35:19 +00003709 funcp->name = name;
3710 return funcp;
3711}
3712
Denis Vlasenko40e84372009-04-18 11:23:38 +00003713static void unset_func(const char *name)
3714{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003715 struct function **funcpp = find_function_slot(name);
3716 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003717
Denys Vlasenko873273d2009-09-12 14:47:41 +02003718 if (funcp != NULL) {
3719 debug_printf_exec("freeing function '%s'\n", funcp->name);
3720 *funcpp = funcp->next;
3721 /* funcp is unlinked now, deleting it.
3722 * Note: if !funcp->body, the function was created by
3723 * "-F name body", do not free ->body_as_string
3724 * and ->name as they were not malloced. */
3725 if (funcp->body) {
3726 free_pipe_list(funcp->body);
3727 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003728# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003729 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003730# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003731 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003732 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003733 }
3734}
3735
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003736# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003737#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003738 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003739# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003740static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003741 const struct function *funcp,
3742 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003743static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003744 const struct function *funcp,
3745 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003746{
3747# if BB_MMU
3748 int n = 1;
3749
3750 argv[0] = G.global_argv[0];
3751 G.global_argv = argv;
3752 while (*++argv)
3753 n++;
3754 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003755 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003756 n = run_list(funcp->body);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003757 fflush_all();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003758 _exit(n);
3759# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003760 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003761 funcp->body_as_string,
3762 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003763 argv + 1,
3764 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003765# endif
3766}
3767
3768static int run_function(const struct function *funcp, char **argv)
3769{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003770 int rc;
3771 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003772 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003773
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003774 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003775
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003776 /* "we are in function, ok to use return" */
3777 sv_flg = G.flag_return_in_progress;
3778 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003779# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003780 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003781# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003782
Denis Vlasenkobc569742009-04-12 20:35:19 +00003783 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003784# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003785 if (!funcp->body) {
3786 /* Function defined by -F */
3787 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003788 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003789 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003790# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003791 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003792 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003793 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003794
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003795# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003796 {
3797 struct variable *var;
3798 struct variable **var_pp;
3799
3800 var_pp = &G.top_var;
3801 while ((var = *var_pp) != NULL) {
3802 if (var->func_nest_level < G.func_nest_level) {
3803 var_pp = &var->next;
3804 continue;
3805 }
3806 /* Unexport */
3807 if (var->flg_export)
3808 bb_unsetenv(var->varstr);
3809 /* Remove from global list */
3810 *var_pp = var->next;
3811 /* Free */
3812 if (!var->max_len)
3813 free(var->varstr);
3814 free(var);
3815 }
3816 G.func_nest_level--;
3817 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003818# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003819 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003820
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003821 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003822
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003823 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003824}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003825#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003826
3827
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003828#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003829#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003830 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003831#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003832#define exec_builtin(to_free, x, argv) \
3833 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003834#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003835static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003836 const struct built_in_command *x,
3837 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003838static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003839 const struct built_in_command *x,
3840 char **argv)
3841{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003842#if BB_MMU
Denys Vlasenko17323a62010-01-28 01:57:05 +01003843 int rcode = x->b_function(argv);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003844 fflush_all();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003845 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003846#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003847 /* On NOMMU, we must never block!
3848 * Example: { sleep 99 | read line; } & echo Ok
3849 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003850 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003851 argv[0],
3852 G.global_argv[0],
3853 G.global_argv + 1,
3854 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003855#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003856}
3857
3858
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003859static void execvp_or_die(char **argv) NORETURN;
3860static void execvp_or_die(char **argv)
3861{
3862 debug_printf_exec("execing '%s'\n", argv[0]);
3863 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3864 execvp(argv[0], argv);
3865 bb_perror_msg("can't execute '%s'", argv[0]);
3866 _exit(127); /* bash compat */
3867}
3868
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003869#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003870static void dump_cmd_in_x_mode(char **argv)
3871{
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003872 if (G_x_mode && argv) {
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003873 /* We want to output the line in one write op */
3874 char *buf, *p;
3875 int len;
3876 int n;
3877
3878 len = 3;
3879 n = 0;
3880 while (argv[n])
3881 len += strlen(argv[n++]) + 1;
3882 buf = xmalloc(len);
3883 buf[0] = '+';
3884 p = buf + 1;
3885 n = 0;
3886 while (argv[n])
3887 p += sprintf(p, " %s", argv[n++]);
3888 *p++ = '\n';
3889 *p = '\0';
3890 fputs(buf, stderr);
3891 free(buf);
3892 }
3893}
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003894#else
3895# define dump_cmd_in_x_mode(argv) ((void)0)
3896#endif
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003897
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003898#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003899#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3900 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3901#define pseudo_exec(nommu_save, command, argv_expanded) \
3902 pseudo_exec(command, argv_expanded)
3903#endif
3904
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003905/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003906 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003907 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003908 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003909 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003910static void pseudo_exec_argv(nommu_save_t *nommu_save,
3911 char **argv, int assignment_cnt,
3912 char **argv_expanded) NORETURN;
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003913static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003914 char **argv, int assignment_cnt,
3915 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003916{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003917 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003918
Denis Vlasenko9504e442008-10-29 01:19:15 +00003919 new_env = expand_assignments(argv, assignment_cnt);
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003920 dump_cmd_in_x_mode(new_env);
Denys Vlasenko889550b2010-07-14 19:01:25 +02003921
3922 if (!argv[assignment_cnt]) {
3923 /* Case when we are here: ... | var=val | ...
3924 * (note that we do not exit early, i.e., do not optimize out
3925 * expand_assignments(): think about ... | var=`sleep 1` | ...
3926 */
3927 free_strings(new_env);
3928 _exit(EXIT_SUCCESS);
3929 }
3930
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003931#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003932 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003933 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003934 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003935 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003936#else
3937 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003938 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003939#endif
Denys Vlasenko889550b2010-07-14 19:01:25 +02003940
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003941 if (argv_expanded) {
3942 argv = argv_expanded;
3943 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003944 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003945#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003946 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003947#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003948 }
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003949 dump_cmd_in_x_mode(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003950
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003951#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3952 if (strchr(argv[0], '/') != NULL)
3953 goto skip;
3954#endif
3955
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003956 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003957 * Depending on context, this might be redundant. But it's
3958 * easier to waste a few CPU cycles than it is to figure out
3959 * if this is one of those cases.
3960 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003961 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003962 /* On NOMMU, it is more expensive to re-execute shell
3963 * just in order to run echo or test builtin.
3964 * It's better to skip it here and run corresponding
3965 * non-builtin later. */
3966 const struct built_in_command *x;
3967 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003968 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003969 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003970 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003971 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003972#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003973 /* Check if the command matches any functions */
3974 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003975 const struct function *funcp = find_function(argv[0]);
3976 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003977 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003978 }
3979 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003980#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003981
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003982#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003983 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003984 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003985 int a = find_applet_by_name(argv[0]);
3986 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003987# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003988 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003989 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003990 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003991 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003992# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003993 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003994 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003995 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3996 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003997 /* If they called chroot or otherwise made the binary no longer
3998 * executable, fall through */
3999 }
4000 }
Eric Andersenaac75e52001-04-30 18:18:45 +00004001#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004002
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004003#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004004 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004005#endif
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02004006 execvp_or_die(argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +00004007}
4008
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004009/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00004010 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004011static void pseudo_exec(nommu_save_t *nommu_save,
4012 struct command *command,
4013 char **argv_expanded) NORETURN;
4014static void pseudo_exec(nommu_save_t *nommu_save,
4015 struct command *command,
4016 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00004017{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004018 if (command->argv) {
4019 pseudo_exec_argv(nommu_save, command->argv,
4020 command->assignment_cnt, argv_expanded);
4021 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004022
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004023 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00004024 /* Cases when we are here:
4025 * ( list )
4026 * { list } &
4027 * ... | ( list ) | ...
4028 * ... | { list } | ...
4029 */
4030#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00004031 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004032 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004033 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004034 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00004035 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004036 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00004037 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004038#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004039 re_execute_shell(&nommu_save->argv_from_re_execing,
4040 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004041 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02004042 G.global_argv + 1,
4043 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00004044#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004045 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004046
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004047 /* Case when we are here: ... | >file */
4048 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004049 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00004050}
4051
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004052#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004053static const char *get_cmdtext(struct pipe *pi)
4054{
4055 char **argv;
4056 char *p;
4057 int len;
4058
4059 /* This is subtle. ->cmdtext is created only on first backgrounding.
4060 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004061 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004062 if (pi->cmdtext)
4063 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004064 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004065 if (!argv || !argv[0]) {
4066 pi->cmdtext = xzalloc(1);
4067 return pi->cmdtext;
4068 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004069
4070 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004071 do {
4072 len += strlen(*argv) + 1;
4073 } while (*++argv);
4074 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004075 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004076 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004077 do {
4078 len = strlen(*argv);
4079 memcpy(p, *argv, len);
4080 p += len;
4081 *p++ = ' ';
4082 } while (*++argv);
4083 p[-1] = '\0';
4084 return pi->cmdtext;
4085}
4086
Eric Andersenbafd94f2001-05-02 16:11:59 +00004087static void insert_bg_job(struct pipe *pi)
4088{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004089 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004090 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004091
4092 /* Linear search for the ID of the job to use */
4093 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004094 for (job = G.job_list; job; job = job->next)
4095 if (job->jobid >= pi->jobid)
4096 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004097
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004098 /* Add job to the list of running jobs */
4099 jobp = &G.job_list;
4100 while ((job = *jobp) != NULL)
4101 jobp = &job->next;
4102 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00004103
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004104 *job = *pi; /* physical copy */
4105 job->next = NULL;
4106 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
4107 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004108 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004109 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004110 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004111 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004112 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00004113
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004114 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004115 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004116 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004117}
4118
Eric Andersenbafd94f2001-05-02 16:11:59 +00004119static void remove_bg_job(struct pipe *pi)
4120{
4121 struct pipe *prev_pipe;
4122
Denis Vlasenko87a86552008-07-29 19:43:10 +00004123 if (pi == G.job_list) {
4124 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004125 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004126 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004127 while (prev_pipe->next != pi)
4128 prev_pipe = prev_pipe->next;
4129 prev_pipe->next = pi->next;
4130 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004131 if (G.job_list)
4132 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00004133 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00004134 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00004135}
Eric Andersen028b65b2001-06-28 01:10:11 +00004136
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004137/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00004138static void delete_finished_bg_job(struct pipe *pi)
4139{
4140 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004141 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004142 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004143 free(pi);
4144}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004145#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004146
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004147/* Check to see if any processes have exited -- if they
4148 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00004149static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00004150{
Eric Andersenc798b072001-06-22 06:23:03 +00004151 int attributes;
4152 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004153#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00004154 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004155#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00004156 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004157 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004158
Denis Vlasenkod5762932009-03-31 11:22:57 +00004159 debug_printf_jobs("checkjobs %p\n", fg_pipe);
4160
Eric Andersenc798b072001-06-22 06:23:03 +00004161 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004162 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00004163 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00004164
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004165 errno = 0;
4166#if ENABLE_HUSH_FAST
4167 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
4168//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
4169//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02004170 /* There was neither fork nor SIGCHLD since last waitpid */
4171 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004172 if (!G.we_have_children) {
4173 errno = ECHILD;
4174 return -1;
4175 }
4176 if (fg_pipe == NULL) { /* is WNOHANG set? */
4177 /* We have children, but they did not exit
4178 * or stop yet (we saw no SIGCHLD) */
4179 return 0;
4180 }
4181 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4182 }
4183#endif
4184
Denis Vlasenko1359da62007-04-21 23:27:30 +00004185/* Do we do this right?
4186 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004187 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00004188 * [3]+ Stopped sleep 20 | false
4189 * bash-3.00# echo $?
4190 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004191 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00004192 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004193 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004194 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004195 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004196 int dead;
4197
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004198#if ENABLE_HUSH_FAST
4199 i = G.count_SIGCHLD;
4200#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004201 childpid = waitpid(-1, &status, attributes);
4202 if (childpid <= 0) {
4203 if (childpid && errno != ECHILD)
4204 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004205#if ENABLE_HUSH_FAST
4206 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004207 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004208 G.handled_SIGCHLD = i;
4209//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4210 }
4211#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004212 break;
4213 }
4214 dead = WIFEXITED(status) || WIFSIGNALED(status);
4215
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00004216#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00004217 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004218 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004219 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4220 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004221 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004222 childpid, WTERMSIG(status), WEXITSTATUS(status));
4223 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004224 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004225 childpid, WEXITSTATUS(status));
4226#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004227 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00004228 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004229 for (i = 0; i < fg_pipe->num_cmds; i++) {
4230 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4231 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004232 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004233 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004234 fg_pipe->cmds[i].pid = 0;
4235 fg_pipe->alive_cmds--;
4236 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004237 /* last process gives overall exitstatus */
4238 rcode = WEXITSTATUS(status);
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004239 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00004240 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004241 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00004242 */
4243 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00004244 int sig = WTERMSIG(status);
4245 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004246 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4247 * Maybe we need to use sig | 128? */
4248 rcode = sig + 128;
Denis Vlasenko40e84372009-04-18 11:23:38 +00004249 }
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004250 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00004251 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004252 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004253 fg_pipe->cmds[i].is_stopped = 1;
4254 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00004255 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004256 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4257 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4258 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004259 /* All processes in fg pipe have exited or stopped */
4260/* Note: *non-interactive* bash does not continue if all processes in fg pipe
4261 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4262 * and "killall -STOP cat" */
4263 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004264#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004265 if (fg_pipe->alive_cmds)
4266 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004267#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004268 return rcode;
4269 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02004270 if (!fg_pipe->alive_cmds)
4271 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004272 }
4273 /* There are still running processes in the fg pipe */
4274 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00004275 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004276 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00004277 }
4278
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004279#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004280 /* We asked to wait for bg or orphaned children */
4281 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004282 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004283 for (i = 0; i < pi->num_cmds; i++) {
4284 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004285 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00004286 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00004287 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004288 /* Happens when shell is used as init process (init=/bin/sh) */
4289 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004290 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00004291
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004292 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00004293 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00004294 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004295 pi->cmds[i].pid = 0;
4296 pi->alive_cmds--;
4297 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004298 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00004299 printf(JOB_STATUS_FORMAT, pi->jobid,
4300 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00004301 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004302 }
4303 } else {
4304 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004305 pi->cmds[i].is_stopped = 1;
4306 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004307 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004308#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004309 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004310
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004311 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00004312}
4313
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004314#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00004315static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4316{
4317 pid_t p;
4318 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04004319 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004320 /* Job finished, move the shell to the foreground */
4321 p = getpgrp(); /* our process group id */
4322 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4323 tcsetpgrp(G_interactive_fd, p);
4324 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00004325 return rcode;
4326}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004327#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00004328
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004329/* Start all the jobs, but don't wait for anything to finish.
4330 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00004331 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00004332 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00004333 * to finish to determine the exit status of the pipe. If the pipe
4334 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00004335 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00004336 * return value.
4337 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00004338 * Returns -1 only if started some children. IOW: we have to
4339 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00004340 *
4341 * The only case when we do not need to [v]fork is when the pipe
4342 * is single, non-backgrounded, non-subshell command. Examples:
4343 * cmd ; ... { list } ; ...
4344 * cmd && ... { list } && ...
4345 * cmd || ... { list } || ...
4346 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4347 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004348 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00004349 *
4350 * Cases when we must fork:
4351 * non-single: cmd | cmd
4352 * backgrounded: cmd & { list } &
4353 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00004354 */
Denys Vlasenko29082232010-07-16 13:52:32 +02004355#if !ENABLE_HUSH_MODE_X
4356#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
4357 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
4358#endif
4359static int redirect_and_varexp_helper(char ***new_env_p, struct variable **old_vars_p, struct command *command, int squirrel[3], char **argv_expanded)
4360{
4361 /* setup_redirects acts on file descriptors, not FILEs.
4362 * This is perfect for work that comes after exec().
4363 * Is it really safe for inline use? Experimentally,
4364 * things seem to work. */
4365 int rcode = setup_redirects(command, squirrel);
4366 if (rcode == 0) {
4367 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
4368 *new_env_p = new_env;
4369 dump_cmd_in_x_mode(new_env);
4370 dump_cmd_in_x_mode(argv_expanded);
4371 if (old_vars_p)
4372 *old_vars_p = set_vars_and_save_old(new_env);
4373 }
4374 return rcode;
4375}
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02004376static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004377{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004378 static const char *const null_ptr = NULL;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004379
4380 int cmd_no;
4381 int next_infd;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004382 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004383 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004384 char **argv;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004385 /* it is not always needed, but we aim to smaller code */
4386 int squirrel[] = { -1, -1, -1 };
4387 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004388
Denis Vlasenko552433b2009-04-04 19:29:21 +00004389 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004390 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004391
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004392 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004393 pi->stopped_cmds = 0;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004394 command = &pi->cmds[0];
Denis Vlasenko552433b2009-04-04 19:29:21 +00004395 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004396
Denis Vlasenko552433b2009-04-04 19:29:21 +00004397 if (pi->num_cmds != 1
4398 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004399 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00004400 ) {
4401 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004402 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004403
Denis Vlasenko552433b2009-04-04 19:29:21 +00004404 pi->alive_cmds = 1;
4405
4406 debug_printf_exec(": group:%p argv:'%s'\n",
4407 command->group, command->argv ? command->argv[0] : "NONE");
4408
4409 if (command->group) {
4410#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004411 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004412 /* "executing" func () { list } */
4413 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004414
Denis Vlasenkobc569742009-04-12 20:35:19 +00004415 funcp = new_function(command->argv[0]);
4416 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004417 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004418# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004419 funcp->body_as_string = command->group_as_string;
4420 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004421# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004422 command->group = NULL;
4423 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00004424 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4425 funcp->parent_cmd = command;
4426 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004427
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004428 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4429 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00004430 return EXIT_SUCCESS;
4431 }
4432#endif
4433 /* { list } */
4434 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004435 rcode = 1; /* exitcode if redir failed */
4436 if (setup_redirects(command, squirrel) == 0) {
4437 debug_printf_exec(": run_list\n");
4438 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004439 }
Eric Andersen04407e52001-06-07 16:42:05 +00004440 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004441 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004442 debug_leave();
4443 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004444 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004445 }
4446
Denis Vlasenko552433b2009-04-04 19:29:21 +00004447 argv = command->argv ? command->argv : (char **) &null_ptr;
4448 {
4449 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004450#if ENABLE_HUSH_FUNCTIONS
4451 const struct function *funcp;
4452#else
4453 enum { funcp = 0 };
4454#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004455 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004456 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004457
Denis Vlasenko552433b2009-04-04 19:29:21 +00004458 if (argv[command->assignment_cnt] == NULL) {
4459 /* Assignments, but no command */
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004460 /* Ensure redirects take effect (that is, create files).
Denys Vlasenko29082232010-07-16 13:52:32 +02004461 * Try "a=t >file" */
4462#if 0 /* A few cases in testsuite fail with this code. FIXME */
4463 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
4464 /* Set shell variables */
4465 if (new_env) {
4466 argv = new_env;
4467 while (*argv) {
4468 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4469 /* Do we need to flag set_local_var() errors?
4470 * "assignment to readonly var" and "putenv error"
4471 */
4472 argv++;
4473 }
4474 }
4475 /* Redirect error sets $? to 1. Otherwise,
4476 * if evaluating assignment value set $?, retain it.
4477 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4478 if (rcode == 0)
4479 rcode = G.last_exitcode;
4480 /* Exit, _skipping_ variable restoring code: */
4481 goto clean_up_and_ret0;
4482
4483#else /* Older, bigger, but more correct code */
4484
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004485 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004486 restore_redirects(squirrel);
4487 /* Set shell variables */
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004488 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004489 bb_putchar_stderr('+');
Denis Vlasenko552433b2009-04-04 19:29:21 +00004490 while (*argv) {
Denys Vlasenko29082232010-07-16 13:52:32 +02004491 char *p = expand_string_to_string(*argv);
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004492 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004493 fprintf(stderr, " %s", p);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004494 debug_printf_exec("set shell var:'%s'->'%s'\n",
4495 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02004496 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenko29082232010-07-16 13:52:32 +02004497 /* Do we need to flag set_local_var() errors?
4498 * "assignment to readonly var" and "putenv error"
4499 */
Denis Vlasenko552433b2009-04-04 19:29:21 +00004500 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00004501 }
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004502 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004503 bb_putchar_stderr('\n');
Denys Vlasenkob3389de2010-07-15 12:33:37 +02004504 /* Redirect error sets $? to 1. Otherwise,
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004505 * if evaluating assignment value set $?, retain it.
4506 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4507 if (rcode == 0)
4508 rcode = G.last_exitcode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004509 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004510 debug_leave();
4511 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004512 return rcode;
Denys Vlasenko29082232010-07-16 13:52:32 +02004513#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00004514 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004515
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004516 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004517 if (0) {}
4518#if ENABLE_HUSH_BASH_COMPAT
4519 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004520 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4521 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004522#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004523#ifdef CMD_SINGLEWORD_NOGLOB_COND
4524 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4525 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004526 }
4527#endif
4528 else {
4529 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4530 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004531
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004532 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04004533 if (!argv_expanded[0]) {
Denys Vlasenko385cc592010-01-12 06:47:39 +01004534 free(argv_expanded);
Mike Frysinger28736c32009-10-18 01:11:45 -04004535 debug_leave();
Denys Vlasenko00243b02009-11-16 02:00:03 +01004536 return G.last_exitcode;
Mike Frysinger28736c32009-10-18 01:11:45 -04004537 }
4538
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004539 x = find_builtin(argv_expanded[0]);
4540#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004541 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004542 if (!x)
4543 funcp = find_function(argv_expanded[0]);
4544#endif
4545 if (x || funcp) {
4546 if (!funcp) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01004547 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004548 debug_printf("exec with redirects only\n");
4549 rcode = setup_redirects(command, NULL);
4550 goto clean_up_and_ret1;
4551 }
Eric Andersen25f27032001-04-26 23:22:31 +00004552 }
Denys Vlasenko29082232010-07-16 13:52:32 +02004553 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004554 if (rcode == 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004555 if (!funcp) {
4556 debug_printf_exec(": builtin '%s' '%s'...\n",
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004557 x->b_cmd, argv_expanded[1]);
Denys Vlasenko17323a62010-01-28 01:57:05 +01004558 rcode = x->b_function(argv_expanded) & 0xff;
Denys Vlasenko8131eea2009-11-02 14:19:51 +01004559 fflush_all();
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004560 }
4561#if ENABLE_HUSH_FUNCTIONS
4562 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02004563# if ENABLE_HUSH_LOCAL
4564 struct variable **sv;
4565 sv = G.shadowed_vars_pp;
4566 G.shadowed_vars_pp = &old_vars;
4567# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004568 debug_printf_exec(": function '%s' '%s'...\n",
4569 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00004570 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02004571# if ENABLE_HUSH_LOCAL
4572 G.shadowed_vars_pp = sv;
4573# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004574 }
4575#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004576 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004577 clean_up_and_ret:
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004578 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004579 add_vars(old_vars);
Denys Vlasenko29082232010-07-16 13:52:32 +02004580/* clean_up_and_ret0: */
4581 restore_redirects(squirrel);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004582 clean_up_and_ret1:
4583 free(argv_expanded);
4584 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004585 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004586 debug_printf_exec("run_pipe return %d\n", rcode);
4587 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004588 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004589
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004590 if (ENABLE_FEATURE_SH_STANDALONE) {
4591 int n = find_applet_by_name(argv_expanded[0]);
4592 if (n >= 0 && APPLET_IS_NOFORK(n)) {
Denys Vlasenko29082232010-07-16 13:52:32 +02004593 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004594 if (rcode == 0) {
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004595 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4596 argv_expanded[0], argv_expanded[1]);
4597 rcode = run_nofork_applet(n, argv_expanded);
4598 }
4599 goto clean_up_and_ret;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004600 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004601 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00004602 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00004603 }
4604
Denis Vlasenko552433b2009-04-04 19:29:21 +00004605 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004606 /* NB: argv_expanded may already be created, and that
4607 * might include `cmd` runs! Do not rerun it! We *must*
4608 * use argv_expanded if it's non-NULL */
4609
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004610 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004611 pi->alive_cmds = 0;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004612 next_infd = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004613
Denys Vlasenko889550b2010-07-14 19:01:25 +02004614 cmd_no = 0;
4615 while (cmd_no < pi->num_cmds) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004616 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004617#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004618 volatile nommu_save_t nommu_save;
4619 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004620 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004621 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004622 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004623#endif
Denys Vlasenko889550b2010-07-14 19:01:25 +02004624 command = &pi->cmds[cmd_no];
4625 cmd_no++;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004626 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004627 debug_printf_exec(": pipe member '%s' '%s'...\n",
4628 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004629 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004630 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004631 }
Eric Andersen25f27032001-04-26 23:22:31 +00004632
4633 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004634 pipefds.rd = 0;
4635 pipefds.wr = 1;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004636 if (cmd_no < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004637 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004638
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004639 command->pid = BB_MMU ? fork() : vfork();
4640 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004641#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004642 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004643 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004644
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004645 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004646 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004647 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004648 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004649 pgrp = pi->pgrp;
4650 if (pgrp < 0) /* true for 1st process only */
4651 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004652 if (setpgid(0, pgrp) == 0
4653 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004654 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004655 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004656 /* We do it in *every* child, not just first,
4657 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004658 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004659 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004660 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004661#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004662 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4663 /* 1st cmd in backgrounded pipe
4664 * should have its stdin /dev/null'ed */
4665 close(0);
4666 if (open(bb_dev_null, O_RDONLY))
4667 xopen("/", O_RDONLY);
4668 } else {
Denys Vlasenko889550b2010-07-14 19:01:25 +02004669 xmove_fd(next_infd, 0);
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004670 }
4671 xmove_fd(pipefds.wr, 1);
4672 if (pipefds.rd > 1)
4673 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004674 /* Like bash, explicit redirects override pipes,
4675 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004676 if (setup_redirects(command, NULL))
4677 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004678
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004679 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004680 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4681
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004682 /* Stores to nommu_save list of env vars putenv'ed
4683 * (NOMMU, on MMU we don't need that) */
4684 /* cast away volatility... */
4685 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004686 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004687 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004688
Denis Vlasenkof9375282009-04-05 19:13:39 +00004689 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004690#if ENABLE_HUSH_FAST
4691 G.count_SIGCHLD++;
4692//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4693#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004694 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004695#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004696 /* Clean up after vforked child */
4697 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004698 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004699 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004700 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004701#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004702 free(argv_expanded);
4703 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004704 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004705 /* Clearly indicate, was it fork or vfork */
Pascal Bellard926031b2010-07-04 15:32:38 +02004706 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004707 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004708 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004709#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004710 /* Second and next children need to know pid of first one */
4711 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004712 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004713#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004714 }
Eric Andersen25f27032001-04-26 23:22:31 +00004715
Denys Vlasenko889550b2010-07-14 19:01:25 +02004716 if (cmd_no > 1)
4717 close(next_infd);
4718 if (cmd_no < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004719 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004720 /* Pass read (output) pipe end to next iteration */
Denys Vlasenko889550b2010-07-14 19:01:25 +02004721 next_infd = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004722 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004723
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004724 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004725 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004726 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4727 return 1;
4728 }
4729
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004730 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004731 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004732 return -1;
4733}
4734
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004735#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004736static void debug_print_tree(struct pipe *pi, int lvl)
4737{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004738 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004739 [PIPE_SEQ] = "SEQ",
4740 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004741 [PIPE_OR ] = "OR" ,
4742 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004743 };
4744 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004745 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004746# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004747 [RES_IF ] = "IF" ,
4748 [RES_THEN ] = "THEN" ,
4749 [RES_ELIF ] = "ELIF" ,
4750 [RES_ELSE ] = "ELSE" ,
4751 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004752# endif
4753# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004754 [RES_FOR ] = "FOR" ,
4755 [RES_WHILE] = "WHILE",
4756 [RES_UNTIL] = "UNTIL",
4757 [RES_DO ] = "DO" ,
4758 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004759# endif
4760# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004761 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004762# endif
4763# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004764 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004765 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004766 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004767 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004768 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004769# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004770 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004771 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004772 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004773 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004774 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004775 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004776 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004777# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004778 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004779# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004780 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004781
4782 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004783
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004784 pin = 0;
4785 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004786 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4787 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004788 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004789 while (prn < pi->num_cmds) {
4790 struct command *command = &pi->cmds[prn];
4791 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004792
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004793 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004794 lvl*2, "", prn,
4795 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004796 if (command->group) {
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004797 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004798 CMDTYPE[command->cmd_type],
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004799 argv
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004800# if !BB_MMU
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004801 , " group_as_string:", command->group_as_string
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004802# else
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004803 , "", ""
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004804# endif
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004805 );
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004806 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004807 prn++;
4808 continue;
4809 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004810 if (argv) while (*argv) {
4811 fprintf(stderr, " '%s'", *argv);
4812 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004813 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004814 fprintf(stderr, "\n");
4815 prn++;
4816 }
4817 pi = pi->next;
4818 pin++;
4819 }
4820}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004821#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004822
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004823/* NB: called by pseudo_exec, and therefore must not modify any
4824 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004825static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004826{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004827#if ENABLE_HUSH_CASE
4828 char *case_word = NULL;
4829#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004830#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004831 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004832 char **for_lcur = NULL;
4833 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004834#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004835 smallint last_followup;
4836 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004837#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004838 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004839#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004840 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004841#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004842#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004843 smallint rword; /* enum reserved_style */
4844 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004845#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004846
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004847 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004848 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004849
Denis Vlasenko06810332007-05-21 23:30:54 +00004850#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004851 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004852 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4853 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004854 continue;
4855 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004856 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004857 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004858 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004859 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004860 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004861 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004862 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004863 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004864 continue;
4865 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004866 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4867 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004868 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004869 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004870 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004871 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004872 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004873 }
4874 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004875#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004876
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004877 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004878 * in order to return, no direct "return" statements please.
4879 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004880
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004881#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004882 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004883#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004884
Denis Vlasenko0e151382009-04-06 18:40:31 +00004885#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004886 rword = RES_NONE;
4887 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004888#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004889 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004890 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004891
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004892 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004893 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004894 if (G.flag_SIGINT)
4895 break;
4896
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004897 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004898 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4899 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004900#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004901 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004902 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004903 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004904 /* start of a loop: remember where loop starts */
4905 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004906 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004907 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004908#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004909 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004910 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004911 if ((rcode == 0 && last_followup == PIPE_OR)
4912 || (rcode != 0 && last_followup == PIPE_AND)
4913 ) {
4914 /* It is "<true> || CMD" or "<false> && CMD"
4915 * and we should not execute CMD */
4916 debug_printf_exec("skipped cmd because of || or &&\n");
4917 last_followup = pi->followup;
4918 continue;
4919 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004920 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004921 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004922 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004923#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004924 if (cond_code) {
4925 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004926 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004927 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004928 /* "if <false> THEN cmd": skip cmd */
4929 continue;
4930 }
4931 } else {
4932 if (rword == RES_ELSE || rword == RES_ELIF) {
4933 /* "if <true> then ... ELSE/ELIF cmd":
4934 * skip cmd and all following ones */
4935 break;
4936 }
4937 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004938#endif
4939#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004940 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004941 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004942 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004943
4944 static const char encoded_dollar_at[] ALIGN1 = {
4945 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4946 }; /* encoded representation of "$@" */
4947 static const char *const encoded_dollar_at_argv[] = {
4948 encoded_dollar_at, NULL
4949 }; /* argv list with one element: "$@" */
4950 char **vals;
4951
4952 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004953 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004954 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004955 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004956 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004957 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004958 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004959 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004960 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004961 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004962 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004963 debug_print_strings("for_list made from", vals);
4964 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004965 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004966 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004967 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004968 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004969 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004970 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004971 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004972 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004973 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004974 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004975 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004976 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004977 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004978 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004979 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004980 if (rword == RES_IN) {
4981 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4982 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004983 if (rword == RES_DONE) {
4984 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004985 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004986#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004987#if ENABLE_HUSH_CASE
4988 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004989 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004990 continue;
4991 }
4992 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004993 char **argv;
4994
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004995 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4996 break;
4997 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004998 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004999 while (*argv) {
5000 char *pattern = expand_string_to_string(*argv);
5001 /* TODO: which FNM_xxx flags to use? */
5002 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
5003 free(pattern);
5004 if (cond_code == 0) { /* match! we will execute this branch */
5005 free(case_word); /* make future "word)" stop */
5006 case_word = NULL;
5007 break;
5008 }
5009 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005010 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005011 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005012 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005013 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005014 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005015 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005016 }
5017#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00005018 /* Just pressing <enter> in shell should check for jobs.
5019 * OTOH, in non-interactive shell this is useless
5020 * and only leads to extra job checks */
5021 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005022 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00005023 goto check_jobs_and_continue;
5024 continue;
5025 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005026
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005027 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00005028 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005029 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005030 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005031 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005032 {
5033 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005034#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00005035 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005036#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005037 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
5038 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00005039 /* We ran a builtin, function, or group.
5040 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005041 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005042 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005043 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005044 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005045#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005046 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005047 if (G.flag_break_continue) {
5048 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005049 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005050 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005051 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00005052 G.depth_break_continue--;
5053 if (G.depth_break_continue == 0)
5054 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005055 /* else: e.g. "continue 2" should *break* once, *then* continue */
5056 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005057 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005058 goto check_jobs_and_break;
5059 /* "continue": simulate end of loop */
5060 rword = RES_DONE;
5061 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005062 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005063#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00005064#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02005065 if (G.flag_return_in_progress == 1) {
5066 /* same as "goto check_jobs_and_break" */
5067 checkjobs(NULL);
5068 break;
5069 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00005070#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005071 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005072 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005073 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005074 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
5075 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005076 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005077#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00005078 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005079 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00005080#endif
Alexander Shishkinccb97712010-07-25 13:07:39 +02005081 /* Last command's pid goes to $! */
5082 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005083 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005084 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005085 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005086#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005087 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005088 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005089 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005090 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005091 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005092 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005093#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005094 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005095 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005096 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005097 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005098 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005099 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00005100 }
5101 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005102
5103 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00005104#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00005105 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005106 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00005107#endif
5108#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005109 /* Beware of "while false; true; do ..."! */
5110 if (pi->next && pi->next->res_word == RES_DO) {
5111 if (rword == RES_WHILE) {
5112 if (rcode) {
5113 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005114 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005115 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
5116 goto check_jobs_and_break;
5117 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00005118 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005119 if (rword == RES_UNTIL) {
5120 if (!rcode) {
5121 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005122 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005123 checkjobs(NULL);
5124 break;
5125 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005126 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005127 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005128#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00005129
5130 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00005131 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005132 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00005133
5134#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00005135 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00005136#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00005137#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005138 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00005139 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00005140 free(for_list);
5141#endif
5142#if ENABLE_HUSH_CASE
5143 free(case_word);
5144#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005145 debug_leave();
5146 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00005147 return rcode;
5148}
5149
Eric Andersen25f27032001-04-26 23:22:31 +00005150/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00005151static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00005152{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005153 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00005154 debug_printf_exec("run_and_free_list entered\n");
Denys Vlasenko202a2d12010-07-16 12:36:14 +02005155 if (!G.n_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005156 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00005157 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00005158 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005159 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00005160 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00005161 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005162 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00005163 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00005164 return rcode;
5165}
5166
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005167
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00005168static struct pipe *new_pipe(void)
5169{
Eric Andersen25f27032001-04-26 23:22:31 +00005170 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00005171 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005172 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005173 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00005174 return pi;
5175}
5176
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005177/* Command (member of a pipe) is complete, or we start a new pipe
5178 * if ctx->command is NULL.
5179 * No errors possible here.
5180 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005181static int done_command(struct parse_context *ctx)
5182{
5183 /* The command is really already in the pipe structure, so
5184 * advance the pipe counter and make a new, null command. */
5185 struct pipe *pi = ctx->pipe;
5186 struct command *command = ctx->command;
5187
5188 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005189 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005190 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005191 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005192 }
5193 pi->num_cmds++;
5194 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005195 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005196 } else {
5197 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
5198 }
5199
5200 /* Only real trickiness here is that the uncommitted
5201 * command structure is not counted in pi->num_cmds. */
5202 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005203 ctx->command = command = &pi->cmds[pi->num_cmds];
5204 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005205 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005206 return pi->num_cmds; /* used only for 0/nonzero check */
5207}
5208
5209static void done_pipe(struct parse_context *ctx, pipe_style type)
5210{
5211 int not_null;
5212
5213 debug_printf_parse("done_pipe entered, followup %d\n", type);
5214 /* Close previous command */
5215 not_null = done_command(ctx);
5216 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005217#if HAS_KEYWORDS
5218 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5219 ctx->ctx_inverted = 0;
5220 ctx->pipe->res_word = ctx->ctx_res_w;
5221#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005222
5223 /* Without this check, even just <enter> on command line generates
5224 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005225 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005226 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00005227#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005228 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00005229#endif
5230#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005231 || ctx->ctx_res_w == RES_DONE
5232 || ctx->ctx_res_w == RES_FOR
5233 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00005234#endif
5235#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005236 || ctx->ctx_res_w == RES_ESAC
5237#endif
5238 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005239 struct pipe *new_p;
5240 debug_printf_parse("done_pipe: adding new pipe: "
5241 "not_null:%d ctx->ctx_res_w:%d\n",
5242 not_null, ctx->ctx_res_w);
5243 new_p = new_pipe();
5244 ctx->pipe->next = new_p;
5245 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005246 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005247 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005248 * This is used to control execution.
5249 * RES_FOR and RES_IN are NOT sticky (needed to support
5250 * cases where variable or value happens to match a keyword):
5251 */
5252#if ENABLE_HUSH_LOOPS
5253 if (ctx->ctx_res_w == RES_FOR
5254 || ctx->ctx_res_w == RES_IN)
5255 ctx->ctx_res_w = RES_NONE;
5256#endif
5257#if ENABLE_HUSH_CASE
5258 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005259 ctx->ctx_res_w = RES_CASE_BODY;
5260 if (ctx->ctx_res_w == RES_CASE)
5261 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005262#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005263 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005264 /* Create the memory for command, roughly:
5265 * ctx->pipe->cmds = new struct command;
5266 * ctx->command = &ctx->pipe->cmds[0];
5267 */
5268 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005269 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005270 }
5271 debug_printf_parse("done_pipe return\n");
5272}
5273
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005274static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005275{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005276 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00005277 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005278 /* Create the memory for command, roughly:
5279 * ctx->pipe->cmds = new struct command;
5280 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005281 */
5282 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005283}
5284
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005285/* If a reserved word is found and processed, parse context is modified
5286 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00005287 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005288#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005289struct reserved_combo {
5290 char literal[6];
5291 unsigned char res;
5292 unsigned char assignment_flag;
5293 int flag;
5294};
5295enum {
5296 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005297# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005298 FLAG_IF = (1 << RES_IF ),
5299 FLAG_THEN = (1 << RES_THEN ),
5300 FLAG_ELIF = (1 << RES_ELIF ),
5301 FLAG_ELSE = (1 << RES_ELSE ),
5302 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005303# endif
5304# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005305 FLAG_FOR = (1 << RES_FOR ),
5306 FLAG_WHILE = (1 << RES_WHILE),
5307 FLAG_UNTIL = (1 << RES_UNTIL),
5308 FLAG_DO = (1 << RES_DO ),
5309 FLAG_DONE = (1 << RES_DONE ),
5310 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005311# endif
5312# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005313 FLAG_MATCH = (1 << RES_MATCH),
5314 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005315# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005316 FLAG_START = (1 << RES_XXXX ),
5317};
5318
5319static const struct reserved_combo* match_reserved_word(o_string *word)
5320{
Eric Andersen25f27032001-04-26 23:22:31 +00005321 /* Mostly a list of accepted follow-up reserved words.
5322 * FLAG_END means we are done with the sequence, and are ready
5323 * to turn the compound list into a command.
5324 * FLAG_START means the word must start a new compound list.
5325 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005326 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005327# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005328 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5329 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5330 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5331 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5332 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5333 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005334# endif
5335# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005336 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5337 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5338 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5339 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5340 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5341 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005342# endif
5343# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005344 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5345 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005346# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005347 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005348 const struct reserved_combo *r;
5349
5350 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5351 if (strcmp(word->data, r->literal) == 0)
5352 return r;
5353 }
5354 return NULL;
5355}
Denis Vlasenkobb929512009-04-16 10:59:40 +00005356/* Return 0: not a keyword, 1: keyword
5357 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005358static int reserved_word(o_string *word, struct parse_context *ctx)
5359{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005360# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005361 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005362 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005363 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005364# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005365 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005366
Denis Vlasenkobb929512009-04-16 10:59:40 +00005367 if (word->o_quoted)
5368 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005369 r = match_reserved_word(word);
5370 if (!r)
5371 return 0;
5372
5373 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005374# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005375 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5376 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005377 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005378 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005379# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005380 if (r->flag == 0) { /* '!' */
5381 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005382 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00005383 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00005384 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005385 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005386 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005387 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005388 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005389 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005390
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005391 old = xmalloc(sizeof(*old));
5392 debug_printf_parse("push stack %p\n", old);
5393 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005394 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005395 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005396 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005397 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005398 ctx->ctx_res_w = RES_SNTX;
5399 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005400 } else {
5401 /* "{...} fi" is ok. "{...} if" is not
5402 * Example:
5403 * if { echo foo; } then { echo bar; } fi */
5404 if (ctx->command->group)
5405 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005406 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00005407
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005408 ctx->ctx_res_w = r->res;
5409 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005410 word->o_assignment = r->assignment_flag;
5411
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005412 if (ctx->old_flag & FLAG_END) {
5413 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005414
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005415 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005416 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005417 old = ctx->stack;
5418 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005419 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005420# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005421 o_addstr(&old->as_string, ctx->as_string.data);
5422 o_free_unsafe(&ctx->as_string);
5423 old->command->group_as_string = xstrdup(old->as_string.data);
5424 debug_printf_parse("pop, remembering as:'%s'\n",
5425 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005426# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005427 *ctx = *old; /* physical copy */
5428 free(old);
5429 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005430 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005431}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005432#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00005433
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005434/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005435 * Normal return is 0. Syntax errors return 1.
5436 * Note: on return, word is reset, but not o_free'd!
5437 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005438static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005439{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005440 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00005441
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005442 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005443 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005444 debug_printf_parse("done_word return 0: true null, ignored\n");
5445 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005446 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005447
Eric Andersen25f27032001-04-26 23:22:31 +00005448 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005449 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5450 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005451 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5452 * "2.7 Redirection
5453 * ...the word that follows the redirection operator
5454 * shall be subjected to tilde expansion, parameter expansion,
5455 * command substitution, arithmetic expansion, and quote
5456 * removal. Pathname expansion shall not be performed
5457 * on the word by a non-interactive shell; an interactive
5458 * shell may perform it, but shall do so only when
5459 * the expansion would result in one word."
5460 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005461 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005462 /* Cater for >\file case:
5463 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5464 * Same with heredocs:
5465 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5466 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005467 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5468 unbackslash(ctx->pending_redirect->rd_filename);
5469 /* Is it <<"HEREDOC"? */
5470 if (word->o_quoted) {
5471 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5472 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005473 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005474 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005475 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00005476 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005477 /* If this word wasn't an assignment, next ones definitely
5478 * can't be assignments. Even if they look like ones. */
5479 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5480 && word->o_assignment != WORD_IS_KEYWORD
5481 ) {
5482 word->o_assignment = NOT_ASSIGNMENT;
5483 } else {
5484 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5485 command->assignment_cnt++;
5486 word->o_assignment = MAYBE_ASSIGNMENT;
5487 }
5488
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005489#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005490# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00005491 if (ctx->ctx_dsemicolon
5492 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5493 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00005494 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005495 /* ctx->ctx_res_w = RES_MATCH; */
5496 ctx->ctx_dsemicolon = 0;
5497 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005498# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005499 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005500# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005501 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5502 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005503# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005504# if ENABLE_HUSH_CASE
5505 && ctx->ctx_res_w != RES_CASE
5506# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005507 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005508 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005509 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005510 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005511 debug_printf_parse("done_word return %d\n",
5512 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005513 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005514 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005515# ifdef CMD_SINGLEWORD_NOGLOB_COND
5516 if (strcmp(word->data, "export") == 0
5517# if ENABLE_HUSH_LOCAL
5518 || strcmp(word->data, "local") == 0
5519# endif
5520 ) {
5521 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5522 } else
5523# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005524# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005525 if (strcmp(word->data, "[[") == 0) {
5526 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5527 }
5528 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005529# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005530 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005531#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00005532 if (command->group) {
5533 /* "{ echo foo; } echo bar" - bad */
5534 syntax_error_at(word->data);
5535 debug_printf_parse("done_word return 1: syntax error, "
5536 "groups and arglists don't mix\n");
5537 return 1;
5538 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005539 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00005540 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5541 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005542 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005543 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005544 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005545 char *p = word->data;
5546 while (p[0] == SPECIAL_VAR_SYMBOL
5547 && (p[1] & 0x7f) == '@'
5548 && p[2] == SPECIAL_VAR_SYMBOL
5549 ) {
5550 p += 3;
5551 }
5552 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005553 /* saw no "$@", or not only "$@" but some
5554 * real text is there too */
5555 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005556 * e.g. "", $empty"" etc to not disappear */
5557 o_addchr(word, SPECIAL_VAR_SYMBOL);
5558 o_addchr(word, SPECIAL_VAR_SYMBOL);
5559 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00005560 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005561 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005562 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005563 }
Eric Andersen25f27032001-04-26 23:22:31 +00005564
Denis Vlasenko06810332007-05-21 23:30:54 +00005565#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005566 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005567 if (word->o_quoted
5568 || !is_well_formed_var_name(command->argv[0], '\0')
5569 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005570 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005571 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005572 return 1;
5573 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005574 /* Force FOR to have just one word (variable name) */
5575 /* NB: basically, this makes hush see "for v in ..."
5576 * syntax as if it is "for v; in ...". FOR and IN become
5577 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005578 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005579 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005580#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005581#if ENABLE_HUSH_CASE
5582 /* Force CASE to have just one word */
5583 if (ctx->ctx_res_w == RES_CASE) {
5584 done_pipe(ctx, PIPE_SEQ);
5585 }
5586#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005587
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005588 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005589
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005590 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005591 return 0;
5592}
5593
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005594
5595/* Peek ahead in the input to find out if we have a "&n" construct,
5596 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005597 * Return:
5598 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5599 * REDIRFD_SYNTAX_ERR if syntax error,
5600 * REDIRFD_TO_FILE if no & was seen,
5601 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005602 */
5603#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005604#define parse_redir_right_fd(as_string, input) \
5605 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005606#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005607static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005608{
5609 int ch, d, ok;
5610
5611 ch = i_peek(input);
5612 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005613 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005614
5615 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005616 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005617 ch = i_peek(input);
5618 if (ch == '-') {
5619 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005620 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005621 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005622 }
5623 d = 0;
5624 ok = 0;
5625 while (ch != EOF && isdigit(ch)) {
5626 d = d*10 + (ch-'0');
5627 ok = 1;
5628 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005629 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005630 ch = i_peek(input);
5631 }
5632 if (ok) return d;
5633
5634//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5635
5636 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005637 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005638}
5639
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005640/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005641 */
5642static int parse_redirect(struct parse_context *ctx,
5643 int fd,
5644 redir_type style,
5645 struct in_str *input)
5646{
5647 struct command *command = ctx->command;
5648 struct redir_struct *redir;
5649 struct redir_struct **redirp;
5650 int dup_num;
5651
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005652 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005653 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005654 /* Check for a '>&1' type redirect */
5655 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5656 if (dup_num == REDIRFD_SYNTAX_ERR)
5657 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005658 } else {
5659 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005660 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005661 if (dup_num) { /* <<-... */
5662 ch = i_getch(input);
5663 nommu_addchr(&ctx->as_string, ch);
5664 ch = i_peek(input);
5665 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005666 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005667
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005668 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005669 int ch = i_peek(input);
5670 if (ch == '|') {
5671 /* >|FILE redirect ("clobbering" >).
5672 * Since we do not support "set -o noclobber" yet,
5673 * >| and > are the same for now. Just eat |.
5674 */
5675 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005676 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005677 }
5678 }
5679
5680 /* Create a new redir_struct and append it to the linked list */
5681 redirp = &command->redirects;
5682 while ((redir = *redirp) != NULL) {
5683 redirp = &(redir->next);
5684 }
5685 *redirp = redir = xzalloc(sizeof(*redir));
5686 /* redir->next = NULL; */
5687 /* redir->rd_filename = NULL; */
5688 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005689 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005690
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005691 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5692 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005693
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005694 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005695 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005696 /* Erik had a check here that the file descriptor in question
5697 * is legit; I postpone that to "run time"
5698 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005699 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5700 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005701 } else {
5702 /* Set ctx->pending_redirect, so we know what to do at the
5703 * end of the next parsed word. */
5704 ctx->pending_redirect = redir;
5705 }
5706 return 0;
5707}
5708
Eric Andersen25f27032001-04-26 23:22:31 +00005709/* If a redirect is immediately preceded by a number, that number is
5710 * supposed to tell which file descriptor to redirect. This routine
5711 * looks for such preceding numbers. In an ideal world this routine
5712 * needs to handle all the following classes of redirects...
5713 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5714 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5715 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5716 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005717 *
5718 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5719 * "2.7 Redirection
5720 * ... If n is quoted, the number shall not be recognized as part of
5721 * the redirection expression. For example:
5722 * echo \2>a
5723 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005724 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005725 *
5726 * A -1 return means no valid number was found,
5727 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005728 */
5729static int redirect_opt_num(o_string *o)
5730{
5731 int num;
5732
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005733 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005734 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005735 num = bb_strtou(o->data, NULL, 10);
5736 if (errno || num < 0)
5737 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005738 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005739 return num;
5740}
5741
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005742#if BB_MMU
5743#define fetch_till_str(as_string, input, word, skip_tabs) \
5744 fetch_till_str(input, word, skip_tabs)
5745#endif
5746static char *fetch_till_str(o_string *as_string,
5747 struct in_str *input,
5748 const char *word,
5749 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005750{
5751 o_string heredoc = NULL_O_STRING;
5752 int past_EOL = 0;
5753 int ch;
5754
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005755 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005756 while (1) {
5757 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005758 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005759 if (ch == '\n') {
5760 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5761 heredoc.data[past_EOL] = '\0';
5762 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5763 return heredoc.data;
5764 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005765 do {
5766 o_addchr(&heredoc, ch);
5767 past_EOL = heredoc.length;
5768 jump_in:
5769 do {
5770 ch = i_getch(input);
5771 nommu_addchr(as_string, ch);
5772 } while (skip_tabs && ch == '\t');
5773 } while (ch == '\n');
5774 }
5775 if (ch == EOF) {
5776 o_free_unsafe(&heredoc);
5777 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005778 }
5779 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005780 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005781 }
5782}
5783
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005784/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5785 * and load them all. There should be exactly heredoc_cnt of them.
5786 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005787static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5788{
5789 struct pipe *pi = ctx->list_head;
5790
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005791 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005792 int i;
5793 struct command *cmd = pi->cmds;
5794
5795 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5796 pi->num_cmds,
5797 cmd->argv ? cmd->argv[0] : "NONE");
5798 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005799 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005800
5801 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5802 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005803 while (redir) {
5804 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005805 char *p;
5806
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005807 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005808 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005809 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005810 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005811 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005812 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005813 return 1;
5814 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005815 free(redir->rd_filename);
5816 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005817 heredoc_cnt--;
5818 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005819 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005820 }
5821 cmd++;
5822 }
5823 pi = pi->next;
5824 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005825#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005826 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005827 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005828 bb_error_msg_and_die("heredoc BUG 2");
5829#endif
5830 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005831}
5832
5833
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005834#if ENABLE_HUSH_TICK
Denys Vlasenko647553a2009-11-15 19:58:19 +01005835static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
Eric Andersen25f27032001-04-26 23:22:31 +00005836{
Denys Vlasenko647553a2009-11-15 19:58:19 +01005837 pid_t pid;
5838 int channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005839# if !BB_MMU
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01005840 char **to_free = NULL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005841# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005842
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005843 xpipe(channel);
Pascal Bellard926031b2010-07-04 15:32:38 +02005844 pid = BB_MMU ? xfork() : xvfork();
Denis Vlasenko05743d72008-02-10 12:10:08 +00005845 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005846 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005847 /* Process substitution is not considered to be usual
5848 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005849 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5850 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005851 bb_signals(0
5852 + (1 << SIGTSTP)
5853 + (1 << SIGTTIN)
5854 + (1 << SIGTTOU)
5855 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005856 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005857 close(channel[0]); /* NB: close _first_, then move fd! */
5858 xmove_fd(channel[1], 1);
5859 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005860 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005861 /* Awful hack for `trap` or $(trap).
5862 *
5863 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5864 * contains an example where "trap" is executed in a subshell:
5865 *
5866 * save_traps=$(trap)
5867 * ...
5868 * eval "$save_traps"
5869 *
5870 * Standard does not say that "trap" in subshell shall print
5871 * parent shell's traps. It only says that its output
5872 * must have suitable form, but then, in the above example
5873 * (which is not supposed to be normative), it implies that.
5874 *
5875 * bash (and probably other shell) does implement it
5876 * (traps are reset to defaults, but "trap" still shows them),
5877 * but as a result, "trap" logic is hopelessly messed up:
5878 *
5879 * # trap
5880 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5881 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5882 * # true | trap <--- trap is in subshell - no output (ditto)
5883 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5884 * trap -- 'echo Ho' SIGWINCH
5885 * # echo `(trap)` <--- in subshell in subshell - output
5886 * trap -- 'echo Ho' SIGWINCH
5887 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5888 * trap -- 'echo Ho' SIGWINCH
5889 *
5890 * The rules when to forget and when to not forget traps
5891 * get really complex and nonsensical.
5892 *
5893 * Our solution: ONLY bare $(trap) or `trap` is special.
5894 */
5895 s = skip_whitespace(s);
5896 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5897 {
5898 static const char *const argv[] = { NULL, NULL };
5899 builtin_trap((char**)argv);
5900 exit(0); /* not _exit() - we need to fflush */
5901 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005902# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005903 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005904 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005905 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005906# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005907 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005908 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5909 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005910 * echo OK
5911 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005912 re_execute_shell(&to_free,
5913 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005914 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005915 G.global_argv + 1,
5916 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005917# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005918 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005919
5920 /* parent */
Denys Vlasenko647553a2009-11-15 19:58:19 +01005921 *pid_p = pid;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005922# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005923 G.count_SIGCHLD++;
5924//bb_error_msg("[%d] fork in generate_stream_from_string: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005925# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005926 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005927# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005928 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005929# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005930 close(channel[1]);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005931 close_on_exec_on(channel[0]);
5932 return xfdopen_for_read(channel[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00005933}
5934
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005935/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005936static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005937{
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005938 FILE *fp;
Eric Andersen25f27032001-04-26 23:22:31 +00005939 struct in_str pipe_str;
Denys Vlasenko647553a2009-11-15 19:58:19 +01005940 pid_t pid;
5941 int status, ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005942
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005943 fp = generate_stream_from_string(s, &pid);
Eric Andersen25f27032001-04-26 23:22:31 +00005944
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005945 /* Now send results of command back into original context */
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005946 setup_file_in_str(&pipe_str, fp);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005947 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005948 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005949 if (ch == '\n') {
5950 eol_cnt++;
5951 continue;
5952 }
5953 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005954 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005955 eol_cnt--;
5956 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005957 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005958 }
5959
Denys Vlasenko647553a2009-11-15 19:58:19 +01005960 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005961 fclose(fp);
Denys Vlasenko647553a2009-11-15 19:58:19 +01005962 /* We need to extract exitcode. Test case
5963 * "true; echo `sleep 1; false` $?"
5964 * should print 1 */
5965 safe_waitpid(pid, &status, 0);
5966 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5967 return WEXITSTATUS(status);
Eric Andersen25f27032001-04-26 23:22:31 +00005968}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005969#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005970
Denys Vlasenkoc2704542009-11-20 19:14:19 +01005971#if !ENABLE_HUSH_FUNCTIONS
5972#define parse_group(dest, ctx, input, ch) \
5973 parse_group(ctx, input, ch)
5974#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005975static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005976 struct in_str *input, int ch)
5977{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005978 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005979 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005980 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005981 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005982 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005983 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005984
5985 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005986#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005987 if (ch == '(' && !dest->o_quoted) {
5988 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005989 if (done_word(dest, ctx))
5990 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005991 if (!command->argv)
5992 goto skip; /* (... */
5993 if (command->argv[1]) { /* word word ... (... */
5994 syntax_error_unexpected_ch('(');
5995 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005996 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005997 /* it is "word(..." or "word (..." */
5998 do
5999 ch = i_getch(input);
6000 while (ch == ' ' || ch == '\t');
6001 if (ch != ')') {
6002 syntax_error_unexpected_ch(ch);
6003 return 1;
6004 }
6005 nommu_addchr(&ctx->as_string, ch);
6006 do
6007 ch = i_getch(input);
6008 while (ch == ' ' || ch == '\t' || ch == '\n');
6009 if (ch != '{') {
6010 syntax_error_unexpected_ch(ch);
6011 return 1;
6012 }
6013 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02006014 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006015 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00006016 }
6017#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006018
6019#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006020 if (command->argv /* word [word]{... */
6021 || dest->length /* word{... */
6022 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006023 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006024 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006025 debug_printf_parse("parse_group return 1: "
6026 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006027 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006028 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006029#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006030
6031#if ENABLE_HUSH_FUNCTIONS
6032 skip:
6033#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006034 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006035 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00006036 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02006037 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00006038 } else {
6039 /* bash does not allow "{echo...", requires whitespace */
6040 ch = i_getch(input);
6041 if (ch != ' ' && ch != '\t' && ch != '\n') {
6042 syntax_error_unexpected_ch(ch);
6043 return 1;
6044 }
6045 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006046 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006047
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006048 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006049#if BB_MMU
6050# define as_string NULL
6051#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006052 char *as_string = NULL;
6053#endif
6054 pipe_list = parse_stream(&as_string, input, endch);
6055#if !BB_MMU
6056 if (as_string)
6057 o_addstr(&ctx->as_string, as_string);
6058#endif
6059 /* empty ()/{} or parse error? */
6060 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00006061 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006062 if (!BB_MMU)
6063 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006064 debug_printf_parse("parse_group return 1: "
6065 "parse_stream returned %p\n", pipe_list);
6066 return 1;
6067 }
6068 command->group = pipe_list;
6069#if !BB_MMU
6070 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
6071 command->group_as_string = as_string;
6072 debug_printf_parse("end of group, remembering as:'%s'\n",
6073 command->group_as_string);
6074#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006075#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006076 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006077 debug_printf_parse("parse_group return 0\n");
6078 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006079 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00006080}
6081
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006082#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006083/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006084static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006085/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006086static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006087{
6088 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006089 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006090 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006091 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006092 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006093 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006094 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006095 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006096 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006097 }
6098}
6099/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006100static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006101{
6102 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006103 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006104 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006105 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006106 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006107 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006108 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006109 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006110 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006111 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006112 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006113 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006114 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006115 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006116 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006117 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006118 continue;
6119 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00006120 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006121 }
6122}
6123/* Process `cmd` - copy contents until "`" is seen. Complicated by
6124 * \` quoting.
6125 * "Within the backquoted style of command substitution, backslash
6126 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
6127 * The search for the matching backquote shall be satisfied by the first
6128 * backquote found without a preceding backslash; during this search,
6129 * if a non-escaped backquote is encountered within a shell comment,
6130 * a here-document, an embedded command substitution of the $(command)
6131 * form, or a quoted string, undefined results occur. A single-quoted
6132 * or double-quoted string that begins, but does not end, within the
6133 * "`...`" sequence produces undefined results."
6134 * Example Output
6135 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
6136 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006137static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006138{
6139 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006140 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006141 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006142 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006143 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006144 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006145 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006146 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006147 if (ch == '\\') {
6148 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006149 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006150 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006151 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006152 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006153 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006154 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006155 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006156 ch = ch2;
6157 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006158 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006159 }
6160}
6161/* Process $(cmd) - copy contents until ")" is seen. Complicated by
6162 * quoting and nested ()s.
6163 * "With the $(command) style of command substitution, all characters
6164 * following the open parenthesis to the matching closing parenthesis
6165 * constitute the command. Any valid shell script can be used for command,
6166 * except a script consisting solely of redirections which produces
6167 * unspecified results."
6168 * Example Output
6169 * echo $(echo '(TEST)' BEST) (TEST) BEST
6170 * echo $(echo 'TEST)' BEST) TEST) BEST
6171 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02006172 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006173 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006174 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006175 * In bash compat mode, it needs to also be able to stop on '}' or ':'
6176 * for ${var:N[:M]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006177 */
Denys Vlasenko74369502010-05-21 19:52:01 +02006178#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006179static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006180{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006181 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02006182 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006183# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006184 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006185# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006186 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
6187
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006188 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006189 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006190 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006191 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006192 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006193 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006194 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006195 if (!dbl)
6196 break;
6197 /* we look for closing )) of $((EXPR)) */
6198 if (i_peek(input) == end_ch) {
6199 i_getch(input); /* eat second ')' */
6200 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00006201 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006202 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006203 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006204 if (ch == '(' || ch == '{') {
6205 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006206 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006207 o_addchr(dest, ch);
6208 continue;
6209 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006210 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006211 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006212 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006213 continue;
6214 }
6215 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006216 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006217 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006218 continue;
6219 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006220 if (ch == '`') {
6221 add_till_backquote(dest, input);
6222 o_addchr(dest, ch);
6223 continue;
6224 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006225 if (ch == '\\') {
6226 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006227 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006228 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006229 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006230 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006231 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006232 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006233 continue;
6234 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006235 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006236 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006237}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006238#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006239
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006240/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006241#if BB_MMU
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006242#define parse_dollar(as_string, dest, input) \
6243 parse_dollar(dest, input)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006244#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006245#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006246static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006247 o_string *dest,
6248 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00006249{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006250 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006251 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006252
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006253 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00006254 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006255 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006256 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00006257 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006258 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006259 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006260 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006261 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00006262 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006263 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006264 if (!isalnum(ch) && ch != '_')
6265 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006266 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006267 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006268 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006269 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006270 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006271 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006272 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006273 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006274 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006275 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006276 o_addchr(dest, ch | quote_mask);
6277 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006278 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006279 case '$': /* pid */
6280 case '!': /* last bg pid */
6281 case '?': /* last exit code */
6282 case '#': /* number of args */
6283 case '*': /* args */
6284 case '@': /* args */
6285 goto make_one_char_var;
6286 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04006287 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6288
Denys Vlasenko74369502010-05-21 19:52:01 +02006289 ch = i_getch(input); /* eat '{' */
6290 nommu_addchr(as_string, ch);
6291
6292 ch = i_getch(input); /* first char after '{' */
6293 nommu_addchr(as_string, ch);
6294 /* It should be ${?}, or ${#var},
6295 * or even ${?+subst} - operator acting on a special variable,
6296 * or the beginning of variable name.
6297 */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02006298 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
Denys Vlasenko74369502010-05-21 19:52:01 +02006299 bad_dollar_syntax:
6300 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006301 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02006302 return 1;
6303 }
6304 ch |= quote_mask;
6305
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006306 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02006307 * However, this regresses some of our testsuite cases
6308 * which check invalid constructs like ${%}.
6309 * Oh well... let's check that the var name part is fine... */
6310
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006311 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006312 unsigned pos;
6313
Denys Vlasenko74369502010-05-21 19:52:01 +02006314 o_addchr(dest, ch);
6315 debug_printf_parse(": '%c'\n", ch);
6316
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006317 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006318 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02006319 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00006320 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00006321
Denys Vlasenko74369502010-05-21 19:52:01 +02006322 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006323 unsigned end_ch;
6324 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006325 /* handle parameter expansions
6326 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6327 */
Denys Vlasenko74369502010-05-21 19:52:01 +02006328 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6329 goto bad_dollar_syntax;
Denys Vlasenko74369502010-05-21 19:52:01 +02006330 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006331
6332 /* Eat everything until closing '}' (or ':') */
6333 end_ch = '}';
6334 if (ENABLE_HUSH_BASH_COMPAT
6335 && ch == ':'
6336 && !strchr("%#:-=+?"+3, i_peek(input))
6337 ) {
6338 /* It's ${var:N[:M]} thing */
6339 end_ch = '}' * 0x100 + ':';
6340 }
6341 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006342 if (!BB_MMU)
6343 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006344#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006345 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006346#else
6347#error Simple code to only allow ${var} is not implemented
6348#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006349 if (as_string) {
6350 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006351 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006352 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006353
6354 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6355 /* close the first block: */
6356 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6357 /* while parsing N from ${var:N[:M]}... */
6358 if ((end_ch & 0xff) == last_ch) {
6359 /* ...got ':' - parse the rest */
6360 end_ch = '}';
6361 goto again;
6362 }
6363 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6364 o_addstr(dest, "999999999");
6365 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006366 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006367 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006368 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006369 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6370 break;
6371 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006372#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006373 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006374 unsigned pos;
6375
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006376 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006377 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006378# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006379 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006380 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006381 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006382 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6383 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006384 if (!BB_MMU)
6385 pos = dest->length;
6386 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006387 if (as_string) {
6388 o_addstr(as_string, dest->data + pos);
6389 o_addchr(as_string, ')');
6390 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006391 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006392 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006393 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006394 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006395# endif
6396# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006397 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6398 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006399 if (!BB_MMU)
6400 pos = dest->length;
6401 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006402 if (as_string) {
6403 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006404 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006405 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006406 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006407# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006408 break;
6409 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006410#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006411 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006412 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006413 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006414 ch = i_peek(input);
6415 if (isalnum(ch)) { /* it's $_name or $_123 */
6416 ch = '_';
6417 goto make_var;
6418 }
6419 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02006420 /* TODO: $_ and $-: */
6421 /* $_ Shell or shell script name; or last argument of last command
6422 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6423 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006424 /* $- Option flags set by set builtin or shell options (-i etc) */
6425 default:
6426 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00006427 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006428 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00006429 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006430#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00006431}
6432
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006433#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006434#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006435 parse_stream_dquoted(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006436#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006437#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006438static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006439 o_string *dest,
6440 struct in_str *input,
6441 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006442{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006443 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006444 int next;
6445
6446 again:
6447 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006448 if (ch != EOF)
6449 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006450 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006451 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006452 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006453 debug_printf_parse("parse_stream_dquoted return 0\n");
6454 return 0;
6455 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006456 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006457 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006458 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006459 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006460 }
6461 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006462 if (ch != '\n') {
6463 next = i_peek(input);
6464 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006465 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006466 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006467 if (ch == '\\') {
6468 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006469 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006470 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006471 }
6472 /* bash:
6473 * "The backslash retains its special meaning [in "..."]
6474 * only when followed by one of the following characters:
6475 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006476 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006477 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006478 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00006479 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006480 if (ch != '\n') {
6481 o_addqchr(dest, ch);
6482 nommu_addchr(as_string, ch);
6483 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006484 } else {
6485 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00006486 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006487 }
6488 goto again;
6489 }
6490 if (ch == '$') {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006491 if (parse_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006492 debug_printf_parse("parse_stream_dquoted return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006493 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006494 return 1;
6495 }
6496 goto again;
6497 }
6498#if ENABLE_HUSH_TICK
6499 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006500 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006501 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6502 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006503 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006504 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6505 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00006506 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006507 }
6508#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00006509 o_addQchr(dest, ch);
6510 if (ch == '='
6511 && (dest->o_assignment == MAYBE_ASSIGNMENT
6512 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006513 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00006514 ) {
6515 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6516 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006517 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006518#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006519}
6520
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006521/*
6522 * Scan input until EOF or end_trigger char.
6523 * Return a list of pipes to execute, or NULL on EOF
6524 * or if end_trigger character is met.
6525 * On syntax error, exit is shell is not interactive,
6526 * reset parsing machinery and start parsing anew,
6527 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006528 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006529static struct pipe *parse_stream(char **pstring,
6530 struct in_str *input,
6531 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006532{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006533 struct parse_context ctx;
6534 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006535 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006536 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00006537
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006538 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00006539 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006540 * found. When recursing, quote state is passed in via dest->o_escape.
6541 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006542 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02006543 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006544 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006545
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006546 /* If very first arg is "" or '', dest.data may end up NULL.
6547 * Preventing this: */
6548 o_addchr(&dest, '\0');
6549 dest.length = 0;
6550
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006551 G.ifs = get_local_var_value("IFS");
6552 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01006553 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006554
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006555 reset:
6556#if ENABLE_HUSH_INTERACTIVE
6557 input->promptmode = 0; /* PS1 */
6558#endif
6559 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6560 initialize_context(&ctx);
6561 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006562 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006563 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006564 const char *is_ifs;
6565 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006566 int ch;
6567 int next;
6568 int redir_fd;
6569 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006570
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006571 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006572 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006573 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006574 goto parse_error;
6575 }
6576 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006577 is_in_dquote = 0;
6578 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006579 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006580 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6581 ch, ch, dest.o_escape);
6582 if (ch == EOF) {
6583 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006584
6585 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006586 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006587 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006588 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006589 /* end_trigger == '}' case errors out earlier,
6590 * checking only ')' */
6591 if (end_trigger == ')') {
6592 syntax_error_unterm_ch('('); /* exits */
6593 /* goto parse_error; */
6594 }
6595
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006596 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006597 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006598 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006599 o_free(&dest);
6600 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006601 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006602 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006603 /* (this makes bare "&" cmd a no-op.
6604 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006605 if (pi->num_cmds == 0
6606 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6607 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006608 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006609 pi = NULL;
6610 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006611#if !BB_MMU
6612 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6613 if (pstring)
6614 *pstring = ctx.as_string.data;
6615 else
6616 o_free_unsafe(&ctx.as_string);
6617#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006618 debug_leave();
6619 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006620 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006621 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006622 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006623
6624 next = '\0';
6625 if (ch != '\n')
6626 next = i_peek(input);
6627
6628 is_special = "{}<>;&|()#'" /* special outside of "str" */
6629 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6630 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02006631 if (ctx.command->argv /* word [word]{... - non-special */
6632 || dest.length /* word{... - non-special */
6633 || dest.o_quoted /* ""{... - non-special */
6634 || (next != ';' /* }; - special */
6635 && next != ')' /* }) - special */
6636 && next != '&' /* }& and }&& ... - special */
6637 && next != '|' /* }|| ... - special */
6638 && !strchr(G.ifs, next) /* {word - non-special */
6639 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006640 ) {
6641 /* They are not special, skip "{}" */
6642 is_special += 2;
6643 }
6644 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006645 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006646
6647 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006648 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006649 o_addQchr(&dest, ch);
6650 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6651 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00006652 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006653 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00006654 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006655 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006656 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006657 continue;
6658 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00006659
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006660 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006661 if (done_word(&dest, &ctx)) {
6662 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00006663 }
Denis Vlasenko37181682009-04-03 03:19:15 +00006664 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00006665#if ENABLE_HUSH_CASE
6666 /* "case ... in <newline> word) ..." -
6667 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006668 if (ctx.command->argv == NULL
6669 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00006670 ) {
6671 continue;
6672 }
6673#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006674 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006675 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006676 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6677 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006678 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006679 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006680 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006681 heredoc_cnt = 0;
6682 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006683 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006684 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006685 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006686 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006687 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006688 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006689
6690 /* "cmd}" or "cmd }..." without semicolon or &:
6691 * } is an ordinary char in this case, even inside { cmd; }
6692 * Pathological example: { ""}; } should exec "}" cmd
6693 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006694 if (ch == '}') {
6695 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6696 || dest.length != 0 /* word} */
6697 || dest.o_quoted /* ""} */
6698 ) {
6699 goto ordinary_char;
6700 }
6701 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6702 goto skip_end_trigger;
6703 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006704 }
6705
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006706 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006707 && (ch != ';' || heredoc_cnt == 0)
6708#if ENABLE_HUSH_CASE
6709 && (ch != ')'
6710 || ctx.ctx_res_w != RES_MATCH
6711 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6712 )
6713#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006714 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006715 if (heredoc_cnt) {
6716 /* This is technically valid:
6717 * { cat <<HERE; }; echo Ok
6718 * heredoc
6719 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006720 * HERE
6721 * but we don't support this.
6722 * We require heredoc to be in enclosing {}/(),
6723 * if any.
6724 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006725 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006726 goto parse_error;
6727 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006728 if (done_word(&dest, &ctx)) {
6729 goto parse_error;
6730 }
6731 done_pipe(&ctx, PIPE_SEQ);
6732 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006733 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006734 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006735 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006736 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006737 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006738#if !BB_MMU
6739 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6740 if (pstring)
6741 *pstring = ctx.as_string.data;
6742 else
6743 o_free_unsafe(&ctx.as_string);
6744#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006745 debug_leave();
6746 debug_printf_parse("parse_stream return %p: "
6747 "end_trigger char found\n",
6748 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006749 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006750 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006751 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006752 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006753 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006754 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006755
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006756 /* Catch <, > before deciding whether this word is
6757 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6758 switch (ch) {
6759 case '>':
6760 redir_fd = redirect_opt_num(&dest);
6761 if (done_word(&dest, &ctx)) {
6762 goto parse_error;
6763 }
6764 redir_style = REDIRECT_OVERWRITE;
6765 if (next == '>') {
6766 redir_style = REDIRECT_APPEND;
6767 ch = i_getch(input);
6768 nommu_addchr(&ctx.as_string, ch);
6769 }
6770#if 0
6771 else if (next == '(') {
6772 syntax_error(">(process) not supported");
6773 goto parse_error;
6774 }
6775#endif
6776 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6777 goto parse_error;
6778 continue; /* back to top of while (1) */
6779 case '<':
6780 redir_fd = redirect_opt_num(&dest);
6781 if (done_word(&dest, &ctx)) {
6782 goto parse_error;
6783 }
6784 redir_style = REDIRECT_INPUT;
6785 if (next == '<') {
6786 redir_style = REDIRECT_HEREDOC;
6787 heredoc_cnt++;
6788 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6789 ch = i_getch(input);
6790 nommu_addchr(&ctx.as_string, ch);
6791 } else if (next == '>') {
6792 redir_style = REDIRECT_IO;
6793 ch = i_getch(input);
6794 nommu_addchr(&ctx.as_string, ch);
6795 }
6796#if 0
6797 else if (next == '(') {
6798 syntax_error("<(process) not supported");
6799 goto parse_error;
6800 }
6801#endif
6802 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6803 goto parse_error;
6804 continue; /* back to top of while (1) */
6805 }
6806
6807 if (dest.o_assignment == MAYBE_ASSIGNMENT
6808 /* check that we are not in word in "a=1 2>word b=1": */
6809 && !ctx.pending_redirect
6810 ) {
6811 /* ch is a special char and thus this word
6812 * cannot be an assignment */
6813 dest.o_assignment = NOT_ASSIGNMENT;
6814 }
6815
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006816 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6817
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006818 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006819 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006820 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006821 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006822 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006823 if (ch == EOF || ch == '\n')
6824 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006825 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006826 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006827 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006828 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006829 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006830 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006831 }
6832 break;
6833 case '\\':
6834 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006835 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006836 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006837 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006838 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006839 if (ch != '\n') {
6840 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006841 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006842 o_addchr(&dest, ch);
6843 nommu_addchr(&ctx.as_string, ch);
6844 /* Example: echo Hello \2>file
6845 * we need to know that word 2 is quoted */
6846 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006847 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006848#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006849 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006850 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6851 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006852 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006853#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006854 break;
6855 case '$':
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006856 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006857 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006858 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006859 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006860 }
Eric Andersen25f27032001-04-26 23:22:31 +00006861 break;
6862 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006863 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006864 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006865 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006866 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006867 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006868 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006869 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006870 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006871 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006872 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006873 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006874 }
Eric Andersen25f27032001-04-26 23:22:31 +00006875 break;
6876 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006877 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006878 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006879 if (dest.o_assignment == NOT_ASSIGNMENT)
6880 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006881 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006882#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006883 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006884 unsigned pos;
6885
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006886 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6887 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006888 pos = dest.length;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006889 add_till_backquote(&dest, input);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006890# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006891 o_addstr(&ctx.as_string, dest.data + pos);
6892 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006893# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006894 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6895 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006896 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006897 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006898#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006899 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006900#if ENABLE_HUSH_CASE
6901 case_semi:
6902#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006903 if (done_word(&dest, &ctx)) {
6904 goto parse_error;
6905 }
6906 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006907#if ENABLE_HUSH_CASE
6908 /* Eat multiple semicolons, detect
6909 * whether it means something special */
6910 while (1) {
6911 ch = i_peek(input);
6912 if (ch != ';')
6913 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006914 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006915 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006916 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006917 ctx.ctx_dsemicolon = 1;
6918 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006919 break;
6920 }
6921 }
6922#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006923 new_cmd:
6924 /* We just finished a cmd. New one may start
6925 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006926 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006927 break;
6928 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006929 if (done_word(&dest, &ctx)) {
6930 goto parse_error;
6931 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006932 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006933 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006934 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006935 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006936 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006937 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006938 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006939 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006940 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006941 if (done_word(&dest, &ctx)) {
6942 goto parse_error;
6943 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006944#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006945 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006946 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006947#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006948 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006949 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006950 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006951 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006952 } else {
6953 /* we could pick up a file descriptor choice here
6954 * with redirect_opt_num(), but bash doesn't do it.
6955 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006956 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006957#if !BB_MMU
6958 o_reset_to_empty_unquoted(&ctx.as_string);
6959#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006960 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006961 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006962 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006963#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006964 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006965 if (ctx.ctx_res_w == RES_MATCH
6966 && ctx.command->argv == NULL /* not (word|(... */
6967 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006968 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006969 ) {
6970 continue;
6971 }
6972#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006973 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006974 if (parse_group(&dest, &ctx, input, ch) != 0) {
6975 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006976 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006977 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006978 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006979#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006980 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006981 goto case_semi;
6982#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006983 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006984 /* proper use of this character is caught by end_trigger:
6985 * if we see {, we call parse_group(..., end_trigger='}')
6986 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006987 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006988 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006989 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006990 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006991 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006992 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006993 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006994
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006995 parse_error:
6996 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006997 struct parse_context *pctx;
6998 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006999
7000 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02007001 * Sample for finding leaks on syntax error recovery path.
7002 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007003 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00007004 * Samples to catch leaks at execution:
7005 * while if (true | {true;}); then echo ok; fi; do break; done
7006 * 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 +00007007 */
7008 pctx = &ctx;
7009 do {
7010 /* Update pipe/command counts,
7011 * otherwise freeing may miss some */
7012 done_pipe(pctx, PIPE_SEQ);
7013 debug_printf_clean("freeing list %p from ctx %p\n",
7014 pctx->list_head, pctx);
7015 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00007016 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007017 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007018#if !BB_MMU
7019 o_free_unsafe(&pctx->as_string);
7020#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007021 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007022 if (pctx != &ctx) {
7023 free(pctx);
7024 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007025 IF_HAS_KEYWORDS(pctx = p2;)
7026 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007027 /* Free text, clear all dest fields */
7028 o_free(&dest);
7029 /* If we are not in top-level parse, we return,
7030 * our caller will propagate error.
7031 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007032 if (end_trigger != ';') {
7033#if !BB_MMU
7034 if (pstring)
7035 *pstring = NULL;
7036#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00007037 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007038 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007039 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007040 /* Discard cached input, force prompt */
7041 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007042 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007043 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00007044 }
Eric Andersen25f27032001-04-26 23:22:31 +00007045}
7046
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007047/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007048 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7049 * end_trigger controls how often we stop parsing
7050 * NUL: parse all, execute, return
7051 * ';': parse till ';' or newline, execute, repeat till EOF
7052 */
7053static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007054{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007055 /* Why we need empty flag?
7056 * An obscure corner case "false; ``; echo $?":
7057 * empty command in `` should still set $? to 0.
7058 * But we can't just set $? to 0 at the start,
7059 * this breaks "false; echo `echo $?`" case.
7060 */
7061 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007062 while (1) {
7063 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007064
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007065 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007066 if (!pipe_list) { /* EOF */
7067 if (empty)
7068 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007069 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007070 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007071 debug_print_tree(pipe_list, 0);
7072 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7073 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007074 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007075 }
Eric Andersen25f27032001-04-26 23:22:31 +00007076}
7077
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007078static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007079{
7080 struct in_str input;
7081 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007082 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00007083}
7084
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007085static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00007086{
Eric Andersen25f27032001-04-26 23:22:31 +00007087 struct in_str input;
7088 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007089 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00007090}
7091
Denis Vlasenkof9375282009-04-05 19:13:39 +00007092/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007093static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007094{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007095 unsigned sig;
7096 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007097 sigset_t old_blocked_set;
7098
7099 if (!G.inherited_set_is_saved) {
7100 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7101 G.inherited_set = G.blocked_set;
7102 }
7103 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007104
Denis Vlasenkof9375282009-04-05 19:13:39 +00007105 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007106 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007107 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007108 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007109 mask |= SPECIAL_JOB_SIGS;
7110 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007111 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007112
Denis Vlasenkof9375282009-04-05 19:13:39 +00007113 sig = 0;
7114 while (mask) {
7115 if (mask & 1)
7116 sigaddset(&G.blocked_set, sig);
7117 mask >>= 1;
7118 sig++;
7119 }
7120 sigdelset(&G.blocked_set, SIGCHLD);
7121
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007122 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7123 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7124
Denis Vlasenkof9375282009-04-05 19:13:39 +00007125 /* POSIX allows shell to re-enable SIGCHLD
7126 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007127#if ENABLE_HUSH_FAST
7128 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007129 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007130 signal(SIGCHLD, SIGCHLD_handler);
7131#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007132 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007133 signal(SIGCHLD, SIG_DFL);
7134#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007135
7136 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007137}
7138
7139#if ENABLE_HUSH_JOB
7140/* helper */
7141static void maybe_set_to_sigexit(int sig)
7142{
7143 void (*handler)(int);
7144 /* non_DFL_mask'ed signals are, well, masked,
7145 * no need to set handler for them.
7146 */
7147 if (!((G.non_DFL_mask >> sig) & 1)) {
7148 handler = signal(sig, sigexit);
7149 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7150 signal(sig, handler);
7151 }
7152}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007153/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007154static void set_fatal_handlers(void)
7155{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007156 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007157 if (HUSH_DEBUG) {
7158 maybe_set_to_sigexit(SIGILL );
7159 maybe_set_to_sigexit(SIGFPE );
7160 maybe_set_to_sigexit(SIGBUS );
7161 maybe_set_to_sigexit(SIGSEGV);
7162 maybe_set_to_sigexit(SIGTRAP);
7163 } /* else: hush is perfect. what SEGV? */
7164 maybe_set_to_sigexit(SIGABRT);
7165 /* bash 3.2 seems to handle these just like 'fatal' ones */
7166 maybe_set_to_sigexit(SIGPIPE);
7167 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007168 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007169 * if we aren't interactive... but in this case
7170 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007171 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007172 /*maybe_set_to_sigexit(SIGTERM);*/
7173 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007174}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007175#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007176
Denis Vlasenkod5762932009-03-31 11:22:57 +00007177static int set_mode(const char cstate, const char mode)
7178{
7179 int state = (cstate == '-' ? 1 : 0);
7180 switch (mode) {
Denys Vlasenko202a2d12010-07-16 12:36:14 +02007181 case 'n': G.n_mode = state; break;
7182 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007183 default: return EXIT_FAILURE;
7184 }
7185 return EXIT_SUCCESS;
7186}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007187
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007188int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007189int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007190{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007191 static const struct variable const_shell_ver = {
7192 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00007193 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007194 .max_len = 1, /* 0 can provoke free(name) */
7195 .flg_export = 1,
7196 .flg_read_only = 1,
7197 };
Eric Andersen25f27032001-04-26 23:22:31 +00007198 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007199 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007200 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007201 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00007202
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007203 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007204 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007205 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007206#if !BB_MMU
7207 G.argv0_for_re_execing = argv[0];
7208#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007209 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007210 G.shell_ver = const_shell_ver; /* copying struct here */
7211 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007212 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007213 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7214 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007215 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007216 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007217 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007218 if (e) while (*e) {
7219 char *value = strchr(*e, '=');
7220 if (value) { /* paranoia */
7221 cur_var->next = xzalloc(sizeof(*cur_var));
7222 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007223 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007224 cur_var->max_len = strlen(*e);
7225 cur_var->flg_export = 1;
7226 }
7227 e++;
7228 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007229 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007230 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007231 putenv((char *)hush_version_str);
7232
7233 /* Export PWD */
7234 set_pwd_var(/*exp:*/ 1);
7235 /* bash also exports SHLVL and _,
7236 * and sets (but doesn't export) the following variables:
7237 * BASH=/bin/bash
7238 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7239 * BASH_VERSION='3.2.0(1)-release'
7240 * HOSTTYPE=i386
7241 * MACHTYPE=i386-pc-linux-gnu
7242 * OSTYPE=linux-gnu
7243 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007244 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007245 * EUID=<NNNNN>
7246 * UID=<NNNNN>
7247 * GROUPS=()
7248 * LINES=<NNN>
7249 * COLUMNS=<NNN>
7250 * BASH_ARGC=()
7251 * BASH_ARGV=()
7252 * BASH_LINENO=()
7253 * BASH_SOURCE=()
7254 * DIRSTACK=()
7255 * PIPESTATUS=([0]="0")
7256 * HISTFILE=/<xxx>/.bash_history
7257 * HISTFILESIZE=500
7258 * HISTSIZE=500
7259 * MAILCHECK=60
7260 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7261 * SHELL=/bin/bash
7262 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7263 * TERM=dumb
7264 * OPTERR=1
7265 * OPTIND=1
7266 * IFS=$' \t\n'
7267 * PS1='\s-\v\$ '
7268 * PS2='> '
7269 * PS4='+ '
7270 */
7271
Denis Vlasenko38f63192007-01-22 09:03:07 +00007272#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007273 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007274#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00007275 G.global_argc = argc;
7276 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007277 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007278 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007279
Denis Vlasenkoed782372009-04-10 00:45:02 +00007280 if (setjmp(die_jmp)) {
7281 /* xfunc has failed! die die die */
7282 /* no EXIT traps, this is an escape hatch! */
7283 G.exiting = 1;
7284 hush_exit(xfunc_error_retval);
7285 }
7286
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007287 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007288 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007289 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007290 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007291 * in order to intercept (more) signals.
7292 */
7293
7294 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007295 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007296 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007297 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007298 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007299#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007300 "<:$:R:V:"
7301# if ENABLE_HUSH_FUNCTIONS
7302 "F:"
7303# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007304#endif
7305 );
7306 if (opt <= 0)
7307 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007308 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007309 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007310 /* Possibilities:
7311 * sh ... -c 'script'
7312 * sh ... -c 'script' ARG0 [ARG1...]
7313 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007314 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007315 * "" needs to be replaced with NULL
7316 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007317 * Note: the form without ARG0 never happens:
7318 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007319 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007320 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007321 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007322 G.root_ppid = getppid();
7323 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007324 G.global_argv = argv + optind;
7325 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007326 if (builtin_argc) {
7327 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7328 const struct built_in_command *x;
7329
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007330 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007331 x = find_builtin(optarg);
7332 if (x) { /* paranoia */
7333 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7334 G.global_argv += builtin_argc;
7335 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007336 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007337 }
7338 goto final_return;
7339 }
7340 if (!G.global_argv[0]) {
7341 /* -c 'script' (no params): prevent empty $0 */
7342 G.global_argv--; /* points to argv[i] of 'script' */
7343 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007344 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007345 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007346 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007347 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007348 goto final_return;
7349 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007350 /* Well, we cannot just declare interactiveness,
7351 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007352 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007353 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007354 case 's':
7355 /* "-s" means "read from stdin", but this is how we always
7356 * operate, so simply do nothing here. */
7357 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007358#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007359 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007360 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007361 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007362 case '$': {
7363 unsigned long long empty_trap_mask;
7364
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007365 G.root_pid = bb_strtou(optarg, &optarg, 16);
7366 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007367 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7368 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007369 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7370 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007371 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007372 optarg++;
7373 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007374 optarg++;
7375 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7376 if (empty_trap_mask != 0) {
7377 int sig;
7378 init_sigmasks();
7379 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7380 for (sig = 1; sig < NSIG; sig++) {
7381 if (empty_trap_mask & (1LL << sig)) {
7382 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7383 sigaddset(&G.blocked_set, sig);
7384 }
7385 }
7386 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7387 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007388# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007389 optarg++;
7390 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007391# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007392 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007393 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007394 case 'R':
7395 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007396 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007397 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007398# if ENABLE_HUSH_FUNCTIONS
7399 case 'F': {
7400 struct function *funcp = new_function(optarg);
7401 /* funcp->name is already set to optarg */
7402 /* funcp->body is set to NULL. It's a special case. */
7403 funcp->body_as_string = argv[optind];
7404 optind++;
7405 break;
7406 }
7407# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007408#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007409 case 'n':
7410 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007411 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007412 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007413 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007414#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007415 fprintf(stderr, "Usage: sh [FILE]...\n"
7416 " or: sh -c command [args]...\n\n");
7417 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007418#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007419 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007420#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007421 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007422 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007423
Denys Vlasenkodea47882009-10-09 15:40:49 +02007424 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007425 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007426 G.root_ppid = getppid();
7427 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007428
7429 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007430 if (argv[0] && argv[0][0] == '-') {
7431 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007432 debug_printf("sourcing /etc/profile\n");
7433 input = fopen_for_read("/etc/profile");
7434 if (input != NULL) {
7435 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007436 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007437 parse_and_run_file(input);
7438 fclose(input);
7439 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007440 /* bash: after sourcing /etc/profile,
7441 * tries to source (in the given order):
7442 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007443 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007444 * bash also sources ~/.bash_logout on exit.
7445 * If called as sh, skips .bash_XXX files.
7446 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007447 }
7448
Denis Vlasenkof9375282009-04-05 19:13:39 +00007449 if (argv[optind]) {
7450 FILE *input;
7451 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007452 * "bash <script>" (which is never interactive (unless -i?))
7453 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007454 * If called as sh, does the same but with $ENV.
7455 */
7456 debug_printf("running script '%s'\n", argv[optind]);
7457 G.global_argv = argv + optind;
7458 G.global_argc = argc - optind;
7459 input = xfopen_for_read(argv[optind]);
7460 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007461 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007462 parse_and_run_file(input);
7463#if ENABLE_FEATURE_CLEAN_UP
7464 fclose(input);
7465#endif
7466 goto final_return;
7467 }
7468
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007469 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007470 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007471 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007472
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007473 /* A shell is interactive if the '-i' flag was given,
7474 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007475 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007476 * no arguments remaining or the -s flag given
7477 * standard input is a terminal
7478 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007479 * Refer to Posix.2, the description of the 'sh' utility.
7480 */
7481#if ENABLE_HUSH_JOB
7482 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007483 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7484 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7485 if (G_saved_tty_pgrp < 0)
7486 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007487
7488 /* try to dup stdin to high fd#, >= 255 */
7489 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7490 if (G_interactive_fd < 0) {
7491 /* try to dup to any fd */
7492 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007493 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007494 /* give up */
7495 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007496 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007497 }
7498 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007499// TODO: track & disallow any attempts of user
7500// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007501 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007502 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007503 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007504 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007505
Mike Frysinger38478a62009-05-20 04:48:06 -04007506 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007507 /* If we were run as 'hush &', sleep until we are
7508 * in the foreground (tty pgrp == our pgrp).
7509 * If we get started under a job aware app (like bash),
7510 * make sure we are now in charge so we don't fight over
7511 * who gets the foreground */
7512 while (1) {
7513 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007514 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7515 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007516 break;
7517 /* send TTIN to ourself (should stop us) */
7518 kill(- shell_pgrp, SIGTTIN);
7519 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007520 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007521
Denis Vlasenkof9375282009-04-05 19:13:39 +00007522 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007523 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007524
Mike Frysinger38478a62009-05-20 04:48:06 -04007525 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007526 /* Set other signals to restore saved_tty_pgrp */
7527 set_fatal_handlers();
7528 /* Put ourselves in our own process group
7529 * (bash, too, does this only if ctty is available) */
7530 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7531 /* Grab control of the terminal */
7532 tcsetpgrp(G_interactive_fd, getpid());
7533 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007534 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007535 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007536 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007537 } else {
7538 init_sigmasks();
7539 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007540#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007541 /* No job control compiled in, only prompt/line editing */
7542 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007543 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7544 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007545 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007546 G_interactive_fd = dup(STDIN_FILENO);
7547 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007548 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007549 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007550 }
7551 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007552 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007553 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007554 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007555 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007556#else
7557 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007558 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007559#endif
7560 /* bash:
7561 * if interactive but not a login shell, sources ~/.bashrc
7562 * (--norc turns this off, --rcfile <file> overrides)
7563 */
7564
7565 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007566 /* note: ash and hush share this string */
7567 printf("\n\n%s %s\n"
7568 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7569 "\n",
7570 bb_banner,
7571 "hush - the humble shell"
7572 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007573 }
7574
Denis Vlasenkof9375282009-04-05 19:13:39 +00007575 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007576
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007577 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007578#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007579 if (G.cwd != bb_msg_unknown)
7580 free((char*)G.cwd);
7581 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007582 while (cur_var) {
7583 struct variable *tmp = cur_var;
7584 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007585 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007586 cur_var = cur_var->next;
7587 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007588 }
Eric Andersen25f27032001-04-26 23:22:31 +00007589#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007590 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007591}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007592
7593
7594#if ENABLE_LASH
7595int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7596int lash_main(int argc, char **argv)
7597{
Denys Vlasenko07934912009-08-20 03:40:04 +02007598 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007599 return hush_main(argc, argv);
7600}
7601#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007602
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007603#if ENABLE_MSH
7604int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7605int msh_main(int argc, char **argv)
7606{
7607 //bb_error_msg("msh is deprecated, please use hush instead");
7608 return hush_main(argc, argv);
7609}
7610#endif
7611
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007612
7613/*
7614 * Built-ins
7615 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007616static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007617{
7618 return 0;
7619}
7620
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007621static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007622{
7623 int argc = 0;
7624 while (*argv) {
7625 argc++;
7626 argv++;
7627 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007628 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007629}
7630
7631static int FAST_FUNC builtin_test(char **argv)
7632{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007633 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007634}
7635
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007636static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007637{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007638 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007639}
7640
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007641#if ENABLE_PRINTF
7642static int FAST_FUNC builtin_printf(char **argv)
7643{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007644 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007645}
7646#endif
7647
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007648static char **skip_dash_dash(char **argv)
7649{
7650 argv++;
7651 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7652 argv++;
7653 return argv;
7654}
7655
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007656static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007657{
7658 int rcode = EXIT_SUCCESS;
7659
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007660 argv = skip_dash_dash(argv);
7661 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007662 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007663 /* bash:
7664 * eval "echo Hi; done" ("done" is syntax error):
7665 * "echo Hi" will not execute too.
7666 */
7667 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007668 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007669 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007670 }
7671 return rcode;
7672}
7673
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007674static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007675{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007676 const char *newdir;
7677
7678 argv = skip_dash_dash(argv);
7679 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007680 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007681 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007682 * bash says "bash: cd: HOME not set" and does nothing
7683 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007684 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007685 const char *home = get_local_var_value("HOME");
7686 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007687 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007688 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007689 /* Mimic bash message exactly */
7690 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007691 return EXIT_FAILURE;
7692 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007693 /* Read current dir (get_cwd(1) is inside) and set PWD.
7694 * Note: do not enforce exporting. If PWD was unset or unexported,
7695 * set it again, but do not export. bash does the same.
7696 */
7697 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007698 return EXIT_SUCCESS;
7699}
7700
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007701static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007702{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007703 argv = skip_dash_dash(argv);
7704 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007705 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007706
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007707 /* Careful: we can end up here after [v]fork. Do not restore
7708 * tty pgrp then, only top-level shell process does that */
7709 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7710 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7711
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007712 /* TODO: if exec fails, bash does NOT exit! We do.
7713 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7714 * and tcsetpgrp, and this is inherently racy.
7715 */
7716 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007717}
7718
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007719static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007720{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007721 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007722
7723 /* interactive bash:
7724 * # trap "echo EEE" EXIT
7725 * # exit
7726 * exit
7727 * There are stopped jobs.
7728 * (if there are _stopped_ jobs, running ones don't count)
7729 * # exit
7730 * exit
7731 # EEE (then bash exits)
7732 *
7733 * we can use G.exiting = -1 as indicator "last cmd was exit"
7734 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007735
7736 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007737 argv = skip_dash_dash(argv);
7738 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007739 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007740 /* mimic bash: exit 123abc == exit 255 + error msg */
7741 xfunc_error_retval = 255;
7742 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007743 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007744}
7745
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007746static void print_escaped(const char *s)
7747{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007748 if (*s == '\'')
7749 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007750 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007751 const char *p = strchrnul(s, '\'');
7752 /* print 'xxxx', possibly just '' */
7753 printf("'%.*s'", (int)(p - s), s);
7754 if (*p == '\0')
7755 break;
7756 s = p;
7757 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007758 /* s points to '; print "'''...'''" */
7759 putchar('"');
7760 do putchar('\''); while (*++s == '\'');
7761 putchar('"');
7762 } while (*s);
7763}
7764
Denys Vlasenko295fef82009-06-03 12:47:26 +02007765#if !ENABLE_HUSH_LOCAL
7766#define helper_export_local(argv, exp, lvl) \
7767 helper_export_local(argv, exp)
7768#endif
7769static void helper_export_local(char **argv, int exp, int lvl)
7770{
7771 do {
7772 char *name = *argv;
7773
7774 /* So far we do not check that name is valid (TODO?) */
7775
7776 if (strchr(name, '=') == NULL) {
7777 struct variable *var;
7778
7779 var = get_local_var(name);
7780 if (exp == -1) { /* unexporting? */
7781 /* export -n NAME (without =VALUE) */
7782 if (var) {
7783 var->flg_export = 0;
7784 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7785 unsetenv(name);
7786 } /* else: export -n NOT_EXISTING_VAR: no-op */
7787 continue;
7788 }
7789 if (exp == 1) { /* exporting? */
7790 /* export NAME (without =VALUE) */
7791 if (var) {
7792 var->flg_export = 1;
7793 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7794 putenv(var->varstr);
7795 continue;
7796 }
7797 }
7798 /* Exporting non-existing variable.
7799 * bash does not put it in environment,
7800 * but remembers that it is exported,
7801 * and does put it in env when it is set later.
7802 * We just set it to "" and export. */
7803 /* Or, it's "local NAME" (without =VALUE).
7804 * bash sets the value to "". */
7805 name = xasprintf("%s=", name);
7806 } else {
7807 /* (Un)exporting/making local NAME=VALUE */
7808 name = xstrdup(name);
7809 }
7810 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7811 } while (*++argv);
7812}
7813
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007814static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007815{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007816 unsigned opt_unexport;
7817
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007818#if ENABLE_HUSH_EXPORT_N
7819 /* "!": do not abort on errors */
7820 opt_unexport = getopt32(argv, "!n");
7821 if (opt_unexport == (uint32_t)-1)
7822 return EXIT_FAILURE;
7823 argv += optind;
7824#else
7825 opt_unexport = 0;
7826 argv++;
7827#endif
7828
7829 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007830 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007831 if (e) {
7832 while (*e) {
7833#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007834 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007835#else
7836 /* ash emits: export VAR='VAL'
7837 * bash: declare -x VAR="VAL"
7838 * we follow ash example */
7839 const char *s = *e++;
7840 const char *p = strchr(s, '=');
7841
7842 if (!p) /* wtf? take next variable */
7843 continue;
7844 /* export var= */
7845 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007846 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007847 putchar('\n');
7848#endif
7849 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007850 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007851 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007852 return EXIT_SUCCESS;
7853 }
7854
Denys Vlasenko295fef82009-06-03 12:47:26 +02007855 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007856
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007857 return EXIT_SUCCESS;
7858}
7859
Denys Vlasenko295fef82009-06-03 12:47:26 +02007860#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007861static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007862{
7863 if (G.func_nest_level == 0) {
7864 bb_error_msg("%s: not in a function", argv[0]);
7865 return EXIT_FAILURE; /* bash compat */
7866 }
7867 helper_export_local(argv, 0, G.func_nest_level);
7868 return EXIT_SUCCESS;
7869}
7870#endif
7871
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007872static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007873{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007874 int sig;
7875 char *new_cmd;
7876
7877 if (!G.traps)
7878 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7879
7880 argv++;
7881 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007882 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007883 /* No args: print all trapped */
7884 for (i = 0; i < NSIG; ++i) {
7885 if (G.traps[i]) {
7886 printf("trap -- ");
7887 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007888 /* note: bash adds "SIG", but only if invoked
7889 * as "bash". If called as "sh", or if set -o posix,
7890 * then it prints short signal names.
7891 * We are printing short names: */
7892 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007893 }
7894 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007895 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007896 return EXIT_SUCCESS;
7897 }
7898
7899 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007900 /* If first arg is a number: reset all specified signals */
7901 sig = bb_strtou(*argv, NULL, 10);
7902 if (errno == 0) {
7903 int ret;
7904 process_sig_list:
7905 ret = EXIT_SUCCESS;
7906 while (*argv) {
7907 sig = get_signum(*argv++);
7908 if (sig < 0 || sig >= NSIG) {
7909 ret = EXIT_FAILURE;
7910 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007911 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007912 continue;
7913 }
7914
7915 free(G.traps[sig]);
7916 G.traps[sig] = xstrdup(new_cmd);
7917
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007918 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007919 get_signame(sig), sig, G.traps[sig]);
7920
7921 /* There is no signal for 0 (EXIT) */
7922 if (sig == 0)
7923 continue;
7924
7925 if (new_cmd) {
7926 sigaddset(&G.blocked_set, sig);
7927 } else {
7928 /* There was a trap handler, we are removing it
7929 * (if sig has non-DFL handling,
7930 * we don't need to do anything) */
7931 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7932 continue;
7933 sigdelset(&G.blocked_set, sig);
7934 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007935 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007936 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007937 return ret;
7938 }
7939
7940 if (!argv[1]) { /* no second arg */
7941 bb_error_msg("trap: invalid arguments");
7942 return EXIT_FAILURE;
7943 }
7944
7945 /* First arg is "-": reset all specified to default */
7946 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7947 /* Everything else: set arg as signal handler
7948 * (includes "" case, which ignores signal) */
7949 if (argv[0][0] == '-') {
7950 if (argv[0][1] == '\0') { /* "-" */
7951 /* new_cmd remains NULL: "reset these sigs" */
7952 goto reset_traps;
7953 }
7954 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7955 argv++;
7956 }
7957 /* else: "-something", no special meaning */
7958 }
7959 new_cmd = *argv;
7960 reset_traps:
7961 argv++;
7962 goto process_sig_list;
7963}
7964
Mike Frysinger93cadc22009-05-27 17:06:25 -04007965/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007966static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007967{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007968 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007969
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007970 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007971 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007972 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007973
7974 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007975 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007976 type = "an alias";*/
7977#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007978 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007979 type = "a function";
7980#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007981 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007982 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007983 else if ((path = find_in_path(*argv)) != NULL)
7984 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007985 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007986 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007987 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007988 continue;
7989 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007990
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007991 printf("%s is %s\n", *argv, type);
7992 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007993 }
7994
7995 return ret;
7996}
7997
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007998#if ENABLE_HUSH_JOB
7999/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008000static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008001{
8002 int i, jobnum;
8003 struct pipe *pi;
8004
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008005 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008006 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008007
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008008 /* If they gave us no args, assume they want the last backgrounded task */
8009 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008010 for (pi = G.job_list; pi; pi = pi->next) {
8011 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008012 goto found;
8013 }
8014 }
8015 bb_error_msg("%s: no current job", argv[0]);
8016 return EXIT_FAILURE;
8017 }
8018 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8019 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8020 return EXIT_FAILURE;
8021 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008022 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008023 if (pi->jobid == jobnum) {
8024 goto found;
8025 }
8026 }
8027 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8028 return EXIT_FAILURE;
8029 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008030 /* TODO: bash prints a string representation
8031 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008032 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008033 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008034 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008035 }
8036
8037 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008038 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8039 for (i = 0; i < pi->num_cmds; i++) {
8040 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8041 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008042 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008043 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008044
8045 i = kill(- pi->pgrp, SIGCONT);
8046 if (i < 0) {
8047 if (errno == ESRCH) {
8048 delete_finished_bg_job(pi);
8049 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008050 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008051 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008052 }
8053
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008054 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008055 remove_bg_job(pi);
8056 return checkjobs_and_fg_shell(pi);
8057 }
8058 return EXIT_SUCCESS;
8059}
8060#endif
8061
8062#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008063static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008064{
8065 const struct built_in_command *x;
8066
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008067 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008068 "Built-in commands:\n"
8069 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008070 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008071 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008072 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008073 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008074 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008075 return EXIT_SUCCESS;
8076}
8077#endif
8078
8079#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008080static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008081{
8082 struct pipe *job;
8083 const char *status_string;
8084
Denis Vlasenko87a86552008-07-29 19:43:10 +00008085 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008086 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008087 status_string = "Stopped";
8088 else
8089 status_string = "Running";
8090
8091 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8092 }
8093 return EXIT_SUCCESS;
8094}
8095#endif
8096
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008097#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008098static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008099{
8100 void *p;
8101 unsigned long l;
8102
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008103# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008104 /* Optional. Reduces probability of false positives */
8105 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008106# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008107 /* Crude attempt to find where "free memory" starts,
8108 * sans fragmentation. */
8109 p = malloc(240);
8110 l = (unsigned long)p;
8111 free(p);
8112 p = malloc(3400);
8113 if (l < (unsigned long)p) l = (unsigned long)p;
8114 free(p);
8115
8116 if (!G.memleak_value)
8117 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008118
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008119 l -= G.memleak_value;
8120 if ((long)l < 0)
8121 l = 0;
8122 l /= 1024;
8123 if (l > 127)
8124 l = 127;
8125
8126 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8127 return l;
8128}
8129#endif
8130
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008131static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008132{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008133 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008134 return EXIT_SUCCESS;
8135}
8136
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008137static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008138{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008139 const char *r;
8140 char *opt_n = NULL;
8141 char *opt_p = NULL;
8142 char *opt_t = NULL;
8143 char *opt_u = NULL;
8144 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008145
Denys Vlasenko03dad222010-01-12 23:29:57 +01008146 /* "!": do not abort on errors.
8147 * Option string must start with "sr" to match BUILTIN_READ_xxx
8148 */
8149 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8150 if (read_flags == (uint32_t)-1)
8151 return EXIT_FAILURE;
8152 argv += optind;
8153
8154 r = shell_builtin_read(set_local_var_from_halves,
8155 argv,
8156 get_local_var_value("IFS"), /* can be NULL */
8157 read_flags,
8158 opt_n,
8159 opt_p,
8160 opt_t,
8161 opt_u
8162 );
8163
8164 if ((uintptr_t)r > 1) {
8165 bb_error_msg("%s", r);
8166 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008167 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008168
Denys Vlasenko03dad222010-01-12 23:29:57 +01008169 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008170}
8171
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008172/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8173 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008174 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008175 * set [-abCefhmnuvx] [-o option] [argument...]
8176 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008177 * set -- [argument...]
8178 * set -o
8179 * set +o
8180 * Implementations shall support the options in both their hyphen and
8181 * plus-sign forms. These options can also be specified as options to sh.
8182 * Examples:
8183 * Write out all variables and their values: set
8184 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8185 * Turn on the -x and -v options: set -xv
8186 * Unset all positional parameters: set --
8187 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8188 * Set the positional parameters to the expansion of x, even if x expands
8189 * with a leading '-' or '+': set -- $x
8190 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008191 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008192 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008193static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008194{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008195 int n;
8196 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008197 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008198
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008199 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008200 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008201 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008202 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008203 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008204 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008205
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008206 do {
8207 if (!strcmp(arg, "--")) {
8208 ++argv;
8209 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008210 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008211 if (arg[0] != '+' && arg[0] != '-')
8212 break;
8213 for (n = 1; arg[n]; ++n)
8214 if (set_mode(arg[0], arg[n]))
8215 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008216 } while ((arg = *++argv) != NULL);
8217 /* Now argv[0] is 1st argument */
8218
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008219 if (arg == NULL)
8220 return EXIT_SUCCESS;
8221 set_argv:
8222
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008223 /* NB: G.global_argv[0] ($0) is never freed/changed */
8224 g_argv = G.global_argv;
8225 if (G.global_args_malloced) {
8226 pp = g_argv;
8227 while (*++pp)
8228 free(*pp);
8229 g_argv[1] = NULL;
8230 } else {
8231 G.global_args_malloced = 1;
8232 pp = xzalloc(sizeof(pp[0]) * 2);
8233 pp[0] = g_argv[0]; /* retain $0 */
8234 g_argv = pp;
8235 }
8236 /* This realloc's G.global_argv */
8237 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8238
8239 n = 1;
8240 while (*++pp)
8241 n++;
8242 G.global_argc = n;
8243
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008244 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008245
8246 /* Nothing known, so abort */
8247 error:
8248 bb_error_msg("set: %s: invalid option", arg);
8249 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008250}
8251
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008252static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008253{
8254 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008255 argv = skip_dash_dash(argv);
8256 if (argv[0]) {
8257 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008258 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008259 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008260 if (G.global_args_malloced) {
8261 int m = 1;
8262 while (m <= n)
8263 free(G.global_argv[m++]);
8264 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008265 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008266 memmove(&G.global_argv[1], &G.global_argv[n+1],
8267 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008268 return EXIT_SUCCESS;
8269 }
8270 return EXIT_FAILURE;
8271}
8272
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008273static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008274{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008275 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008276 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008277 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008278#if ENABLE_HUSH_FUNCTIONS
8279 smallint sv_flg;
8280#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008281
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008282 argv = skip_dash_dash(argv);
8283 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008284 if (!filename) {
8285 /* bash says: "bash: .: filename argument required" */
8286 return 2; /* bash compat */
8287 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008288 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008289 if (!strchr(filename, '/')) {
8290 arg_path = find_in_path(filename);
8291 if (arg_path)
8292 filename = arg_path;
8293 }
8294 input = fopen_or_warn(filename, "r");
8295 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008296 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008297 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008298 return EXIT_FAILURE;
8299 }
8300 close_on_exec_on(fileno(input));
8301
Mike Frysinger885b6f22009-04-18 21:04:25 +00008302#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008303 sv_flg = G.flag_return_in_progress;
8304 /* "we are inside sourced file, ok to use return" */
8305 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008306#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008307 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008308
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008309 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008310 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008311
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008312 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008313#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008314 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008315#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008316
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008317 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008318}
8319
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008320static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008321{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008322 int rc;
8323 mode_t mask;
8324
8325 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008326 argv = skip_dash_dash(argv);
8327 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008328 mode_t old_mask = mask;
8329
8330 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008331 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008332 mask ^= 0777;
8333 if (rc == 0) {
8334 mask = old_mask;
8335 /* bash messages:
8336 * bash: umask: 'q': invalid symbolic mode operator
8337 * bash: umask: 999: octal number out of range
8338 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008339 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008340 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008341 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008342 rc = 1;
8343 /* Mimic bash */
8344 printf("%04o\n", (unsigned) mask);
8345 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008346 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008347 umask(mask);
8348
8349 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008350}
8351
Mike Frysingerd690f682009-03-30 06:50:54 +00008352/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008353static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008354{
Mike Frysingerd690f682009-03-30 06:50:54 +00008355 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008356 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008357
Denis Vlasenko28e67962009-04-26 23:22:40 +00008358 /* "!": do not abort on errors */
8359 /* "+": stop at 1st non-option */
8360 opts = getopt32(argv, "!+vf");
8361 if (opts == (unsigned)-1)
8362 return EXIT_FAILURE;
8363 if (opts == 3) {
8364 bb_error_msg("unset: -v and -f are exclusive");
8365 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008366 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008367 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008368
8369 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008370 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008371 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008372 if (unset_local_var(*argv)) {
8373 /* unset <nonexistent_var> doesn't fail.
8374 * Error is when one tries to unset RO var.
8375 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008376 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008377 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008378 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008379#if ENABLE_HUSH_FUNCTIONS
8380 else {
8381 unset_func(*argv);
8382 }
8383#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008384 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008385 }
8386 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008387}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008388
Mike Frysinger56bdea12009-03-28 20:01:58 +00008389/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008390static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008391{
8392 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008393 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008394
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008395 argv = skip_dash_dash(argv);
8396 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008397 /* Don't care about wait results */
8398 /* Note 1: must wait until there are no more children */
8399 /* Note 2: must be interruptible */
8400 /* Examples:
8401 * $ sleep 3 & sleep 6 & wait
8402 * [1] 30934 sleep 3
8403 * [2] 30935 sleep 6
8404 * [1] Done sleep 3
8405 * [2] Done sleep 6
8406 * $ sleep 3 & sleep 6 & wait
8407 * [1] 30936 sleep 3
8408 * [2] 30937 sleep 6
8409 * [1] Done sleep 3
8410 * ^C <-- after ~4 sec from keyboard
8411 * $
8412 */
8413 sigaddset(&G.blocked_set, SIGCHLD);
8414 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8415 while (1) {
8416 checkjobs(NULL);
8417 if (errno == ECHILD)
8418 break;
8419 /* Wait for SIGCHLD or any other signal of interest */
8420 /* sigtimedwait with infinite timeout: */
8421 sig = sigwaitinfo(&G.blocked_set, NULL);
8422 if (sig > 0) {
8423 sig = check_and_run_traps(sig);
8424 if (sig && sig != SIGCHLD) { /* see note 2 */
8425 ret = 128 + sig;
8426 break;
8427 }
8428 }
8429 }
8430 sigdelset(&G.blocked_set, SIGCHLD);
8431 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8432 return ret;
8433 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008434
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008435 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008436 while (*argv) {
8437 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008438 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008439 /* mimic bash message */
8440 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008441 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008442 }
8443 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008444 if (WIFSIGNALED(status))
8445 ret = 128 + WTERMSIG(status);
8446 else if (WIFEXITED(status))
8447 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008448 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008449 ret = EXIT_FAILURE;
8450 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008451 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008452 ret = 127;
8453 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008454 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008455 }
8456
8457 return ret;
8458}
8459
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008460#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8461static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8462{
8463 if (argv[1]) {
8464 def = bb_strtou(argv[1], NULL, 10);
8465 if (errno || def < def_min || argv[2]) {
8466 bb_error_msg("%s: bad arguments", argv[0]);
8467 def = UINT_MAX;
8468 }
8469 }
8470 return def;
8471}
8472#endif
8473
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008474#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008475static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008476{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008477 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008478 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008479 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008480 return EXIT_SUCCESS; /* bash compat */
8481 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008482 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008483
8484 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8485 if (depth == UINT_MAX)
8486 G.flag_break_continue = BC_BREAK;
8487 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008488 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008489
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008490 return EXIT_SUCCESS;
8491}
8492
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008493static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008494{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008495 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8496 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008497}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008498#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008499
8500#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008501static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008502{
8503 int rc;
8504
8505 if (G.flag_return_in_progress != -1) {
8506 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8507 return EXIT_FAILURE; /* bash compat */
8508 }
8509
8510 G.flag_return_in_progress = 1;
8511
8512 /* bash:
8513 * out of range: wraps around at 256, does not error out
8514 * non-numeric param:
8515 * f() { false; return qwe; }; f; echo $?
8516 * bash: return: qwe: numeric argument required <== we do this
8517 * 255 <== we also do this
8518 */
8519 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8520 return rc;
8521}
8522#endif