blob: 0a420f685205f21c53b2fd9c79ff24cdec1ee154 [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 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000082 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
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. */
393 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000394 smallint has_empty_slot;
395 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
396} o_string;
397enum {
398 MAYBE_ASSIGNMENT = 0,
399 DEFINITELY_ASSIGNMENT = 1,
400 NOT_ASSIGNMENT = 2,
401 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
402};
403/* Used for initialization: o_string foo = NULL_O_STRING; */
404#define NULL_O_STRING { NULL }
405
406/* I can almost use ordinary FILE*. Is open_memstream() universally
407 * available? Where is it documented? */
408typedef struct in_str {
409 const char *p;
410 /* eof_flag=1: last char in ->p is really an EOF */
411 char eof_flag; /* meaningless if ->p == NULL */
412 char peek_buf[2];
413#if ENABLE_HUSH_INTERACTIVE
414 smallint promptme;
415 smallint promptmode; /* 0: PS1, 1: PS2 */
416#endif
417 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200418 int (*get) (struct in_str *) FAST_FUNC;
419 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000420} in_str;
421#define i_getch(input) ((input)->get(input))
422#define i_peek(input) ((input)->peek(input))
423
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200424/* The descrip member of this structure is only used to make
425 * debugging output pretty */
426static const struct {
427 int mode;
428 signed char default_fd;
429 char descrip[3];
430} redir_table[] = {
431 { O_RDONLY, 0, "<" },
432 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
433 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
434 { O_CREAT|O_RDWR, 1, "<>" },
435 { O_RDONLY, 0, "<<" },
436/* Should not be needed. Bogus default_fd helps in debugging */
437/* { O_RDONLY, 77, "<<" }, */
438};
439
Eric Andersen25f27032001-04-26 23:22:31 +0000440struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000441 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000442 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000443 int rd_fd; /* fd to redirect */
444 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
445 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000446 smallint rd_type; /* (enum redir_type) */
447 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000448 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200449 * bit 0: do we need to trim leading tabs?
450 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000451 */
Eric Andersen25f27032001-04-26 23:22:31 +0000452};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000453typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200454 REDIRECT_INPUT = 0,
455 REDIRECT_OVERWRITE = 1,
456 REDIRECT_APPEND = 2,
457 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000458 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200459 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000460
461 REDIRFD_CLOSE = -3,
462 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000463 REDIRFD_TO_FILE = -1,
464 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000465
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000466 HEREDOC_SKIPTABS = 1,
467 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000468} redir_type;
469
Eric Andersen25f27032001-04-26 23:22:31 +0000470
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000471struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000472 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000473 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000474 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200475 smallint cmd_type; /* CMD_xxx */
476#define CMD_NORMAL 0
477#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200478
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200479/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200480#if ENABLE_HUSH_BASH_COMPAT
481# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000482#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200483
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200484/* used for "export noglob=* glob* a=`echo a b`" */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +0200485//#define CMD_SINGLEWORD_NOGLOB_COND 3
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200486// It is hard to implement correctly, it adds significant amounts of tricky code,
487// and all this is only useful for really obscure export statements
488// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
489// guards the code which implements it, but I have doubts it works
490// in all cases (especially with mixed globbed/non-globbed arguments)
491
492#if ENABLE_HUSH_FUNCTIONS
493# define CMD_FUNCDEF 3
494#endif
495
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200496 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
497 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000498#if !BB_MMU
499 char *group_as_string;
500#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000501#if ENABLE_HUSH_FUNCTIONS
502 struct function *child_func;
503/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200504 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000505 * When we execute "f1() {a;}" cmd, we create new function and clear
506 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200507 * When we execute "f1() {b;}", we notice that f1 exists,
508 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000509 * we put those fields back into cmd->xxx
510 * (struct function has ->parent_cmd ptr to facilitate that).
511 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
512 * Without this trick, loop would execute a;b;b;b;...
513 * instead of correct sequence a;b;a;b;...
514 * When command is freed, it severs the link
515 * (sets ->child_func->parent_cmd to NULL).
516 */
517#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000518 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000519/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
520 * and on execution these are substituted with their values.
521 * Substitution can make _several_ words out of one argv[n]!
522 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000523 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000524 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000525 struct redir_struct *redirects; /* I/O redirections */
526};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000527/* Is there anything in this command at all? */
528#define IS_NULL_CMD(cmd) \
529 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
530
Eric Andersen25f27032001-04-26 23:22:31 +0000531
532struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000533 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000534 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000535 int alive_cmds; /* number of commands running (not exited) */
536 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000537#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000538 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000539 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000540 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000541#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000542 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000543 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000544 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
545 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000546};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000547typedef enum pipe_style {
548 PIPE_SEQ = 1,
549 PIPE_AND = 2,
550 PIPE_OR = 3,
551 PIPE_BG = 4,
552} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000553/* Is there anything in this pipe at all? */
554#define IS_NULL_PIPE(pi) \
555 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000556
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000557/* This holds pointers to the various results of parsing */
558struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000559 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000560 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000561 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000562 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000563 /* last command in pipe (being constructed right now) */
564 struct command *command;
565 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000566 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000567#if !BB_MMU
568 o_string as_string;
569#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000570#if HAS_KEYWORDS
571 smallint ctx_res_w;
572 smallint ctx_inverted; /* "! cmd | cmd" */
573#if ENABLE_HUSH_CASE
574 smallint ctx_dsemicolon; /* ";;" seen */
575#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000576 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
577 int old_flag;
578 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000579 * example: "if pipe1; pipe2; then pipe3; fi"
580 * when we see "if" or "then", we malloc and copy current context,
581 * and make ->stack point to it. then we parse pipeN.
582 * when closing "then" / fi" / whatever is found,
583 * we move list_head into ->stack->command->group,
584 * copy ->stack into current context, and delete ->stack.
585 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000586 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000587 struct parse_context *stack;
588#endif
589};
590
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000591/* On program start, environ points to initial environment.
592 * putenv adds new pointers into it, unsetenv removes them.
593 * Neither of these (de)allocates the strings.
594 * setenv allocates new strings in malloc space and does putenv,
595 * and thus setenv is unusable (leaky) for shell's purposes */
596#define setenv(...) setenv_is_leaky_dont_use()
597struct variable {
598 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000599 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200600#if ENABLE_HUSH_LOCAL
601 unsigned func_nest_level;
602#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000603 int max_len; /* if > 0, name is part of initial env; else name is malloced */
604 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000605 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000606};
607
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000608enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000609 BC_BREAK = 1,
610 BC_CONTINUE = 2,
611};
612
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000613#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000614struct function {
615 struct function *next;
616 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000617 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000618 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200619# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000620 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200621# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000622};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000623#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000624
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000625
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000626/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000627/* Sorted roughly by size (smaller offsets == smaller code) */
628struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000629 /* interactive_fd != 0 means we are an interactive shell.
630 * If we are, then saved_tty_pgrp can also be != 0, meaning
631 * that controlling tty is available. With saved_tty_pgrp == 0,
632 * job control still works, but terminal signals
633 * (^C, ^Z, ^Y, ^\) won't work at all, and background
634 * process groups can only be created with "cmd &".
635 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
636 * to give tty to the foreground process group,
637 * and will take it back when the group is stopped (^Z)
638 * or killed (^C).
639 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000640#if ENABLE_HUSH_INTERACTIVE
641 /* 'interactive_fd' is a fd# open to ctty, if we have one
642 * _AND_ if we decided to act interactively */
643 int interactive_fd;
644 const char *PS1;
645 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000646# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000647#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000648# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000649#endif
650#if ENABLE_FEATURE_EDITING
651 line_input_t *line_input_state;
652#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000653 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200654 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000655 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200656#if ENABLE_HUSH_RANDOM_SUPPORT
657 random_t random_gen;
658#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000659#if ENABLE_HUSH_JOB
660 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000661 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000662 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000663 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400664# define G_saved_tty_pgrp (G.saved_tty_pgrp)
665#else
666# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000667#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000668 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000669#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000670 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000671#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000672#if ENABLE_HUSH_FUNCTIONS
673 /* 0: outside of a function (or sourced file)
674 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000675 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000676 */
677 smallint flag_return_in_progress;
678#endif
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200679 smallint n_mode;
680#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +0200681 smallint x_mode;
Denys Vlasenko29082232010-07-16 13:52:32 +0200682# define G_x_mode (G.x_mode)
Denys Vlasenko202a2d12010-07-16 12:36:14 +0200683#else
684# define G_x_mode 0
685#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000686 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000687 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000688 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000689 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000690 smalluint global_args_malloced;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +0100691 smalluint inherited_set_is_saved;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000692 /* how many non-NULL argv's we have. NB: $# + 1 */
693 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000694 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000695#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000696 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000697#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000698#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000699 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000700 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000701#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000702 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000703 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000704 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000705 struct variable shell_ver;
Denys Vlasenko29082232010-07-16 13:52:32 +0200706 char **expanded_assignments;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000707#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000708 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200709# if ENABLE_HUSH_LOCAL
710 struct variable **shadowed_vars_pp;
711 unsigned func_nest_level;
712# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000713#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000714 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200715#if ENABLE_HUSH_FAST
716 unsigned count_SIGCHLD;
717 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200718 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200719#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000720 /* which signals have non-DFL handler (even with no traps set)? */
721 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000722 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000723 sigset_t blocked_set;
724 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000725#if HUSH_DEBUG
726 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000727 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000728#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200729 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000730};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000731#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000732/* Not #defining name to G.name - this quickly gets unwieldy
733 * (too many defines). Also, I actually prefer to see when a variable
734 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000735#define INIT_G() do { \
736 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
737} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000738
739
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000740/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200741static int builtin_cd(char **argv) FAST_FUNC;
742static int builtin_echo(char **argv) FAST_FUNC;
743static int builtin_eval(char **argv) FAST_FUNC;
744static int builtin_exec(char **argv) FAST_FUNC;
745static int builtin_exit(char **argv) FAST_FUNC;
746static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000747#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200748static int builtin_fg_bg(char **argv) FAST_FUNC;
749static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000750#endif
751#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200752static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000753#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200754#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200755static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200756#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000757#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200758static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000759#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400760#if ENABLE_PRINTF
761static int builtin_printf(char **argv) FAST_FUNC;
762#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200763static int builtin_pwd(char **argv) FAST_FUNC;
764static int builtin_read(char **argv) FAST_FUNC;
765static int builtin_set(char **argv) FAST_FUNC;
766static int builtin_shift(char **argv) FAST_FUNC;
767static int builtin_source(char **argv) FAST_FUNC;
768static int builtin_test(char **argv) FAST_FUNC;
769static int builtin_trap(char **argv) FAST_FUNC;
770static int builtin_type(char **argv) FAST_FUNC;
771static int builtin_true(char **argv) FAST_FUNC;
772static int builtin_umask(char **argv) FAST_FUNC;
773static int builtin_unset(char **argv) FAST_FUNC;
774static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000775#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200776static int builtin_break(char **argv) FAST_FUNC;
777static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000778#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000779#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200780static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000781#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000782
783/* Table of built-in functions. They can be forked or not, depending on
784 * context: within pipes, they fork. As simple commands, they do not.
785 * When used in non-forking context, they can change global variables
786 * in the parent shell process. If forked, of course they cannot.
787 * For example, 'unset foo | whatever' will parse and run, but foo will
788 * still be set at the end. */
789struct built_in_command {
Denys Vlasenko17323a62010-01-28 01:57:05 +0100790 const char *b_cmd;
791 int (*b_function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000792#if ENABLE_HUSH_HELP
Denys Vlasenko17323a62010-01-28 01:57:05 +0100793 const char *b_descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200794# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000795#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200796# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000797#endif
798};
799
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200800static const struct built_in_command bltins1[] = {
801 BLTIN("." , builtin_source , "Run commands in a file"),
802 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000803#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200804 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000805#endif
806#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200807 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000808#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200809 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000810#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200811 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000812#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200813 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
814 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
815 BLTIN("exit" , builtin_exit , "Exit"),
816 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000817#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200818 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000819#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000820#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200821 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000822#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000823#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200824 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000825#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200826#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200827 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200828#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000829#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200830 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000831#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200832 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000833#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200834 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000835#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200836 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
837 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
Denys Vlasenko82731b42010-05-17 17:49:52 +0200838#if ENABLE_HUSH_BASH_COMPAT
839 BLTIN("source" , builtin_source , "Run commands in a file"),
840#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200841 BLTIN("trap" , builtin_trap , "Trap signals"),
Denys Vlasenko651a2692010-03-23 16:25:17 +0100842 BLTIN("type" , builtin_type , "Show command type"),
Denys Vlasenkof3c742f2010-03-06 20:12:00 +0100843 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200844 BLTIN("umask" , builtin_umask , "Set file creation mask"),
845 BLTIN("unset" , builtin_unset , "Unset variables"),
846 BLTIN("wait" , builtin_wait , "Wait for process"),
847};
848/* For now, echo and test are unconditionally enabled.
849 * Maybe make it configurable? */
850static const struct built_in_command bltins2[] = {
851 BLTIN("[" , builtin_test , NULL),
852 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400853#if ENABLE_PRINTF
854 BLTIN("printf" , builtin_printf , NULL),
855#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200856 BLTIN("pwd" , builtin_pwd , NULL),
857 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000858};
859
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000860
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000861/* Debug printouts.
862 */
863#if HUSH_DEBUG
864/* prevent disasters with G.debug_indent < 0 */
865# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
866# define debug_enter() (G.debug_indent++)
867# define debug_leave() (G.debug_indent--)
868#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200869# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000870# define debug_enter() ((void)0)
871# define debug_leave() ((void)0)
872#endif
873
874#ifndef debug_printf
875# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
876#endif
877
878#ifndef debug_printf_parse
879# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
880#endif
881
882#ifndef debug_printf_exec
883#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
884#endif
885
886#ifndef debug_printf_env
887# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
888#endif
889
890#ifndef debug_printf_jobs
891# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
892# define DEBUG_JOBS 1
893#else
894# define DEBUG_JOBS 0
895#endif
896
897#ifndef debug_printf_expand
898# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
899# define DEBUG_EXPAND 1
900#else
901# define DEBUG_EXPAND 0
902#endif
903
Denys Vlasenko1e811b12010-05-22 03:12:29 +0200904#ifndef debug_printf_varexp
905# define debug_printf_varexp(...) (indent(), fprintf(stderr, __VA_ARGS__))
906#endif
907
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000908#ifndef debug_printf_glob
909# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
910# define DEBUG_GLOB 1
911#else
912# define DEBUG_GLOB 0
913#endif
914
915#ifndef debug_printf_list
916# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
917#endif
918
919#ifndef debug_printf_subst
920# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
921#endif
922
923#ifndef debug_printf_clean
924# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
925# define DEBUG_CLEAN 1
926#else
927# define DEBUG_CLEAN 0
928#endif
929
930#if DEBUG_EXPAND
931static void debug_print_strings(const char *prefix, char **vv)
932{
933 indent();
934 fprintf(stderr, "%s:\n", prefix);
935 while (*vv)
936 fprintf(stderr, " '%s'\n", *vv++);
937}
938#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200939# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000940#endif
941
942
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000943/* Leak hunting. Use hush_leaktool.sh for post-processing.
944 */
945#if LEAK_HUNTING
946static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000947{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000948 void *ptr = xmalloc((size + 0xff) & ~0xff);
949 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
950 return ptr;
951}
952static void *xxrealloc(int lineno, void *ptr, size_t size)
953{
954 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
955 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
956 return ptr;
957}
958static char *xxstrdup(int lineno, const char *str)
959{
960 char *ptr = xstrdup(str);
961 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
962 return ptr;
963}
964static void xxfree(void *ptr)
965{
966 fdprintf(2, "free %p\n", ptr);
967 free(ptr);
968}
Denys Vlasenko8391c482010-05-22 17:50:43 +0200969# define xmalloc(s) xxmalloc(__LINE__, s)
970# define xrealloc(p, s) xxrealloc(__LINE__, p, s)
971# define xstrdup(s) xxstrdup(__LINE__, s)
972# define free(p) xxfree(p)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000973#endif
974
975
976/* Syntax and runtime errors. They always abort scripts.
977 * In interactive use they usually discard unparsed and/or unexecuted commands
978 * and return to the prompt.
979 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
980 */
981#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200982# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000983# define syntax_error(lineno, msg) syntax_error(msg)
984# define syntax_error_at(lineno, msg) syntax_error_at(msg)
985# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
986# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
987# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000988#endif
989
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000990static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000991{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000992 va_list p;
993
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000994#if HUSH_DEBUG >= 2
995 bb_error_msg("hush.c:%u", lineno);
996#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000997 va_start(p, fmt);
998 bb_verror_msg(fmt, p, NULL);
999 va_end(p);
1000 if (!G_interactive_fd)
1001 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +00001002}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001003
1004static void syntax_error(unsigned lineno, const char *msg)
1005{
1006 if (msg)
1007 die_if_script(lineno, "syntax error: %s", msg);
1008 else
1009 die_if_script(lineno, "syntax error", NULL);
1010}
1011
1012static void syntax_error_at(unsigned lineno, const char *msg)
1013{
1014 die_if_script(lineno, "syntax error at '%s'", msg);
1015}
1016
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001017static void syntax_error_unterm_str(unsigned lineno, const char *s)
1018{
1019 die_if_script(lineno, "syntax error: unterminated %s", s);
1020}
1021
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001022/* It so happens that all such cases are totally fatal
1023 * even if shell is interactive: EOF while looking for closing
1024 * delimiter. There is nowhere to read stuff from after that,
1025 * it's EOF! The only choice is to terminate.
1026 */
1027static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001028static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001029{
Mike Frysinger6a46ab82009-06-01 14:14:36 -04001030 char msg[2] = { ch, '\0' };
1031 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001032 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001033}
1034
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001035static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001036{
1037 char msg[2];
1038 msg[0] = ch;
1039 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02001040 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001041}
1042
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001043#if HUSH_DEBUG < 2
1044# undef die_if_script
1045# undef syntax_error
1046# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001047# undef syntax_error_unterm_ch
1048# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001049# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001050#else
Denys Vlasenko606291b2009-09-23 23:15:43 +02001051# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00001052# define syntax_error(msg) syntax_error(__LINE__, msg)
1053# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1054# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1055# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1056# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001057#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001058
Denis Vlasenko552433b2009-04-04 19:29:21 +00001059
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001060#if ENABLE_HUSH_INTERACTIVE
1061static void cmdedit_update_prompt(void);
1062#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001063# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001064#endif
1065
1066
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001067/* Utility functions
1068 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00001069/* Replace each \x with x in place, return ptr past NUL. */
1070static char *unbackslash(char *src)
1071{
Denys Vlasenko71885402009-09-24 01:44:13 +02001072 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +00001073 while (1) {
1074 if (*src == '\\')
1075 src++;
1076 if ((*dst++ = *src++) == '\0')
1077 break;
1078 }
1079 return dst;
1080}
1081
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001082static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001083{
1084 int i;
1085 unsigned count1;
1086 unsigned count2;
1087 char **v;
1088
1089 v = strings;
1090 count1 = 0;
1091 if (v) {
1092 while (*v) {
1093 count1++;
1094 v++;
1095 }
1096 }
1097 count2 = 0;
1098 v = add;
1099 while (*v) {
1100 count2++;
1101 v++;
1102 }
1103 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1104 v[count1 + count2] = NULL;
1105 i = count2;
1106 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001107 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001108 return v;
1109}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001110#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001111static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1112{
1113 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1114 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1115 return ptr;
1116}
1117#define add_strings_to_strings(strings, add, need_to_dup) \
1118 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1119#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001120
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001121/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001122static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001123{
1124 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001125 v[0] = add;
1126 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00001127 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001128}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001129#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +00001130static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1131{
1132 char **ptr = add_string_to_strings(strings, add);
1133 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1134 return ptr;
1135}
1136#define add_string_to_strings(strings, add) \
1137 xx_add_string_to_strings(__LINE__, strings, add)
1138#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001139
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001140static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001141{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001142 char **v;
1143
1144 if (!strings)
1145 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001146 v = strings;
1147 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001148 free(*v);
1149 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001150 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001151 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001152}
1153
Denis Vlasenko76d50412008-06-10 16:19:39 +00001154
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001155/* Helpers for setting new $n and restoring them back
1156 */
1157typedef struct save_arg_t {
1158 char *sv_argv0;
1159 char **sv_g_argv;
1160 int sv_g_argc;
1161 smallint sv_g_malloced;
1162} save_arg_t;
1163
1164static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1165{
1166 int n;
1167
1168 sv->sv_argv0 = argv[0];
1169 sv->sv_g_argv = G.global_argv;
1170 sv->sv_g_argc = G.global_argc;
1171 sv->sv_g_malloced = G.global_args_malloced;
1172
1173 argv[0] = G.global_argv[0]; /* retain $0 */
1174 G.global_argv = argv;
1175 G.global_args_malloced = 0;
1176
1177 n = 1;
1178 while (*++argv)
1179 n++;
1180 G.global_argc = n;
1181}
1182
1183static void restore_G_args(save_arg_t *sv, char **argv)
1184{
1185 char **pp;
1186
1187 if (G.global_args_malloced) {
1188 /* someone ran "set -- arg1 arg2 ...", undo */
1189 pp = G.global_argv;
1190 while (*++pp) /* note: does not free $0 */
1191 free(*pp);
1192 free(G.global_argv);
1193 }
1194 argv[0] = sv->sv_argv0;
1195 G.global_argv = sv->sv_g_argv;
1196 G.global_argc = sv->sv_g_argc;
1197 G.global_args_malloced = sv->sv_g_malloced;
1198}
1199
1200
Denis Vlasenkod5762932009-03-31 11:22:57 +00001201/* Basic theory of signal handling in shell
1202 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001203 * This does not describe what hush does, rather, it is current understanding
1204 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001205 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1206 *
1207 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1208 * is finished or backgrounded. It is the same in interactive and
1209 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001210 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001211 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001212 * backgrounds (i.e. stops) or kills all members of currently running
1213 * pipe.
1214 *
1215 * Wait builtin in interruptible by signals for which user trap is set
1216 * or by SIGINT in interactive shell.
1217 *
1218 * Trap handlers will execute even within trap handlers. (right?)
1219 *
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001220 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1221 * except for handlers set to '' (empty string).
Denis Vlasenkod5762932009-03-31 11:22:57 +00001222 *
1223 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001224 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001225 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001226 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001227 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001228 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001229 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001230 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001231 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001232 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001233 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001234 *
1235 * SIGQUIT: ignore
1236 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001237 * SIGHUP (interactive):
1238 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001239 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001240 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1241 * that all pipe members are stopped. Try this in bash:
1242 * while :; do :; done - ^Z does not background it
1243 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001244 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001245 * of the command line, show prompt. NB: ^C does not send SIGINT
1246 * to interactive shell while shell is waiting for a pipe,
1247 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001248 * Example 1: this waits 5 sec, but does not execute ls:
1249 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1250 * Example 2: this does not wait and does not execute ls:
1251 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1252 * Example 3: this does not wait 5 sec, but executes ls:
1253 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001254 *
1255 * (What happens to signals which are IGN on shell start?)
1256 * (What happens with signal mask on shell start?)
1257 *
1258 * Implementation in hush
1259 * ======================
1260 * We use in-kernel pending signal mask to determine which signals were sent.
1261 * We block all signals which we don't want to take action immediately,
1262 * i.e. we block all signals which need to have special handling as described
1263 * above, and all signals which have traps set.
1264 * After each pipe execution, we extract any pending signals via sigtimedwait()
1265 * and act on them.
1266 *
1267 * unsigned non_DFL_mask: a mask of such "special" signals
1268 * sigset_t blocked_set: current blocked signal set
1269 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001270 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001271 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001272 * "trap 'cmd' SIGxxx":
1273 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001274 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001275 * unblock signals with special interactive handling
1276 * (child shell is not interactive),
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001277 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001278 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001279 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001280 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001281 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001282 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001283 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001284 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001285 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001286 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001287 * Standard says "When a subshell is entered, traps that are not being ignored
1288 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01001289 * are set to '' (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001290 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001291enum {
1292 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001293 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001294 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001295 | (1 << SIGHUP)
1296 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001297 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001298#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001299 | (1 << SIGTTIN)
1300 | (1 << SIGTTOU)
1301 | (1 << SIGTSTP)
1302#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001303};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001304
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001305#if ENABLE_HUSH_FAST
1306static void SIGCHLD_handler(int sig UNUSED_PARAM)
1307{
1308 G.count_SIGCHLD++;
1309//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1310}
1311#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001312
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001313#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001314
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001315/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001316# define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001317/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denys Vlasenko8391c482010-05-22 17:50:43 +02001318# define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001319
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001320/* Restores tty foreground process group, and exits.
1321 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001322 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001323 * or called directly with -EXITCODE.
1324 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001325static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001326static void sigexit(int sig)
1327{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001328 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001329 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001330
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001331 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001332 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001333 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1334 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001335
1336 /* Not a signal, just exit */
1337 if (sig <= 0)
1338 _exit(- sig);
1339
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001340 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001341}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001342#else
1343
Denys Vlasenko8391c482010-05-22 17:50:43 +02001344# define disable_restore_tty_pgrp_on_exit() ((void)0)
1345# define enable_restore_tty_pgrp_on_exit() ((void)0)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001346
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001347#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001348
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001349/* Restores tty foreground process group, and exits. */
1350static void hush_exit(int exitcode) NORETURN;
1351static void hush_exit(int exitcode)
1352{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001353 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1354 /* Prevent recursion:
1355 * trap "echo Hi; exit" EXIT; exit
1356 */
1357 char *argv[] = { NULL, G.traps[0], NULL };
1358 G.traps[0] = NULL;
1359 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001360 builtin_eval(argv);
1361 free(argv[1]);
1362 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001363
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001364#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001365 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001366 sigexit(- (exitcode & 0xff));
1367#else
1368 exit(exitcode);
1369#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001370}
1371
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001372static int check_and_run_traps(int sig)
1373{
Dan Fandrichfdd7b562010-06-18 22:37:42 -07001374 static const struct timespec zero_timespec;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001375 smalluint save_rcode;
1376 int last_sig = 0;
1377
1378 if (sig)
1379 goto jump_in;
1380 while (1) {
1381 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1382 if (sig <= 0)
1383 break;
1384 jump_in:
1385 last_sig = sig;
1386 if (G.traps && G.traps[sig]) {
1387 if (G.traps[sig][0]) {
1388 /* We have user-defined handler */
1389 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1390 save_rcode = G.last_exitcode;
1391 builtin_eval(argv);
1392 free(argv[1]);
1393 G.last_exitcode = save_rcode;
1394 } /* else: "" trap, ignoring signal */
1395 continue;
1396 }
1397 /* not a trap: special action */
1398 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001399#if ENABLE_HUSH_FAST
1400 case SIGCHLD:
1401 G.count_SIGCHLD++;
1402//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1403 break;
1404#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001405 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001406 /* Builtin was ^C'ed, make it look prettier: */
1407 bb_putchar('\n');
1408 G.flag_SIGINT = 1;
1409 break;
1410#if ENABLE_HUSH_JOB
1411 case SIGHUP: {
1412 struct pipe *job;
1413 /* bash is observed to signal whole process groups,
1414 * not individual processes */
1415 for (job = G.job_list; job; job = job->next) {
1416 if (job->pgrp <= 0)
1417 continue;
1418 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1419 if (kill(- job->pgrp, SIGHUP) == 0)
1420 kill(- job->pgrp, SIGCONT);
1421 }
1422 sigexit(SIGHUP);
1423 }
1424#endif
1425 default: /* ignored: */
1426 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1427 break;
1428 }
1429 }
1430 return last_sig;
1431}
1432
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001433
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001434static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001435{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001436 if (force || G.cwd == NULL) {
1437 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1438 * we must not try to free(bb_msg_unknown) */
1439 if (G.cwd == bb_msg_unknown)
1440 G.cwd = NULL;
1441 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1442 if (!G.cwd)
1443 G.cwd = bb_msg_unknown;
1444 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001445 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001446}
1447
Denis Vlasenko83506862007-11-23 13:11:42 +00001448
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001449/*
1450 * Shell and environment variable support
1451 */
1452static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001453{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001454 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001455 struct variable *cur;
1456 int len;
1457
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001458 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001459 pp = &G.top_var;
1460 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001461 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001462 return pp;
1463 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001464 }
1465 return NULL;
1466}
1467
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001468static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001469{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001470 struct variable **pp = get_ptr_to_local_var(name);
1471 if (pp)
1472 return *pp;
1473 return NULL;
1474}
1475
Denys Vlasenko03dad222010-01-12 23:29:57 +01001476static const char* FAST_FUNC get_local_var_value(const char *name)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001477{
Denys Vlasenko29082232010-07-16 13:52:32 +02001478 struct variable **vpp;
1479
1480 if (G.expanded_assignments) {
1481 char **cpp = G.expanded_assignments;
1482 int len = strlen(name);
1483 while (*cpp) {
1484 char *cp = *cpp;
1485 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1486 return cp + len + 1;
1487 cpp++;
1488 }
1489 }
1490
1491 vpp = get_ptr_to_local_var(name);
1492 if (vpp)
1493 return strchr((*vpp)->varstr, '=') + 1;
1494
Denys Vlasenkodea47882009-10-09 15:40:49 +02001495 if (strcmp(name, "PPID") == 0)
1496 return utoa(G.root_ppid);
1497 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001498#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001499 if (strcmp(name, "RANDOM") == 0) {
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001500 return utoa(next_random(&G.random_gen));
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001501 }
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001502#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001503 return NULL;
1504}
1505
1506/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001507 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001508 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001509 * 0: do not change export flag
1510 * (if creating new variable, flag will be 0)
1511 * 1: set export flag and putenv the variable
1512 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001513 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001514 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001515#if !BB_MMU && ENABLE_HUSH_LOCAL
1516/* all params are used */
1517#elif BB_MMU && ENABLE_HUSH_LOCAL
1518#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1519 set_local_var(str, flg_export, local_lvl)
1520#elif BB_MMU && !ENABLE_HUSH_LOCAL
1521#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001522 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001523#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1524#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1525 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001526#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001527static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001528{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001529 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001530 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001531 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001532 int name_len;
1533
Denis Vlasenko950bd722009-04-21 11:23:56 +00001534 eq_sign = strchr(str, '=');
1535 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001536 free(str);
1537 return -1;
1538 }
1539
Denis Vlasenko950bd722009-04-21 11:23:56 +00001540 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001541 var_pp = &G.top_var;
1542 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001543 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001544 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001545 continue;
1546 }
1547 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001548 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001549#if !BB_MMU
1550 if (!flg_read_only)
1551#endif
1552 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001553 free(str);
1554 return -1;
1555 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001556 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001557 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1558 *eq_sign = '\0';
1559 unsetenv(str);
1560 *eq_sign = '=';
1561 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001562#if ENABLE_HUSH_LOCAL
1563 if (cur->func_nest_level < local_lvl) {
1564 /* New variable is declared as local,
1565 * and existing one is global, or local
1566 * from enclosing function.
1567 * Remove and save old one: */
1568 *var_pp = cur->next;
1569 cur->next = *G.shadowed_vars_pp;
1570 *G.shadowed_vars_pp = cur;
1571 /* bash 3.2.33(1) and exported vars:
1572 * # export z=z
1573 * # f() { local z=a; env | grep ^z; }
1574 * # f
1575 * z=a
1576 * # env | grep ^z
1577 * z=z
1578 */
1579 if (cur->flg_export)
1580 flg_export = 1;
1581 break;
1582 }
1583#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001584 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001585 free_and_exp:
1586 free(str);
1587 goto exp;
1588 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001589 if (cur->max_len != 0) {
1590 if (cur->max_len >= strlen(str)) {
1591 /* This one is from startup env, reuse space */
1592 strcpy(cur->varstr, str);
1593 goto free_and_exp;
1594 }
1595 } else {
1596 /* max_len == 0 signifies "malloced" var, which we can
1597 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001598 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001599 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001600 cur->max_len = 0;
1601 goto set_str_and_exp;
1602 }
1603
Denys Vlasenko295fef82009-06-03 12:47:26 +02001604 /* Not found - create new variable struct */
1605 cur = xzalloc(sizeof(*cur));
1606#if ENABLE_HUSH_LOCAL
1607 cur->func_nest_level = local_lvl;
1608#endif
1609 cur->next = *var_pp;
1610 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001611
1612 set_str_and_exp:
1613 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001614#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001615 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001616#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001617 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001618 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001619 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001620 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1621 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001622 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001623 if (flg_export == -1) {
1624 cur->flg_export = 0;
1625 /* unsetenv was already done */
1626 } else {
1627 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1628 return putenv(cur->varstr);
1629 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001630 }
1631 return 0;
1632}
1633
Denys Vlasenko6db47842009-09-05 20:15:17 +02001634/* Used at startup and after each cd */
1635static void set_pwd_var(int exp)
1636{
1637 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1638 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1639}
1640
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001641static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001642{
1643 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001644 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001645
1646 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001647 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001648 var_pp = &G.top_var;
1649 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001650 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1651 if (cur->flg_read_only) {
1652 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001653 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001654 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001655 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001656 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1657 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001658 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1659 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001660 if (!cur->max_len)
1661 free(cur->varstr);
1662 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001663 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001664 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001665 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001666 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001667 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001668}
1669
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001670static int unset_local_var(const char *name)
1671{
1672 return unset_local_var_len(name, strlen(name));
1673}
1674
1675static void unset_vars(char **strings)
1676{
1677 char **v;
1678
1679 if (!strings)
1680 return;
1681 v = strings;
1682 while (*v) {
1683 const char *eq = strchrnul(*v, '=');
1684 unset_local_var_len(*v, (int)(eq - *v));
1685 v++;
1686 }
1687 free(strings);
1688}
1689
Mike Frysinger98c52642009-04-02 10:02:37 +00001690#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko8391c482010-05-22 17:50:43 +02001691# define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1692# define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
Denys Vlasenko03dad222010-01-12 23:29:57 +01001693static char* FAST_FUNC endofname(const char *name)
Mike Frysinger98c52642009-04-02 10:02:37 +00001694{
1695 char *p;
1696
1697 p = (char *) name;
1698 if (!is_name(*p))
1699 return p;
1700 while (*++p) {
1701 if (!is_in_name(*p))
1702 break;
1703 }
1704 return p;
1705}
Denys Vlasenko6b01b712010-01-24 22:52:21 +01001706#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001707
Denys Vlasenko03dad222010-01-12 23:29:57 +01001708static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
Mike Frysinger98c52642009-04-02 10:02:37 +00001709{
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001710 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko03dad222010-01-12 23:29:57 +01001711 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001712}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001713
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001714
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001715/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001716 * Helpers for "var1=val1 var2=val2 cmd" feature
1717 */
1718static void add_vars(struct variable *var)
1719{
1720 struct variable *next;
1721
1722 while (var) {
1723 next = var->next;
1724 var->next = G.top_var;
1725 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001726 if (var->flg_export) {
1727 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001728 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001729 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001730 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001731 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001732 var = next;
1733 }
1734}
1735
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001736static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001737{
1738 char **s;
1739 struct variable *old = NULL;
1740
1741 if (!strings)
1742 return old;
1743 s = strings;
1744 while (*s) {
1745 struct variable *var_p;
1746 struct variable **var_pp;
1747 char *eq;
1748
1749 eq = strchr(*s, '=');
1750 if (eq) {
1751 *eq = '\0';
1752 var_pp = get_ptr_to_local_var(*s);
1753 *eq = '=';
1754 if (var_pp) {
1755 /* Remove variable from global linked list */
1756 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001757 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001758 *var_pp = var_p->next;
1759 /* Add it to returned list */
1760 var_p->next = old;
1761 old = var_p;
1762 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001763 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001764 }
1765 s++;
1766 }
1767 return old;
1768}
1769
1770
1771/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001772 * in_str support
1773 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001774static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001775{
Denys Vlasenko8391c482010-05-22 17:50:43 +02001776 int ch = *i->p;
1777 if (ch != '\0') {
1778 i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001779 return ch;
Denys Vlasenko8391c482010-05-22 17:50:43 +02001780 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001781 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001782}
1783
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001784static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001785{
1786 return *i->p;
1787}
1788
1789#if ENABLE_HUSH_INTERACTIVE
1790
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001791static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001792{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001793 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001794 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001795 if (G.PS1 == NULL)
1796 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001797 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001798 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001799 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001800 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001801 if (G.PS2 == NULL)
1802 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001803}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001804
1805static const char* setup_prompt_string(int promptmode)
1806{
1807 const char *prompt_str;
1808 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001809 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1810 /* Set up the prompt */
1811 if (promptmode == 0) { /* PS1 */
1812 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001813 /* bash uses $PWD value, even if it is set by user.
1814 * It uses current dir only if PWD is unset.
1815 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001816 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001817 prompt_str = G.PS1;
1818 } else
1819 prompt_str = G.PS2;
1820 } else
1821 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001822 debug_printf("result '%s'\n", prompt_str);
1823 return prompt_str;
1824}
1825
1826static void get_user_input(struct in_str *i)
1827{
1828 int r;
1829 const char *prompt_str;
1830
1831 prompt_str = setup_prompt_string(i->promptmode);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001832# if ENABLE_FEATURE_EDITING
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001833 /* Enable command line editing only while a command line
1834 * is actually being read */
1835 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001836 G.flag_SIGINT = 0;
1837 /* buglet: SIGINT will not make new prompt to appear _at once_,
1838 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001839 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 +00001840 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001841 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001842 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001843 i->eof_flag = (r < 0);
1844 if (i->eof_flag) { /* EOF/error detected */
1845 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1846 G.user_input_buf[1] = '\0';
1847 }
Denys Vlasenko8391c482010-05-22 17:50:43 +02001848# else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001849 do {
1850 G.flag_SIGINT = 0;
1851 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001852 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001853 G.user_input_buf[0] = r = fgetc(i->file);
1854 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001855//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001856 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001857 i->eof_flag = (r == EOF);
Denys Vlasenko8391c482010-05-22 17:50:43 +02001858# endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001859 i->p = G.user_input_buf;
1860}
1861
1862#endif /* INTERACTIVE */
1863
1864/* This is the magic location that prints prompts
1865 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001866static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001867{
1868 int ch;
1869
1870 /* If there is data waiting, eat it up */
1871 if (i->p && *i->p) {
1872#if ENABLE_HUSH_INTERACTIVE
1873 take_cached:
1874#endif
1875 ch = *i->p++;
1876 if (i->eof_flag && !*i->p)
1877 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001878 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001879 } else {
1880 /* need to double check i->file because we might be doing something
1881 * more complicated by now, like sourcing or substituting. */
1882#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001883 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001884 do {
1885 get_user_input(i);
1886 } while (!*i->p); /* need non-empty line */
1887 i->promptmode = 1; /* PS2 */
1888 i->promptme = 0;
1889 goto take_cached;
1890 }
1891#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001892 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001893 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001894 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001895#if ENABLE_HUSH_INTERACTIVE
1896 if (ch == '\n')
1897 i->promptme = 1;
1898#endif
1899 return ch;
1900}
1901
Denis Vlasenko913a2012009-04-05 22:17:04 +00001902/* All callers guarantee this routine will never
1903 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001904 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001905static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001906{
1907 int ch;
1908 if (i->p && *i->p) {
1909 if (i->eof_flag && !i->p[1])
1910 return EOF;
1911 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001912 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001913 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001914 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001915 i->eof_flag = (ch == EOF);
1916 i->peek_buf[0] = ch;
1917 i->peek_buf[1] = '\0';
1918 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001919 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001920 return ch;
1921}
1922
1923static void setup_file_in_str(struct in_str *i, FILE *f)
1924{
1925 i->peek = file_peek;
1926 i->get = file_get;
1927#if ENABLE_HUSH_INTERACTIVE
1928 i->promptme = 1;
1929 i->promptmode = 0; /* PS1 */
1930#endif
1931 i->file = f;
1932 i->p = NULL;
1933}
1934
1935static void setup_string_in_str(struct in_str *i, const char *s)
1936{
1937 i->peek = static_peek;
1938 i->get = static_get;
1939#if ENABLE_HUSH_INTERACTIVE
1940 i->promptme = 1;
1941 i->promptmode = 0; /* PS1 */
1942#endif
1943 i->p = s;
1944 i->eof_flag = 0;
1945}
1946
1947
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001948/*
1949 * o_string support
1950 */
1951#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001952
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001953static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001954{
1955 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001956 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001957 if (o->data)
1958 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001959}
1960
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001961static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001962{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001963 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001964 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001965}
1966
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001967static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1968{
1969 free(o->data);
1970}
1971
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001972static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001973{
1974 if (o->length + len > o->maxlen) {
1975 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1976 o->data = xrealloc(o->data, 1 + o->maxlen);
1977 }
1978}
1979
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001980static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001981{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001982 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1983 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001984 o->data[o->length] = ch;
1985 o->length++;
1986 o->data[o->length] = '\0';
1987}
1988
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001989static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001990{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001991 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001992 memcpy(&o->data[o->length], str, len);
1993 o->length += len;
1994 o->data[o->length] = '\0';
1995}
1996
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001997static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001998{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001999 o_addblock(o, str, strlen(str));
2000}
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002001
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002002#if !BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002003static void nommu_addchr(o_string *o, int ch)
2004{
2005 if (o)
2006 o_addchr(o, ch);
2007}
2008#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02002009# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002010#endif
2011
2012static void o_addstr_with_NUL(o_string *o, const char *str)
2013{
2014 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00002015}
2016
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002017static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00002018{
2019 while (len) {
2020 o_addchr(o, *str);
2021 if (*str++ == '\\'
2022 && (*str != '*' && *str != '?' && *str != '[')
2023 ) {
2024 o_addchr(o, '\\');
2025 }
2026 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();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002131 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
2132 prefix, list, n, string_start, o->length, o->maxlen);
2133 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
2566 if (strchr(str, '$') == NULL
2567#if ENABLE_HUSH_TICK
2568 && strchr(str, '`') == NULL
2569#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> */
2743 char *var;
2744 char first_char;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002745 char exp_op;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002746 char exp_save = exp_save; /* for compiler */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002747 char *exp_saveptr; /* points to expansion operator */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002748 char *exp_word = exp_word; /* for compiler */
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002749
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002750 var = arg;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002751 *p = '\0';
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002752 exp_saveptr = arg[1] ? strchr("%#:-=+?", arg[1]) : NULL;
2753 first_char = arg[0] = first_ch & 0x7f;
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002754 exp_op = 0;
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002755
2756 if (first_char == '#' && arg[1] && !exp_saveptr) {
Mike Frysinger6379bb42009-03-28 18:55:03 +00002757 /* handle length expansion ${#var} */
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002758 var++;
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002759 exp_op = 'L';
Mike Frysinger6379bb42009-03-28 18:55:03 +00002760 } else {
2761 /* maybe handle parameter expansion */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002762 if (exp_saveptr /* if 2nd char is one of expansion operators */
2763 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
2764 ) {
2765 /* ${?:0}, ${#[:]%0} etc */
2766 exp_saveptr = var + 1;
2767 } else {
2768 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
2769 exp_saveptr = var+1 + strcspn(var+1, "%#:-=+?");
2770 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002771 exp_op = exp_save = *exp_saveptr;
2772 if (exp_op) {
2773 exp_word = exp_saveptr + 1;
2774 if (exp_op == ':') {
2775 exp_op = *exp_word++;
2776 if (ENABLE_HUSH_BASH_COMPAT
2777 && (exp_op == '\0' || !strchr("%#:-=+?"+3, exp_op))
2778 ) {
2779 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
2780 exp_op = ':';
2781 exp_word--;
2782 }
2783 }
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002784 *exp_saveptr = '\0';
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002785 } /* else: it's not an expansion op, but bare ${var} */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002786 }
2787
2788 /* lookup the variable in question */
2789 if (isdigit(var[0])) {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02002790 /* parse_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002791 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002792 if (i < G.global_argc)
2793 val = G.global_argv[i];
2794 /* else val remains NULL: $N with too big N */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002795 } else {
2796 switch (var[0]) {
2797 case '$': /* pid */
2798 val = utoa(G.root_pid);
2799 break;
2800 case '!': /* bg pid */
2801 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2802 break;
2803 case '?': /* exitcode */
2804 val = utoa(G.last_exitcode);
2805 break;
2806 case '#': /* argc */
2807 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2808 break;
2809 default:
2810 val = get_local_var_value(var);
2811 }
2812 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002813
2814 /* handle any expansions */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002815 if (exp_op == 'L') {
Denys Vlasenkoee0775d2010-05-20 16:37:53 +02002816 debug_printf_expand("expand: length(%s)=", val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002817 val = utoa(val ? strlen(val) : 0);
2818 debug_printf_expand("%s\n", val);
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002819 } else if (exp_op) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002820 if (exp_op == '%' || exp_op == '#') {
Denys Vlasenko53b51332010-05-20 21:46:45 +02002821 /* Standard-mandated substring removal ops:
2822 * ${parameter%word} - remove smallest suffix pattern
2823 * ${parameter%%word} - remove largest suffix pattern
2824 * ${parameter#word} - remove smallest prefix pattern
2825 * ${parameter##word} - remove largest prefix pattern
2826 *
2827 * Word is expanded to produce a glob pattern.
2828 * Then var's value is matched to it and matching part removed.
2829 */
Mike Frysinger57e74672009-04-09 23:00:33 +00002830 if (val) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002831 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002832 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002833 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002834 if (exp_op == *exp_word) /* ## or %% */
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002835 exp_word++;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002836 val = to_be_freed = xstrdup(val);
Denys Vlasenko74369502010-05-21 19:52:01 +02002837 {
2838 char *exp_exp_word = expand_pseudo_dquoted(exp_word);
2839 if (exp_exp_word)
2840 exp_word = exp_exp_word;
2841 loc = scan(to_be_freed, exp_word, match_at_left);
2842 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
2843 // exp_op, to_be_freed, exp_word, loc);
2844 free(exp_exp_word);
2845 }
2846 if (loc) { /* match was found */
2847 if (match_at_left) /* # or ## */
2848 val = loc;
2849 else /* % or %% */
2850 *loc = '\0';
2851 }
Mike Frysinger57e74672009-04-09 23:00:33 +00002852 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002853 } else if (exp_op == ':') {
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02002854#if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002855 /* It's ${var:N[:M]} bashism.
2856 * Note that in encoded form it has TWO parts:
2857 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002858 */
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002859 arith_t beg, len;
2860 int errcode = 0;
2861
2862 beg = expand_and_evaluate_arith(exp_word, &errcode);
2863 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
2864 *p++ = SPECIAL_VAR_SYMBOL;
2865 exp_word = p;
2866 p = strchr(p, SPECIAL_VAR_SYMBOL);
2867 *p = '\0';
2868 len = expand_and_evaluate_arith(exp_word, &errcode);
2869 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
2870
2871 if (errcode >= 0 && len >= 0) { /* bash compat: len < 0 is illegal */
2872 if (beg < 0) /* bash compat */
2873 beg = 0;
2874 debug_printf_varexp("from val:'%s'\n", val);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002875 if (len == 0 || !val || beg >= strlen(val))
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002876 val = "";
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002877 else {
2878 /* Paranoia. What if user entered 9999999999999
2879 * which fits in arith_t but not int? */
2880 if (len >= INT_MAX)
2881 len = INT_MAX;
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002882 val = to_be_freed = xstrndup(val + beg, len);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002883 }
2884 debug_printf_varexp("val:'%s'\n", val);
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002885 } else
2886#endif
2887 {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02002888 die_if_script("malformed ${%s:...}", var);
Denys Vlasenko73e013f2010-05-21 15:24:12 +02002889 val = "";
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002890 }
2891 } else { /* one of "-=+?" */
Denys Vlasenko53b51332010-05-20 21:46:45 +02002892 /* Standard-mandated substitution ops:
2893 * ${var?word} - indicate error if unset
2894 * If var is unset, word (or a message indicating it is unset
2895 * if word is null) is written to standard error
2896 * and the shell exits with a non-zero exit status.
2897 * Otherwise, the value of var is substituted.
2898 * ${var-word} - use default value
2899 * If var is unset, word is substituted.
2900 * ${var=word} - assign and use default value
2901 * If var is unset, word is assigned to var.
2902 * In all cases, final value of var is substituted.
2903 * ${var+word} - use alternative value
2904 * If var is unset, null is substituted.
2905 * Otherwise, word is substituted.
2906 *
2907 * Word is subjected to tilde expansion, parameter expansion,
2908 * command substitution, and arithmetic expansion.
2909 * If word is not needed, it is not expanded.
2910 *
2911 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
2912 * but also treat null var as if it is unset.
2913 */
2914 int use_word = (!val || ((exp_save == ':') && !val[0]));
Mike Frysingera4f331d2009-04-07 06:03:22 +00002915 if (exp_op == '+')
Denys Vlasenko53b51332010-05-20 21:46:45 +02002916 use_word = !use_word;
Mike Frysingera4f331d2009-04-07 06:03:22 +00002917 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
Denys Vlasenko53b51332010-05-20 21:46:45 +02002918 (exp_save == ':') ? "true" : "false", use_word);
2919 if (use_word) {
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002920 to_be_freed = expand_pseudo_dquoted(exp_word);
2921 if (to_be_freed)
2922 exp_word = to_be_freed;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002923 if (exp_op == '?') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002924 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002925 die_if_script("%s: %s",
2926 var,
2927 exp_word[0] ? exp_word : "parameter null or not set"
2928 );
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002929//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002930 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002931 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002932 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002933
Mike Frysingera4f331d2009-04-07 06:03:22 +00002934 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002935 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002936 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002937 /* mimic bash message */
2938 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002939 val = NULL;
2940 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002941 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002942 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002943 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002944 }
2945 }
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02002946 } /* one of "-=+?" */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002947
Denys Vlasenkoe3be7842010-05-20 16:27:42 +02002948 *exp_saveptr = exp_save;
Denys Vlasenko4d8e5fd2010-05-21 01:15:42 +02002949 } /* if (exp_op) */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002950
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002951 arg[0] = first_ch;
2952#if ENABLE_HUSH_TICK
2953 store_val:
2954#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002955 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002956 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002957 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002958 /* unquoted var's contents should be globbed, so don't escape */
2959 smallint sv = output->o_escape;
2960 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002961 n = expand_on_ifs(output, n, val);
2962 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002963 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002964 }
2965 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002966 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002967 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002968 } /* default: */
2969 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002970
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002971 if (val) {
2972 o_addQstr(output, val, strlen(val));
2973 }
Denys Vlasenko3f78cec2010-05-21 17:54:46 +02002974 free(to_be_freed);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002975 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002976 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002977 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002978
2979#if ENABLE_HUSH_TICK
2980 o_free(&subst_result);
2981#endif
2982 arg = ++p;
2983 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2984
2985 if (arg[0]) {
2986 debug_print_list("expand_vars_to_list[a]", output, n);
2987 /* this part is literal, and it was already pre-quoted
2988 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002989 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002990 debug_print_list("expand_vars_to_list[b]", output, n);
2991 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2992 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2993 ) {
2994 n--;
2995 /* allow to reuse list[n] later without re-growth */
2996 output->has_empty_slot = 1;
2997 } else {
2998 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002999 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003000 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00003001}
3002
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003003static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00003004{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003005 int n;
3006 char **list;
3007 char **v;
3008 o_string output = NULL_O_STRING;
3009
3010 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00003011 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003012 /* (unquoted $var will temporarily switch it off) */
3013 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003014 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003015
3016 n = 0;
3017 v = argv;
3018 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003019 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003020 v++;
3021 }
3022 debug_print_list("expand_variables", &output, n);
3023
3024 /* output.data (malloced in one block) gets returned in "list" */
3025 list = o_finalize_list(&output, n);
3026 debug_print_strings("expand_variables[1]", list);
3027 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00003028}
3029
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003030static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003031{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003032 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00003033}
3034
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003035#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003036static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
3037{
3038 return expand_variables(argv, 0x80);
3039}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003040#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003041
3042#ifdef CMD_SINGLEWORD_NOGLOB_COND
3043static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
3044{
3045 int n;
3046 char **list;
3047 char **v;
3048 o_string output = NULL_O_STRING;
3049
3050 n = 0;
3051 v = argv;
3052 while (*v) {
3053 int is_var = is_well_formed_var_name(*v, '=');
3054 /* is_var * 0x80: singleword expansion for vars */
3055 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
3056
3057 /* Subtle! expand_vars_to_list did not glob last word yet.
3058 * It does this only when fed with further data.
3059 * Therefore we set globbing flags AFTER it, not before:
3060 */
3061
3062 /* if it is not recognizably abc=...; then: */
3063 output.o_escape = !is_var; /* protect against globbing for "$var" */
3064 /* (unquoted $var will temporarily switch it off) */
3065 output.o_glob = !is_var; /* and indeed do globbing */
3066 v++;
3067 }
3068 debug_print_list("expand_cond", &output, n);
3069
3070 /* output.data (malloced in one block) gets returned in "list" */
3071 list = o_finalize_list(&output, n);
3072 debug_print_strings("expand_cond[1]", list);
3073 return list;
3074}
3075#endif
3076
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003077/* Used for expansion of right hand of assignments */
3078/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
3079 * "v=/bin/c*" */
3080static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00003081{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003082 char *argv[2], **list;
3083
3084 argv[0] = (char*)str;
3085 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003086 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003087 if (HUSH_DEBUG)
3088 if (!list[0] || list[1])
3089 bb_error_msg_and_die("BUG in varexp2");
3090 /* actually, just move string 2*sizeof(char*) bytes back */
3091 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02003092 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003093 debug_printf_expand("string_to_string='%s'\n", (char*)list);
3094 return (char*)list;
3095}
3096
3097/* Used for "eval" builtin */
3098static char* expand_strvec_to_string(char **argv)
3099{
3100 char **list;
3101
3102 list = expand_variables(argv, 0x80);
3103 /* Convert all NULs to spaces */
3104 if (list[0]) {
3105 int n = 1;
3106 while (list[n]) {
3107 if (HUSH_DEBUG)
3108 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
3109 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00003110 /* bash uses ' ' regardless of $IFS contents */
3111 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003112 n++;
3113 }
3114 }
3115 overlapping_strcpy((char*)list, list[0]);
3116 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
3117 return (char*)list;
3118}
3119
3120static char **expand_assignments(char **argv, int count)
3121{
3122 int i;
Denys Vlasenko29082232010-07-16 13:52:32 +02003123 char **p;
3124
3125 G.expanded_assignments = p = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003126 /* Expand assignments into one string each */
3127 for (i = 0; i < count; i++) {
Denys Vlasenko29082232010-07-16 13:52:32 +02003128 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i]));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003129 }
Denys Vlasenko29082232010-07-16 13:52:32 +02003130 G.expanded_assignments = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003131 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00003132}
3133
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003134
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003135#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003136/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003137void re_execute_shell(char ***to_free, const char *s,
3138 char *g_argv0, char **g_argv,
3139 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003140
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003141static void reset_traps_to_defaults(void)
3142{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003143 /* This function is always called in a child shell
3144 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003145 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003146 unsigned sig;
3147 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003148
Denys Vlasenko67f71862009-09-25 14:21:06 +02003149 /* Child shells are not interactive.
3150 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
3151 * Testcase: (while :; do :; done) + ^Z should background.
3152 * Same goes for SIGTERM, SIGHUP, SIGINT.
3153 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003154 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02003155 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003156
Denys Vlasenko67f71862009-09-25 14:21:06 +02003157 /* Switching off SPECIAL_INTERACTIVE_SIGS.
3158 * Stupid. It can be done with *single* &= op, but we can't use
3159 * the fact that G.blocked_set is implemented as a bitmask
3160 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003161 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
3162 sig = 1;
3163 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02003164 if (mask & 1) {
3165 /* Careful. Only if no trap or trap is not "" */
3166 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
3167 sigdelset(&G.blocked_set, sig);
3168 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003169 mask >>= 1;
3170 if (!mask)
3171 break;
3172 sig++;
3173 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02003174 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003175 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003176
3177 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003178 mask = G.non_DFL_mask;
3179 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02003180 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003181 continue;
3182 free(G.traps[sig]);
3183 G.traps[sig] = NULL;
3184 /* There is no signal for 0 (EXIT) */
3185 if (sig == 0)
3186 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02003187 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003188 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02003189 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00003190 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003191 continue;
3192 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003193 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00003194 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003195}
3196
3197#else /* !BB_MMU */
3198
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003199static void re_execute_shell(char ***to_free, const char *s,
3200 char *g_argv0, char **g_argv,
3201 char **builtin_argv) NORETURN;
3202static void re_execute_shell(char ***to_free, const char *s,
3203 char *g_argv0, char **g_argv,
3204 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003205{
Denys Vlasenko8391c482010-05-22 17:50:43 +02003206# define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003207 /* delims + 2 * (number of bytes in printed hex numbers) */
3208 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003209 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003210 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003211# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003212 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003213# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003214 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003215 unsigned cnt;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003216 unsigned long long empty_trap_mask;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003217
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003218 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003219 argv = heredoc_argv;
3220 argv[0] = (char *) G.argv0_for_re_execing;
3221 argv[1] = (char *) "-<";
3222 argv[2] = (char *) s;
3223 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00003224 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003225 goto do_exec;
3226 }
3227
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003228 cnt = 0;
3229 pp = builtin_argv;
3230 if (pp) while (*pp++)
3231 cnt++;
3232
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003233 empty_trap_mask = 0;
3234 if (G.traps) {
3235 int sig;
3236 for (sig = 1; sig < NSIG; sig++) {
3237 if (G.traps[sig] && !G.traps[sig][0])
3238 empty_trap_mask |= 1LL << sig;
3239 }
3240 }
3241
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003242 sprintf(param_buf, NOMMU_HACK_FMT
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003243 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02003244 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003245 , (unsigned) G.last_bg_pid
3246 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003247 , cnt
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003248 , empty_trap_mask
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003249 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003250 );
Denys Vlasenko8391c482010-05-22 17:50:43 +02003251# undef NOMMU_HACK_FMT
Denys Vlasenko6c93b242010-01-12 19:28:10 +01003252 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003253 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003254 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003255 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003256 for (cur = G.top_var; cur; cur = cur->next) {
3257 if (!cur->flg_export || cur->flg_read_only)
3258 cnt += 2;
3259 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003260# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003261 for (funcp = G.top_func; funcp; funcp = funcp->next)
3262 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003263# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003264 pp = g_argv;
3265 while (*pp++)
3266 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003267 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003268 *pp++ = (char *) G.argv0_for_re_execing;
3269 *pp++ = param_buf;
3270 for (cur = G.top_var; cur; cur = cur->next) {
3271 if (cur->varstr == hush_version_str)
3272 continue;
3273 if (cur->flg_read_only) {
3274 *pp++ = (char *) "-R";
3275 *pp++ = cur->varstr;
3276 } else if (!cur->flg_export) {
3277 *pp++ = (char *) "-V";
3278 *pp++ = cur->varstr;
3279 }
3280 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003281# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00003282 for (funcp = G.top_func; funcp; funcp = funcp->next) {
3283 *pp++ = (char *) "-F";
3284 *pp++ = funcp->name;
3285 *pp++ = funcp->body_as_string;
3286 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003287# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003288 /* We can pass activated traps here. Say, -Tnn:trap_string
3289 *
3290 * However, POSIX says that subshells reset signals with traps
3291 * to SIG_DFL.
3292 * I tested bash-3.2 and it not only does that with true subshells
3293 * of the form ( list ), but with any forked children shells.
3294 * I set trap "echo W" WINCH; and then tried:
3295 *
3296 * { echo 1; sleep 20; echo 2; } &
3297 * while true; do echo 1; sleep 20; echo 2; break; done &
3298 * true | { echo 1; sleep 20; echo 2; } | cat
3299 *
3300 * In all these cases sending SIGWINCH to the child shell
3301 * did not run the trap. If I add trap "echo V" WINCH;
3302 * _inside_ group (just before echo 1), it works.
3303 *
3304 * I conclude it means we don't need to pass active traps here.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01003305 * Even if we would use signal handlers instead of signal masking
3306 * in order to implement trap handling,
3307 * exec syscall below resets signals to SIG_DFL for us.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003308 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003309 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003310 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003311 if (builtin_argv) {
3312 while (*++builtin_argv)
3313 *pp++ = *builtin_argv;
3314 *pp++ = (char *) "";
3315 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003316 *pp++ = g_argv0;
3317 while (*g_argv)
3318 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003319 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003320 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003321
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003322 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003323 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3324 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003325 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003326 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003327 if (argv[0][0] == '/')
3328 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003329 xfunc_error_retval = 127;
3330 bb_error_msg_and_die("can't re-execute the shell");
3331}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003332#endif /* !BB_MMU */
3333
3334
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003335static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003336{
3337 struct fd_pair pair;
3338 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003339 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003340 /* the _body_ of heredoc (misleading field name) */
3341 const char *heredoc = redir->rd_filename;
3342 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003343#if !BB_MMU
3344 char **to_free;
3345#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003346
3347 expanded = NULL;
3348 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3349 expanded = expand_pseudo_dquoted(heredoc);
3350 if (expanded)
3351 heredoc = expanded;
3352 }
3353 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003354
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003355 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003356 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003357 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003358
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003359 /* Try writing without forking. Newer kernels have
3360 * dynamically growing pipes. Must use non-blocking write! */
3361 ndelay_on(pair.wr);
3362 while (1) {
3363 written = write(pair.wr, heredoc, len);
3364 if (written <= 0)
3365 break;
3366 len -= written;
3367 if (len == 0) {
3368 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00003369 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003370 return;
3371 }
3372 heredoc += written;
3373 }
3374 ndelay_off(pair.wr);
3375
3376 /* Okay, pipe buffer was not big enough */
3377 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003378 * for the unsuspecting parent process. Child creates a grandchild
3379 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003380 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003381#if !BB_MMU
3382 to_free = NULL;
3383#endif
Pascal Bellard926031b2010-07-04 15:32:38 +02003384 pid = xvfork();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003385 if (pid == 0) {
3386 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003387 disable_restore_tty_pgrp_on_exit();
Pascal Bellard926031b2010-07-04 15:32:38 +02003388 pid = BB_MMU ? xfork() : xvfork();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003389 if (pid != 0)
3390 _exit(0);
3391 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003392 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003393#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003394 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003395 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003396#else
3397 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003398 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003399 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003400#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003401 }
3402 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003403#if ENABLE_HUSH_FAST
3404 G.count_SIGCHLD++;
3405//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3406#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003407 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003408#if !BB_MMU
3409 free(to_free);
3410#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003411 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003412 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003413 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003414}
3415
Eric Andersen25f27032001-04-26 23:22:31 +00003416/* squirrel != NULL means we squirrel away copies of stdin, stdout,
3417 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003418static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00003419{
3420 int openfd, mode;
3421 struct redir_struct *redir;
3422
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003423 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003424 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003425 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003426 if (squirrel && redir->rd_fd < 3
3427 && squirrel[redir->rd_fd] < 0
3428 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003429 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003430 }
3431 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3432 * of the heredoc */
3433 debug_printf_parse("set heredoc '%s'\n",
3434 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003435 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00003436 continue;
3437 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003438
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003439 if (redir->rd_dup == REDIRFD_TO_FILE) {
3440 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003441 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003442 if (redir->rd_filename == NULL) {
3443 /* Something went wrong in the parse.
3444 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003445 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003446 continue;
3447 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003448 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003449 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003450 openfd = open_or_warn(p, mode);
3451 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00003452 if (openfd < 0) {
3453 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003454 * bash and ash both lose it as well (though zsh doesn't!) */
3455//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00003456 return 1;
3457 }
3458 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003459 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003460 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00003461 }
3462
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003463 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003464 if (squirrel && redir->rd_fd < 3
3465 && squirrel[redir->rd_fd] < 0
3466 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003467 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00003468 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003469 if (openfd == REDIRFD_CLOSE) {
3470 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003471 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003472 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003473 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003474 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003475 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003476 }
Eric Andersen25f27032001-04-26 23:22:31 +00003477 }
3478 }
3479 return 0;
3480}
3481
3482static void restore_redirects(int squirrel[])
3483{
3484 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003485 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00003486 fd = squirrel[i];
3487 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003488 /* We simply die on error */
3489 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00003490 }
3491 }
3492}
3493
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003494
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003495static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003496
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003497/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003498static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003499{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003500 char **p;
3501 struct command *command;
3502 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003503 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003504
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003505 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003506 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003507 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003508 for (i = 0; i < pi->num_cmds; i++) {
3509 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003510 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003511 if (command->argv) {
3512 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003513 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003514 }
3515 free_strings(command->argv);
3516 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003517 }
3518 /* not "else if": on syntax error, we may have both! */
3519 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003520 debug_printf_clean(" begin group (cmd_type:%d)\n",
3521 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003522 free_pipe_list(command->group);
3523 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003524 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003525 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003526 /* else is crucial here.
3527 * If group != NULL, child_func is meaningless */
3528#if ENABLE_HUSH_FUNCTIONS
3529 else if (command->child_func) {
3530 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3531 command->child_func->parent_cmd = NULL;
3532 }
3533#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003534#if !BB_MMU
3535 free(command->group_as_string);
3536 command->group_as_string = NULL;
3537#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003538 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003539 debug_printf_clean(" redirect %d%s",
3540 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003541 /* guard against the case >$FOO, where foo is unset or blank */
3542 if (r->rd_filename) {
3543 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3544 free(r->rd_filename);
3545 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003546 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003547 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003548 rnext = r->next;
3549 free(r);
3550 }
3551 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003552 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003553 free(pi->cmds); /* children are an array, they get freed all at once */
3554 pi->cmds = NULL;
3555#if ENABLE_HUSH_JOB
3556 free(pi->cmdtext);
3557 pi->cmdtext = NULL;
3558#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003559}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003560
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003561static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003562{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003563 struct pipe *pi, *next;
3564
3565 for (pi = head; pi; pi = next) {
3566#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003567 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003568#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003569 free_pipe(pi);
3570 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003571 next = pi->next;
3572 /*pi->next = NULL;*/
3573 free(pi);
3574 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003575}
3576
3577
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003578static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003579#if BB_MMU
3580#define parse_stream(pstring, input, end_trigger) \
3581 parse_stream(input, end_trigger)
3582#endif
3583static struct pipe *parse_stream(char **pstring,
3584 struct in_str *input,
3585 int end_trigger);
3586static void parse_and_run_string(const char *s);
3587
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003588
Mike Frysinger93cadc22009-05-27 17:06:25 -04003589static char *find_in_path(const char *arg)
3590{
3591 char *ret = NULL;
3592 const char *PATH = get_local_var_value("PATH");
3593
3594 if (!PATH)
3595 return NULL;
3596
3597 while (1) {
3598 const char *end = strchrnul(PATH, ':');
3599 int sz = end - PATH; /* must be int! */
3600
3601 free(ret);
3602 if (sz != 0) {
3603 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3604 } else {
3605 /* We have xxx::yyyy in $PATH,
3606 * it means "use current dir" */
3607 ret = xstrdup(arg);
3608 }
3609 if (access(ret, F_OK) == 0)
3610 break;
3611
3612 if (*end == '\0') {
3613 free(ret);
3614 return NULL;
3615 }
3616 PATH = end + 1;
3617 }
3618
3619 return ret;
3620}
3621
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003622static const struct built_in_command* find_builtin_helper(const char *name,
3623 const struct built_in_command *x,
3624 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003625{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003626 while (x != end) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01003627 if (strcmp(name, x->b_cmd) != 0) {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003628 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003629 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003630 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003631 debug_printf_exec("found builtin '%s'\n", name);
3632 return x;
3633 }
3634 return NULL;
3635}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003636static const struct built_in_command* find_builtin1(const char *name)
3637{
3638 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3639}
3640static const struct built_in_command* find_builtin(const char *name)
3641{
3642 const struct built_in_command *x = find_builtin1(name);
3643 if (x)
3644 return x;
3645 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3646}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003647
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003648#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003649static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003650{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003651 struct function **funcpp = &G.top_func;
3652 while (*funcpp) {
3653 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003654 break;
3655 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003656 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003657 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003658 return funcpp;
3659}
3660
3661static const struct function *find_function(const char *name)
3662{
3663 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003664 if (funcp)
3665 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003666 return funcp;
3667}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003668
Denis Vlasenkobc569742009-04-12 20:35:19 +00003669/* Note: takes ownership on name ptr */
3670static struct function *new_function(char *name)
3671{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003672 struct function **funcpp = find_function_slot(name);
3673 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003674
Denys Vlasenko873273d2009-09-12 14:47:41 +02003675 if (funcp != NULL) {
3676 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003677 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3678 if (!cmd) {
3679 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3680 free(funcp->name);
3681 /* Note: if !funcp->body, do not free body_as_string!
3682 * This is a special case of "-F name body" function:
3683 * body_as_string was not malloced! */
3684 if (funcp->body) {
3685 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003686# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003687 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003688# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003689 }
3690 } else {
3691 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3692 cmd->argv[0] = funcp->name;
3693 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003694# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003695 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003696# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003697 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003698 } else {
3699 debug_printf_exec("remembering new function '%s'\n", name);
3700 funcp = *funcpp = xzalloc(sizeof(*funcp));
3701 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003702 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003703
Denis Vlasenkobc569742009-04-12 20:35:19 +00003704 funcp->name = name;
3705 return funcp;
3706}
3707
Denis Vlasenko40e84372009-04-18 11:23:38 +00003708static void unset_func(const char *name)
3709{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003710 struct function **funcpp = find_function_slot(name);
3711 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003712
Denys Vlasenko873273d2009-09-12 14:47:41 +02003713 if (funcp != NULL) {
3714 debug_printf_exec("freeing function '%s'\n", funcp->name);
3715 *funcpp = funcp->next;
3716 /* funcp is unlinked now, deleting it.
3717 * Note: if !funcp->body, the function was created by
3718 * "-F name body", do not free ->body_as_string
3719 * and ->name as they were not malloced. */
3720 if (funcp->body) {
3721 free_pipe_list(funcp->body);
3722 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003723# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003724 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003725# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003726 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003727 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003728 }
3729}
3730
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003731# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003732#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003733 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003734# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003735static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003736 const struct function *funcp,
3737 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003738static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003739 const struct function *funcp,
3740 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003741{
3742# if BB_MMU
3743 int n = 1;
3744
3745 argv[0] = G.global_argv[0];
3746 G.global_argv = argv;
3747 while (*++argv)
3748 n++;
3749 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003750 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003751 n = run_list(funcp->body);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003752 fflush_all();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003753 _exit(n);
3754# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003755 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003756 funcp->body_as_string,
3757 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003758 argv + 1,
3759 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003760# endif
3761}
3762
3763static int run_function(const struct function *funcp, char **argv)
3764{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003765 int rc;
3766 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003767 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003768
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003769 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003770
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003771 /* "we are in function, ok to use return" */
3772 sv_flg = G.flag_return_in_progress;
3773 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003774# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003775 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003776# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003777
Denis Vlasenkobc569742009-04-12 20:35:19 +00003778 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003779# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003780 if (!funcp->body) {
3781 /* Function defined by -F */
3782 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003783 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003784 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003785# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003786 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003787 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003788 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003789
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003790# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003791 {
3792 struct variable *var;
3793 struct variable **var_pp;
3794
3795 var_pp = &G.top_var;
3796 while ((var = *var_pp) != NULL) {
3797 if (var->func_nest_level < G.func_nest_level) {
3798 var_pp = &var->next;
3799 continue;
3800 }
3801 /* Unexport */
3802 if (var->flg_export)
3803 bb_unsetenv(var->varstr);
3804 /* Remove from global list */
3805 *var_pp = var->next;
3806 /* Free */
3807 if (!var->max_len)
3808 free(var->varstr);
3809 free(var);
3810 }
3811 G.func_nest_level--;
3812 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003813# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003814 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003815
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003816 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003817
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003818 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003819}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003820#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003821
3822
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003823#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003824#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003825 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003826#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003827#define exec_builtin(to_free, x, argv) \
3828 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003829#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003830static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003831 const struct built_in_command *x,
3832 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003833static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003834 const struct built_in_command *x,
3835 char **argv)
3836{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003837#if BB_MMU
Denys Vlasenko17323a62010-01-28 01:57:05 +01003838 int rcode = x->b_function(argv);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003839 fflush_all();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003840 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003841#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003842 /* On NOMMU, we must never block!
3843 * Example: { sleep 99 | read line; } & echo Ok
3844 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003845 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003846 argv[0],
3847 G.global_argv[0],
3848 G.global_argv + 1,
3849 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003850#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003851}
3852
3853
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003854static void execvp_or_die(char **argv) NORETURN;
3855static void execvp_or_die(char **argv)
3856{
3857 debug_printf_exec("execing '%s'\n", argv[0]);
3858 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3859 execvp(argv[0], argv);
3860 bb_perror_msg("can't execute '%s'", argv[0]);
3861 _exit(127); /* bash compat */
3862}
3863
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003864#if ENABLE_HUSH_MODE_X
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003865static void dump_cmd_in_x_mode(char **argv)
3866{
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003867 if (G_x_mode && argv) {
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003868 /* We want to output the line in one write op */
3869 char *buf, *p;
3870 int len;
3871 int n;
3872
3873 len = 3;
3874 n = 0;
3875 while (argv[n])
3876 len += strlen(argv[n++]) + 1;
3877 buf = xmalloc(len);
3878 buf[0] = '+';
3879 p = buf + 1;
3880 n = 0;
3881 while (argv[n])
3882 p += sprintf(p, " %s", argv[n++]);
3883 *p++ = '\n';
3884 *p = '\0';
3885 fputs(buf, stderr);
3886 free(buf);
3887 }
3888}
Denys Vlasenko202a2d12010-07-16 12:36:14 +02003889#else
3890# define dump_cmd_in_x_mode(argv) ((void)0)
3891#endif
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003892
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003893#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003894#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3895 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3896#define pseudo_exec(nommu_save, command, argv_expanded) \
3897 pseudo_exec(command, argv_expanded)
3898#endif
3899
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003900/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003901 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003902 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003903 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003904 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003905static void pseudo_exec_argv(nommu_save_t *nommu_save,
3906 char **argv, int assignment_cnt,
3907 char **argv_expanded) NORETURN;
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003908static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003909 char **argv, int assignment_cnt,
3910 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003911{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003912 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003913
Denis Vlasenko9504e442008-10-29 01:19:15 +00003914 new_env = expand_assignments(argv, assignment_cnt);
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003915 dump_cmd_in_x_mode(new_env);
Denys Vlasenko889550b2010-07-14 19:01:25 +02003916
3917 if (!argv[assignment_cnt]) {
3918 /* Case when we are here: ... | var=val | ...
3919 * (note that we do not exit early, i.e., do not optimize out
3920 * expand_assignments(): think about ... | var=`sleep 1` | ...
3921 */
3922 free_strings(new_env);
3923 _exit(EXIT_SUCCESS);
3924 }
3925
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003926#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003927 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003928 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003929 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003930 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003931#else
3932 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003933 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003934#endif
Denys Vlasenko889550b2010-07-14 19:01:25 +02003935
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003936 if (argv_expanded) {
3937 argv = argv_expanded;
3938 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003939 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003940#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003941 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003942#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003943 }
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02003944 dump_cmd_in_x_mode(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003945
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003946#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3947 if (strchr(argv[0], '/') != NULL)
3948 goto skip;
3949#endif
3950
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003951 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003952 * Depending on context, this might be redundant. But it's
3953 * easier to waste a few CPU cycles than it is to figure out
3954 * if this is one of those cases.
3955 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003956 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003957 /* On NOMMU, it is more expensive to re-execute shell
3958 * just in order to run echo or test builtin.
3959 * It's better to skip it here and run corresponding
3960 * non-builtin later. */
3961 const struct built_in_command *x;
3962 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003963 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003964 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003965 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003966 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003967#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003968 /* Check if the command matches any functions */
3969 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003970 const struct function *funcp = find_function(argv[0]);
3971 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003972 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003973 }
3974 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003975#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003976
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003977#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003978 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003979 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003980 int a = find_applet_by_name(argv[0]);
3981 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003982# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003983 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003984 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003985 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003986 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003987# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003988 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003989 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003990 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3991 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003992 /* If they called chroot or otherwise made the binary no longer
3993 * executable, fall through */
3994 }
3995 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003996#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003997
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003998#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003999 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004000#endif
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02004001 execvp_or_die(argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +00004002}
4003
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004004/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00004005 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004006static void pseudo_exec(nommu_save_t *nommu_save,
4007 struct command *command,
4008 char **argv_expanded) NORETURN;
4009static void pseudo_exec(nommu_save_t *nommu_save,
4010 struct command *command,
4011 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00004012{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004013 if (command->argv) {
4014 pseudo_exec_argv(nommu_save, command->argv,
4015 command->assignment_cnt, argv_expanded);
4016 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004017
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004018 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00004019 /* Cases when we are here:
4020 * ( list )
4021 * { list } &
4022 * ... | ( list ) | ...
4023 * ... | { list } | ...
4024 */
4025#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00004026 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004027 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004028 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004029 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00004030 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004031 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00004032 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004033#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004034 re_execute_shell(&nommu_save->argv_from_re_execing,
4035 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004036 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02004037 G.global_argv + 1,
4038 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00004039#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004040 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004041
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004042 /* Case when we are here: ... | >file */
4043 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004044 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00004045}
4046
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004047#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004048static const char *get_cmdtext(struct pipe *pi)
4049{
4050 char **argv;
4051 char *p;
4052 int len;
4053
4054 /* This is subtle. ->cmdtext is created only on first backgrounding.
4055 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004056 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004057 if (pi->cmdtext)
4058 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004059 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004060 if (!argv || !argv[0]) {
4061 pi->cmdtext = xzalloc(1);
4062 return pi->cmdtext;
4063 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004064
4065 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004066 do {
4067 len += strlen(*argv) + 1;
4068 } while (*++argv);
4069 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004070 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004071 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004072 do {
4073 len = strlen(*argv);
4074 memcpy(p, *argv, len);
4075 p += len;
4076 *p++ = ' ';
4077 } while (*++argv);
4078 p[-1] = '\0';
4079 return pi->cmdtext;
4080}
4081
Eric Andersenbafd94f2001-05-02 16:11:59 +00004082static void insert_bg_job(struct pipe *pi)
4083{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004084 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004085 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004086
4087 /* Linear search for the ID of the job to use */
4088 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004089 for (job = G.job_list; job; job = job->next)
4090 if (job->jobid >= pi->jobid)
4091 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004092
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004093 /* Add job to the list of running jobs */
4094 jobp = &G.job_list;
4095 while ((job = *jobp) != NULL)
4096 jobp = &job->next;
4097 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00004098
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004099 *job = *pi; /* physical copy */
4100 job->next = NULL;
4101 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
4102 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004103 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004104 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004105 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004106 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004107 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00004108
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004109 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004110 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004111 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004112}
4113
Eric Andersenbafd94f2001-05-02 16:11:59 +00004114static void remove_bg_job(struct pipe *pi)
4115{
4116 struct pipe *prev_pipe;
4117
Denis Vlasenko87a86552008-07-29 19:43:10 +00004118 if (pi == G.job_list) {
4119 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004120 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004121 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004122 while (prev_pipe->next != pi)
4123 prev_pipe = prev_pipe->next;
4124 prev_pipe->next = pi->next;
4125 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004126 if (G.job_list)
4127 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00004128 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00004129 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00004130}
Eric Andersen028b65b2001-06-28 01:10:11 +00004131
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004132/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00004133static void delete_finished_bg_job(struct pipe *pi)
4134{
4135 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004136 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004137 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004138 free(pi);
4139}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004140#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004141
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004142/* Check to see if any processes have exited -- if they
4143 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00004144static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00004145{
Eric Andersenc798b072001-06-22 06:23:03 +00004146 int attributes;
4147 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004148#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00004149 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004150#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00004151 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004152 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004153
Denis Vlasenkod5762932009-03-31 11:22:57 +00004154 debug_printf_jobs("checkjobs %p\n", fg_pipe);
4155
Eric Andersenc798b072001-06-22 06:23:03 +00004156 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004157 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00004158 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00004159
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004160 errno = 0;
4161#if ENABLE_HUSH_FAST
4162 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
4163//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
4164//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02004165 /* There was neither fork nor SIGCHLD since last waitpid */
4166 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004167 if (!G.we_have_children) {
4168 errno = ECHILD;
4169 return -1;
4170 }
4171 if (fg_pipe == NULL) { /* is WNOHANG set? */
4172 /* We have children, but they did not exit
4173 * or stop yet (we saw no SIGCHLD) */
4174 return 0;
4175 }
4176 /* else: !WNOHANG, waitpid will block, can't short-circuit */
4177 }
4178#endif
4179
Denis Vlasenko1359da62007-04-21 23:27:30 +00004180/* Do we do this right?
4181 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004182 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00004183 * [3]+ Stopped sleep 20 | false
4184 * bash-3.00# echo $?
4185 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004186 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00004187 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004188 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004189 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004190 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004191 int dead;
4192
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004193#if ENABLE_HUSH_FAST
4194 i = G.count_SIGCHLD;
4195#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004196 childpid = waitpid(-1, &status, attributes);
4197 if (childpid <= 0) {
4198 if (childpid && errno != ECHILD)
4199 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004200#if ENABLE_HUSH_FAST
4201 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02004202 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004203 G.handled_SIGCHLD = i;
4204//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4205 }
4206#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004207 break;
4208 }
4209 dead = WIFEXITED(status) || WIFSIGNALED(status);
4210
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00004211#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00004212 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004213 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004214 childpid, WSTOPSIG(status), WEXITSTATUS(status));
4215 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004216 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004217 childpid, WTERMSIG(status), WEXITSTATUS(status));
4218 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00004219 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00004220 childpid, WEXITSTATUS(status));
4221#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004222 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00004223 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004224 for (i = 0; i < fg_pipe->num_cmds; i++) {
4225 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
4226 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004227 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004228 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004229 fg_pipe->cmds[i].pid = 0;
4230 fg_pipe->alive_cmds--;
4231 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004232 /* last process gives overall exitstatus */
4233 rcode = WEXITSTATUS(status);
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004234 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00004235 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02004236 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00004237 */
4238 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00004239 int sig = WTERMSIG(status);
4240 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004241 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
4242 * Maybe we need to use sig | 128? */
4243 rcode = sig + 128;
Denis Vlasenko40e84372009-04-18 11:23:38 +00004244 }
Denys Vlasenkoa4899ef2010-01-04 11:37:09 +01004245 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00004246 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004247 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004248 fg_pipe->cmds[i].is_stopped = 1;
4249 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00004250 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004251 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
4252 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
4253 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004254 /* All processes in fg pipe have exited or stopped */
4255/* Note: *non-interactive* bash does not continue if all processes in fg pipe
4256 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
4257 * and "killall -STOP cat" */
4258 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004259#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004260 if (fg_pipe->alive_cmds)
4261 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004262#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004263 return rcode;
4264 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02004265 if (!fg_pipe->alive_cmds)
4266 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004267 }
4268 /* There are still running processes in the fg pipe */
4269 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00004270 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004271 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00004272 }
4273
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004274#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004275 /* We asked to wait for bg or orphaned children */
4276 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004277 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004278 for (i = 0; i < pi->num_cmds; i++) {
4279 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004280 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00004281 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00004282 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004283 /* Happens when shell is used as init process (init=/bin/sh) */
4284 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004285 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00004286
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004287 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00004288 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00004289 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004290 pi->cmds[i].pid = 0;
4291 pi->alive_cmds--;
4292 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004293 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00004294 printf(JOB_STATUS_FORMAT, pi->jobid,
4295 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00004296 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00004297 }
4298 } else {
4299 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004300 pi->cmds[i].is_stopped = 1;
4301 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00004302 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004303#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004304 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00004305
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004306 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00004307}
4308
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004309#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00004310static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
4311{
4312 pid_t p;
4313 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04004314 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004315 /* Job finished, move the shell to the foreground */
4316 p = getpgrp(); /* our process group id */
4317 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
4318 tcsetpgrp(G_interactive_fd, p);
4319 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00004320 return rcode;
4321}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004322#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00004323
Denis Vlasenko34d4d892009-04-04 20:24:37 +00004324/* Start all the jobs, but don't wait for anything to finish.
4325 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00004326 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00004327 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00004328 * to finish to determine the exit status of the pipe. If the pipe
4329 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00004330 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00004331 * return value.
4332 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00004333 * Returns -1 only if started some children. IOW: we have to
4334 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00004335 *
4336 * The only case when we do not need to [v]fork is when the pipe
4337 * is single, non-backgrounded, non-subshell command. Examples:
4338 * cmd ; ... { list } ; ...
4339 * cmd && ... { list } && ...
4340 * cmd || ... { list } || ...
4341 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4342 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004343 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00004344 *
4345 * Cases when we must fork:
4346 * non-single: cmd | cmd
4347 * backgrounded: cmd & { list } &
4348 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00004349 */
Denys Vlasenko29082232010-07-16 13:52:32 +02004350#if !ENABLE_HUSH_MODE_X
4351#define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, char argv_expanded) \
4352 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
4353#endif
4354static int redirect_and_varexp_helper(char ***new_env_p, struct variable **old_vars_p, struct command *command, int squirrel[3], char **argv_expanded)
4355{
4356 /* setup_redirects acts on file descriptors, not FILEs.
4357 * This is perfect for work that comes after exec().
4358 * Is it really safe for inline use? Experimentally,
4359 * things seem to work. */
4360 int rcode = setup_redirects(command, squirrel);
4361 if (rcode == 0) {
4362 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
4363 *new_env_p = new_env;
4364 dump_cmd_in_x_mode(new_env);
4365 dump_cmd_in_x_mode(argv_expanded);
4366 if (old_vars_p)
4367 *old_vars_p = set_vars_and_save_old(new_env);
4368 }
4369 return rcode;
4370}
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02004371static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004372{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004373 static const char *const null_ptr = NULL;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004374
4375 int cmd_no;
4376 int next_infd;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004377 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004378 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004379 char **argv;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004380 /* it is not always needed, but we aim to smaller code */
4381 int squirrel[] = { -1, -1, -1 };
4382 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004383
Denis Vlasenko552433b2009-04-04 19:29:21 +00004384 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004385 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004386
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004387 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004388 pi->stopped_cmds = 0;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004389 command = &pi->cmds[0];
Denis Vlasenko552433b2009-04-04 19:29:21 +00004390 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004391
Denis Vlasenko552433b2009-04-04 19:29:21 +00004392 if (pi->num_cmds != 1
4393 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004394 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00004395 ) {
4396 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004397 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004398
Denis Vlasenko552433b2009-04-04 19:29:21 +00004399 pi->alive_cmds = 1;
4400
4401 debug_printf_exec(": group:%p argv:'%s'\n",
4402 command->group, command->argv ? command->argv[0] : "NONE");
4403
4404 if (command->group) {
4405#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004406 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004407 /* "executing" func () { list } */
4408 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004409
Denis Vlasenkobc569742009-04-12 20:35:19 +00004410 funcp = new_function(command->argv[0]);
4411 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004412 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004413# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004414 funcp->body_as_string = command->group_as_string;
4415 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004416# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004417 command->group = NULL;
4418 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00004419 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4420 funcp->parent_cmd = command;
4421 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004422
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004423 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4424 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00004425 return EXIT_SUCCESS;
4426 }
4427#endif
4428 /* { list } */
4429 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004430 rcode = 1; /* exitcode if redir failed */
4431 if (setup_redirects(command, squirrel) == 0) {
4432 debug_printf_exec(": run_list\n");
4433 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004434 }
Eric Andersen04407e52001-06-07 16:42:05 +00004435 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004436 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004437 debug_leave();
4438 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004439 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004440 }
4441
Denis Vlasenko552433b2009-04-04 19:29:21 +00004442 argv = command->argv ? command->argv : (char **) &null_ptr;
4443 {
4444 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004445#if ENABLE_HUSH_FUNCTIONS
4446 const struct function *funcp;
4447#else
4448 enum { funcp = 0 };
4449#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004450 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004451 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004452
Denis Vlasenko552433b2009-04-04 19:29:21 +00004453 if (argv[command->assignment_cnt] == NULL) {
4454 /* Assignments, but no command */
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004455 /* Ensure redirects take effect (that is, create files).
Denys Vlasenko29082232010-07-16 13:52:32 +02004456 * Try "a=t >file" */
4457#if 0 /* A few cases in testsuite fail with this code. FIXME */
4458 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
4459 /* Set shell variables */
4460 if (new_env) {
4461 argv = new_env;
4462 while (*argv) {
4463 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
4464 /* Do we need to flag set_local_var() errors?
4465 * "assignment to readonly var" and "putenv error"
4466 */
4467 argv++;
4468 }
4469 }
4470 /* Redirect error sets $? to 1. Otherwise,
4471 * if evaluating assignment value set $?, retain it.
4472 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4473 if (rcode == 0)
4474 rcode = G.last_exitcode;
4475 /* Exit, _skipping_ variable restoring code: */
4476 goto clean_up_and_ret0;
4477
4478#else /* Older, bigger, but more correct code */
4479
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004480 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004481 restore_redirects(squirrel);
4482 /* Set shell variables */
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004483 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004484 bb_putchar_stderr('+');
Denis Vlasenko552433b2009-04-04 19:29:21 +00004485 while (*argv) {
Denys Vlasenko29082232010-07-16 13:52:32 +02004486 char *p = expand_string_to_string(*argv);
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004487 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004488 fprintf(stderr, " %s", p);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004489 debug_printf_exec("set shell var:'%s'->'%s'\n",
4490 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02004491 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenko29082232010-07-16 13:52:32 +02004492 /* Do we need to flag set_local_var() errors?
4493 * "assignment to readonly var" and "putenv error"
4494 */
Denis Vlasenko552433b2009-04-04 19:29:21 +00004495 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00004496 }
Denys Vlasenko202a2d12010-07-16 12:36:14 +02004497 if (G_x_mode)
Denys Vlasenko3f5fae02010-07-16 12:35:35 +02004498 bb_putchar_stderr('\n');
Denys Vlasenkob3389de2010-07-15 12:33:37 +02004499 /* Redirect error sets $? to 1. Otherwise,
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004500 * if evaluating assignment value set $?, retain it.
4501 * Try "false; q=`exit 2`; echo $?" - should print 2: */
4502 if (rcode == 0)
4503 rcode = G.last_exitcode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004504 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004505 debug_leave();
4506 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004507 return rcode;
Denys Vlasenko29082232010-07-16 13:52:32 +02004508#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00004509 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004510
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004511 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004512 if (0) {}
4513#if ENABLE_HUSH_BASH_COMPAT
4514 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004515 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4516 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004517#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004518#ifdef CMD_SINGLEWORD_NOGLOB_COND
4519 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4520 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004521 }
4522#endif
4523 else {
4524 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4525 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004526
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004527 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04004528 if (!argv_expanded[0]) {
Denys Vlasenko385cc592010-01-12 06:47:39 +01004529 free(argv_expanded);
Mike Frysinger28736c32009-10-18 01:11:45 -04004530 debug_leave();
Denys Vlasenko00243b02009-11-16 02:00:03 +01004531 return G.last_exitcode;
Mike Frysinger28736c32009-10-18 01:11:45 -04004532 }
4533
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004534 x = find_builtin(argv_expanded[0]);
4535#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004536 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004537 if (!x)
4538 funcp = find_function(argv_expanded[0]);
4539#endif
4540 if (x || funcp) {
4541 if (!funcp) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01004542 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004543 debug_printf("exec with redirects only\n");
4544 rcode = setup_redirects(command, NULL);
4545 goto clean_up_and_ret1;
4546 }
Eric Andersen25f27032001-04-26 23:22:31 +00004547 }
Denys Vlasenko29082232010-07-16 13:52:32 +02004548 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004549 if (rcode == 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004550 if (!funcp) {
4551 debug_printf_exec(": builtin '%s' '%s'...\n",
Denys Vlasenkocddbb612010-05-20 14:27:09 +02004552 x->b_cmd, argv_expanded[1]);
Denys Vlasenko17323a62010-01-28 01:57:05 +01004553 rcode = x->b_function(argv_expanded) & 0xff;
Denys Vlasenko8131eea2009-11-02 14:19:51 +01004554 fflush_all();
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004555 }
4556#if ENABLE_HUSH_FUNCTIONS
4557 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02004558# if ENABLE_HUSH_LOCAL
4559 struct variable **sv;
4560 sv = G.shadowed_vars_pp;
4561 G.shadowed_vars_pp = &old_vars;
4562# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004563 debug_printf_exec(": function '%s' '%s'...\n",
4564 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00004565 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02004566# if ENABLE_HUSH_LOCAL
4567 G.shadowed_vars_pp = sv;
4568# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004569 }
4570#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004571 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004572 clean_up_and_ret:
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004573 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004574 add_vars(old_vars);
Denys Vlasenko29082232010-07-16 13:52:32 +02004575/* clean_up_and_ret0: */
4576 restore_redirects(squirrel);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004577 clean_up_and_ret1:
4578 free(argv_expanded);
4579 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004580 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004581 debug_printf_exec("run_pipe return %d\n", rcode);
4582 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004583 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004584
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004585 if (ENABLE_FEATURE_SH_STANDALONE) {
4586 int n = find_applet_by_name(argv_expanded[0]);
4587 if (n >= 0 && APPLET_IS_NOFORK(n)) {
Denys Vlasenko29082232010-07-16 13:52:32 +02004588 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004589 if (rcode == 0) {
Denys Vlasenko8fa1f5d2010-07-15 08:18:46 +02004590 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
4591 argv_expanded[0], argv_expanded[1]);
4592 rcode = run_nofork_applet(n, argv_expanded);
4593 }
4594 goto clean_up_and_ret;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004595 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004596 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00004597 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00004598 }
4599
Denis Vlasenko552433b2009-04-04 19:29:21 +00004600 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004601 /* NB: argv_expanded may already be created, and that
4602 * might include `cmd` runs! Do not rerun it! We *must*
4603 * use argv_expanded if it's non-NULL */
4604
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004605 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004606 pi->alive_cmds = 0;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004607 next_infd = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004608
Denys Vlasenko889550b2010-07-14 19:01:25 +02004609 cmd_no = 0;
4610 while (cmd_no < pi->num_cmds) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004611 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004612#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004613 volatile nommu_save_t nommu_save;
4614 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004615 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004616 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004617 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004618#endif
Denys Vlasenko889550b2010-07-14 19:01:25 +02004619 command = &pi->cmds[cmd_no];
4620 cmd_no++;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004621 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004622 debug_printf_exec(": pipe member '%s' '%s'...\n",
4623 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004624 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004625 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004626 }
Eric Andersen25f27032001-04-26 23:22:31 +00004627
4628 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004629 pipefds.rd = 0;
4630 pipefds.wr = 1;
Denys Vlasenko889550b2010-07-14 19:01:25 +02004631 if (cmd_no < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004632 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004633
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004634 command->pid = BB_MMU ? fork() : vfork();
4635 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004636#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004637 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004638 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004639
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004640 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004641 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004642 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004643 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004644 pgrp = pi->pgrp;
4645 if (pgrp < 0) /* true for 1st process only */
4646 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004647 if (setpgid(0, pgrp) == 0
4648 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004649 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004650 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004651 /* We do it in *every* child, not just first,
4652 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004653 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004654 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004655 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004656#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004657 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4658 /* 1st cmd in backgrounded pipe
4659 * should have its stdin /dev/null'ed */
4660 close(0);
4661 if (open(bb_dev_null, O_RDONLY))
4662 xopen("/", O_RDONLY);
4663 } else {
Denys Vlasenko889550b2010-07-14 19:01:25 +02004664 xmove_fd(next_infd, 0);
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004665 }
4666 xmove_fd(pipefds.wr, 1);
4667 if (pipefds.rd > 1)
4668 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004669 /* Like bash, explicit redirects override pipes,
4670 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004671 if (setup_redirects(command, NULL))
4672 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004673
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004674 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004675 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4676
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004677 /* Stores to nommu_save list of env vars putenv'ed
4678 * (NOMMU, on MMU we don't need that) */
4679 /* cast away volatility... */
4680 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004681 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004682 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004683
Denis Vlasenkof9375282009-04-05 19:13:39 +00004684 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004685#if ENABLE_HUSH_FAST
4686 G.count_SIGCHLD++;
4687//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4688#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004689 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004690#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004691 /* Clean up after vforked child */
4692 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004693 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004694 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004695 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004696#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004697 free(argv_expanded);
4698 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004699 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004700 /* Clearly indicate, was it fork or vfork */
Pascal Bellard926031b2010-07-04 15:32:38 +02004701 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004702 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004703 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004704#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004705 /* Second and next children need to know pid of first one */
4706 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004707 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004708#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004709 }
Eric Andersen25f27032001-04-26 23:22:31 +00004710
Denys Vlasenko889550b2010-07-14 19:01:25 +02004711 if (cmd_no > 1)
4712 close(next_infd);
4713 if (cmd_no < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004714 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004715 /* Pass read (output) pipe end to next iteration */
Denys Vlasenko889550b2010-07-14 19:01:25 +02004716 next_infd = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004717 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004718
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004719 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004720 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004721 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4722 return 1;
4723 }
4724
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004725 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004726 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004727 return -1;
4728}
4729
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004730#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004731static void debug_print_tree(struct pipe *pi, int lvl)
4732{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004733 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004734 [PIPE_SEQ] = "SEQ",
4735 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004736 [PIPE_OR ] = "OR" ,
4737 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004738 };
4739 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004740 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004741# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004742 [RES_IF ] = "IF" ,
4743 [RES_THEN ] = "THEN" ,
4744 [RES_ELIF ] = "ELIF" ,
4745 [RES_ELSE ] = "ELSE" ,
4746 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004747# endif
4748# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004749 [RES_FOR ] = "FOR" ,
4750 [RES_WHILE] = "WHILE",
4751 [RES_UNTIL] = "UNTIL",
4752 [RES_DO ] = "DO" ,
4753 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004754# endif
4755# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004756 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004757# endif
4758# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004759 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004760 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004761 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004762 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004763 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004764# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004765 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004766 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004767 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004768 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004769 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004770 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004771 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004772# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004773 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004774# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004775 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004776
4777 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004778
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004779 pin = 0;
4780 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004781 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4782 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004783 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004784 while (prn < pi->num_cmds) {
4785 struct command *command = &pi->cmds[prn];
4786 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004787
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004788 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004789 lvl*2, "", prn,
4790 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004791 if (command->group) {
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004792 fprintf(stderr, " group %s: (argv=%p)%s%s\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004793 CMDTYPE[command->cmd_type],
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004794 argv
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004795# if !BB_MMU
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004796 , " group_as_string:", command->group_as_string
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004797# else
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004798 , "", ""
Denys Vlasenko2e48d532010-05-22 17:30:39 +02004799# endif
Denys Vlasenkob70cef72010-01-12 13:45:45 +01004800 );
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004801 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004802 prn++;
4803 continue;
4804 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004805 if (argv) while (*argv) {
4806 fprintf(stderr, " '%s'", *argv);
4807 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004808 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004809 fprintf(stderr, "\n");
4810 prn++;
4811 }
4812 pi = pi->next;
4813 pin++;
4814 }
4815}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004816#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004817
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004818/* NB: called by pseudo_exec, and therefore must not modify any
4819 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004820static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004821{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004822#if ENABLE_HUSH_CASE
4823 char *case_word = NULL;
4824#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004825#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004826 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004827 char **for_lcur = NULL;
4828 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004829#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004830 smallint last_followup;
4831 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004832#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004833 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004834#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004835 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004836#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004837#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004838 smallint rword; /* enum reserved_style */
4839 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004840#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004841
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004842 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004843 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004844
Denis Vlasenko06810332007-05-21 23:30:54 +00004845#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004846 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004847 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4848 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004849 continue;
4850 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004851 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004852 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004853 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004854 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004855 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004856 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004857 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004858 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004859 continue;
4860 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004861 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4862 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004863 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004864 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004865 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004866 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004867 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004868 }
4869 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004870#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004871
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004872 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004873 * in order to return, no direct "return" statements please.
4874 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004875
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004876#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004877 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004878#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004879
Denis Vlasenko0e151382009-04-06 18:40:31 +00004880#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004881 rword = RES_NONE;
4882 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004883#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004884 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004885 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004886
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004887 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004888 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004889 if (G.flag_SIGINT)
4890 break;
4891
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004892 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004893 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4894 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004895#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004896 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004897 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004898 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004899 /* start of a loop: remember where loop starts */
4900 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004901 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004902 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004903#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004904 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004905 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004906 if ((rcode == 0 && last_followup == PIPE_OR)
4907 || (rcode != 0 && last_followup == PIPE_AND)
4908 ) {
4909 /* It is "<true> || CMD" or "<false> && CMD"
4910 * and we should not execute CMD */
4911 debug_printf_exec("skipped cmd because of || or &&\n");
4912 last_followup = pi->followup;
4913 continue;
4914 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004915 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004916 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004917 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004918#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004919 if (cond_code) {
4920 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004921 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004922 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004923 /* "if <false> THEN cmd": skip cmd */
4924 continue;
4925 }
4926 } else {
4927 if (rword == RES_ELSE || rword == RES_ELIF) {
4928 /* "if <true> then ... ELSE/ELIF cmd":
4929 * skip cmd and all following ones */
4930 break;
4931 }
4932 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004933#endif
4934#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004935 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004936 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004937 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004938
4939 static const char encoded_dollar_at[] ALIGN1 = {
4940 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4941 }; /* encoded representation of "$@" */
4942 static const char *const encoded_dollar_at_argv[] = {
4943 encoded_dollar_at, NULL
4944 }; /* argv list with one element: "$@" */
4945 char **vals;
4946
4947 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004948 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004949 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004950 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004951 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004952 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004953 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004954 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004955 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004956 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004957 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004958 debug_print_strings("for_list made from", vals);
4959 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004960 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004961 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004962 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004963 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004964 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004965 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004966 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004967 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004968 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004969 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004970 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004971 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004972 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 +02004973 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004974 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004975 if (rword == RES_IN) {
4976 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4977 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004978 if (rword == RES_DONE) {
4979 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004980 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004981#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004982#if ENABLE_HUSH_CASE
4983 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004984 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004985 continue;
4986 }
4987 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004988 char **argv;
4989
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004990 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4991 break;
4992 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004993 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004994 while (*argv) {
4995 char *pattern = expand_string_to_string(*argv);
4996 /* TODO: which FNM_xxx flags to use? */
4997 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4998 free(pattern);
4999 if (cond_code == 0) { /* match! we will execute this branch */
5000 free(case_word); /* make future "word)" stop */
5001 case_word = NULL;
5002 break;
5003 }
5004 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005005 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005006 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005007 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005008 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005009 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005010 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005011 }
5012#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00005013 /* Just pressing <enter> in shell should check for jobs.
5014 * OTOH, in non-interactive shell this is useless
5015 * and only leads to extra job checks */
5016 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005017 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00005018 goto check_jobs_and_continue;
5019 continue;
5020 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005021
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005022 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00005023 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005024 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005025 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005026 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005027 {
5028 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005029#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00005030 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005031#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005032 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
5033 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00005034 /* We ran a builtin, function, or group.
5035 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005036 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005037 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005038 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005039 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005040#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005041 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005042 if (G.flag_break_continue) {
5043 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005044 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005045 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005046 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00005047 G.depth_break_continue--;
5048 if (G.depth_break_continue == 0)
5049 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005050 /* else: e.g. "continue 2" should *break* once, *then* continue */
5051 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005052 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005053 goto check_jobs_and_break;
5054 /* "continue": simulate end of loop */
5055 rword = RES_DONE;
5056 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005057 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005058#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00005059#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02005060 if (G.flag_return_in_progress == 1) {
5061 /* same as "goto check_jobs_and_break" */
5062 checkjobs(NULL);
5063 break;
5064 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00005065#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005066 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005067 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005068 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005069 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
5070 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005071 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005072#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00005073 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005074 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00005075#endif
Alexander Shishkinccb97712010-07-25 13:07:39 +02005076 /* Last command's pid goes to $! */
5077 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005078 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005079 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005080 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005081#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005082 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005083 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005084 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005085 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005086 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005087 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005088#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005089 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005090 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005091 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005092 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005093 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005094 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00005095 }
5096 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005097
5098 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00005099#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00005100 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005101 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00005102#endif
5103#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005104 /* Beware of "while false; true; do ..."! */
5105 if (pi->next && pi->next->res_word == RES_DO) {
5106 if (rword == RES_WHILE) {
5107 if (rcode) {
5108 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005109 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005110 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
5111 goto check_jobs_and_break;
5112 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00005113 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005114 if (rword == RES_UNTIL) {
5115 if (!rcode) {
5116 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005117 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005118 checkjobs(NULL);
5119 break;
5120 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005121 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00005122 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005123#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00005124
5125 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00005126 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005127 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00005128
5129#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00005130 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00005131#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00005132#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005133 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00005134 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00005135 free(for_list);
5136#endif
5137#if ENABLE_HUSH_CASE
5138 free(case_word);
5139#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005140 debug_leave();
5141 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00005142 return rcode;
5143}
5144
Eric Andersen25f27032001-04-26 23:22:31 +00005145/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00005146static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00005147{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005148 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00005149 debug_printf_exec("run_and_free_list entered\n");
Denys Vlasenko202a2d12010-07-16 12:36:14 +02005150 if (!G.n_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00005151 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00005152 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00005153 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005154 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00005155 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00005156 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005157 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00005158 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00005159 return rcode;
5160}
5161
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005162
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00005163static struct pipe *new_pipe(void)
5164{
Eric Andersen25f27032001-04-26 23:22:31 +00005165 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00005166 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005167 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005168 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00005169 return pi;
5170}
5171
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005172/* Command (member of a pipe) is complete, or we start a new pipe
5173 * if ctx->command is NULL.
5174 * No errors possible here.
5175 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005176static int done_command(struct parse_context *ctx)
5177{
5178 /* The command is really already in the pipe structure, so
5179 * advance the pipe counter and make a new, null command. */
5180 struct pipe *pi = ctx->pipe;
5181 struct command *command = ctx->command;
5182
5183 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005184 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005185 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005186 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005187 }
5188 pi->num_cmds++;
5189 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005190 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005191 } else {
5192 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
5193 }
5194
5195 /* Only real trickiness here is that the uncommitted
5196 * command structure is not counted in pi->num_cmds. */
5197 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005198 ctx->command = command = &pi->cmds[pi->num_cmds];
5199 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005200 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005201 return pi->num_cmds; /* used only for 0/nonzero check */
5202}
5203
5204static void done_pipe(struct parse_context *ctx, pipe_style type)
5205{
5206 int not_null;
5207
5208 debug_printf_parse("done_pipe entered, followup %d\n", type);
5209 /* Close previous command */
5210 not_null = done_command(ctx);
5211 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005212#if HAS_KEYWORDS
5213 ctx->pipe->pi_inverted = ctx->ctx_inverted;
5214 ctx->ctx_inverted = 0;
5215 ctx->pipe->res_word = ctx->ctx_res_w;
5216#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005217
5218 /* Without this check, even just <enter> on command line generates
5219 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005220 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005221 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00005222#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005223 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00005224#endif
5225#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005226 || ctx->ctx_res_w == RES_DONE
5227 || ctx->ctx_res_w == RES_FOR
5228 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00005229#endif
5230#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005231 || ctx->ctx_res_w == RES_ESAC
5232#endif
5233 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005234 struct pipe *new_p;
5235 debug_printf_parse("done_pipe: adding new pipe: "
5236 "not_null:%d ctx->ctx_res_w:%d\n",
5237 not_null, ctx->ctx_res_w);
5238 new_p = new_pipe();
5239 ctx->pipe->next = new_p;
5240 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005241 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005242 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005243 * This is used to control execution.
5244 * RES_FOR and RES_IN are NOT sticky (needed to support
5245 * cases where variable or value happens to match a keyword):
5246 */
5247#if ENABLE_HUSH_LOOPS
5248 if (ctx->ctx_res_w == RES_FOR
5249 || ctx->ctx_res_w == RES_IN)
5250 ctx->ctx_res_w = RES_NONE;
5251#endif
5252#if ENABLE_HUSH_CASE
5253 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005254 ctx->ctx_res_w = RES_CASE_BODY;
5255 if (ctx->ctx_res_w == RES_CASE)
5256 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005257#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005258 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005259 /* Create the memory for command, roughly:
5260 * ctx->pipe->cmds = new struct command;
5261 * ctx->command = &ctx->pipe->cmds[0];
5262 */
5263 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00005264 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005265 }
5266 debug_printf_parse("done_pipe return\n");
5267}
5268
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005269static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005270{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005271 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00005272 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005273 /* Create the memory for command, roughly:
5274 * ctx->pipe->cmds = new struct command;
5275 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005276 */
5277 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005278}
5279
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005280/* If a reserved word is found and processed, parse context is modified
5281 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00005282 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005283#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005284struct reserved_combo {
5285 char literal[6];
5286 unsigned char res;
5287 unsigned char assignment_flag;
5288 int flag;
5289};
5290enum {
5291 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005292# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005293 FLAG_IF = (1 << RES_IF ),
5294 FLAG_THEN = (1 << RES_THEN ),
5295 FLAG_ELIF = (1 << RES_ELIF ),
5296 FLAG_ELSE = (1 << RES_ELSE ),
5297 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005298# endif
5299# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005300 FLAG_FOR = (1 << RES_FOR ),
5301 FLAG_WHILE = (1 << RES_WHILE),
5302 FLAG_UNTIL = (1 << RES_UNTIL),
5303 FLAG_DO = (1 << RES_DO ),
5304 FLAG_DONE = (1 << RES_DONE ),
5305 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005306# endif
5307# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005308 FLAG_MATCH = (1 << RES_MATCH),
5309 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005310# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005311 FLAG_START = (1 << RES_XXXX ),
5312};
5313
5314static const struct reserved_combo* match_reserved_word(o_string *word)
5315{
Eric Andersen25f27032001-04-26 23:22:31 +00005316 /* Mostly a list of accepted follow-up reserved words.
5317 * FLAG_END means we are done with the sequence, and are ready
5318 * to turn the compound list into a command.
5319 * FLAG_START means the word must start a new compound list.
5320 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005321 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005322# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005323 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
5324 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
5325 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
5326 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
5327 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
5328 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005329# endif
5330# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005331 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
5332 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5333 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
5334 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
5335 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
5336 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005337# endif
5338# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005339 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
5340 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005341# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005342 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005343 const struct reserved_combo *r;
5344
5345 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
5346 if (strcmp(word->data, r->literal) == 0)
5347 return r;
5348 }
5349 return NULL;
5350}
Denis Vlasenkobb929512009-04-16 10:59:40 +00005351/* Return 0: not a keyword, 1: keyword
5352 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005353static int reserved_word(o_string *word, struct parse_context *ctx)
5354{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005355# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005356 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005357 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005358 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005359# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005360 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00005361
Denis Vlasenkobb929512009-04-16 10:59:40 +00005362 if (word->o_quoted)
5363 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005364 r = match_reserved_word(word);
5365 if (!r)
5366 return 0;
5367
5368 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005369# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005370 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
5371 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005372 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005373 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005374# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005375 if (r->flag == 0) { /* '!' */
5376 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005377 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00005378 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00005379 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005380 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005381 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005382 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005383 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005384 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005385
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005386 old = xmalloc(sizeof(*old));
5387 debug_printf_parse("push stack %p\n", old);
5388 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005389 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005390 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005391 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005392 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005393 ctx->ctx_res_w = RES_SNTX;
5394 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005395 } else {
5396 /* "{...} fi" is ok. "{...} if" is not
5397 * Example:
5398 * if { echo foo; } then { echo bar; } fi */
5399 if (ctx->command->group)
5400 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005401 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00005402
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005403 ctx->ctx_res_w = r->res;
5404 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005405 word->o_assignment = r->assignment_flag;
5406
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005407 if (ctx->old_flag & FLAG_END) {
5408 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005409
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005410 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005411 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005412 old = ctx->stack;
5413 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005414 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005415# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005416 o_addstr(&old->as_string, ctx->as_string.data);
5417 o_free_unsafe(&ctx->as_string);
5418 old->command->group_as_string = xstrdup(old->as_string.data);
5419 debug_printf_parse("pop, remembering as:'%s'\n",
5420 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005421# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005422 *ctx = *old; /* physical copy */
5423 free(old);
5424 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005425 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005426}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005427#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00005428
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005429/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005430 * Normal return is 0. Syntax errors return 1.
5431 * Note: on return, word is reset, but not o_free'd!
5432 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005433static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005434{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005435 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00005436
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005437 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005438 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005439 debug_printf_parse("done_word return 0: true null, ignored\n");
5440 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005441 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005442
Eric Andersen25f27032001-04-26 23:22:31 +00005443 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005444 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5445 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005446 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5447 * "2.7 Redirection
5448 * ...the word that follows the redirection operator
5449 * shall be subjected to tilde expansion, parameter expansion,
5450 * command substitution, arithmetic expansion, and quote
5451 * removal. Pathname expansion shall not be performed
5452 * on the word by a non-interactive shell; an interactive
5453 * shell may perform it, but shall do so only when
5454 * the expansion would result in one word."
5455 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005456 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005457 /* Cater for >\file case:
5458 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5459 * Same with heredocs:
5460 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5461 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005462 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5463 unbackslash(ctx->pending_redirect->rd_filename);
5464 /* Is it <<"HEREDOC"? */
5465 if (word->o_quoted) {
5466 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5467 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005468 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005469 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005470 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00005471 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005472 /* If this word wasn't an assignment, next ones definitely
5473 * can't be assignments. Even if they look like ones. */
5474 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5475 && word->o_assignment != WORD_IS_KEYWORD
5476 ) {
5477 word->o_assignment = NOT_ASSIGNMENT;
5478 } else {
5479 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5480 command->assignment_cnt++;
5481 word->o_assignment = MAYBE_ASSIGNMENT;
5482 }
5483
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005484#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005485# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00005486 if (ctx->ctx_dsemicolon
5487 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5488 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00005489 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005490 /* ctx->ctx_res_w = RES_MATCH; */
5491 ctx->ctx_dsemicolon = 0;
5492 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005493# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005494 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005495# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005496 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5497 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005498# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005499# if ENABLE_HUSH_CASE
5500 && ctx->ctx_res_w != RES_CASE
5501# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005502 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005503 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005504 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005505 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005506 debug_printf_parse("done_word return %d\n",
5507 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005508 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005509 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005510# ifdef CMD_SINGLEWORD_NOGLOB_COND
5511 if (strcmp(word->data, "export") == 0
5512# if ENABLE_HUSH_LOCAL
5513 || strcmp(word->data, "local") == 0
5514# endif
5515 ) {
5516 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5517 } else
5518# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005519# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005520 if (strcmp(word->data, "[[") == 0) {
5521 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5522 }
5523 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005524# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005525 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005526#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00005527 if (command->group) {
5528 /* "{ echo foo; } echo bar" - bad */
5529 syntax_error_at(word->data);
5530 debug_printf_parse("done_word return 1: syntax error, "
5531 "groups and arglists don't mix\n");
5532 return 1;
5533 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005534 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00005535 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5536 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005537 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005538 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005539 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005540 char *p = word->data;
5541 while (p[0] == SPECIAL_VAR_SYMBOL
5542 && (p[1] & 0x7f) == '@'
5543 && p[2] == SPECIAL_VAR_SYMBOL
5544 ) {
5545 p += 3;
5546 }
5547 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005548 /* saw no "$@", or not only "$@" but some
5549 * real text is there too */
5550 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005551 * e.g. "", $empty"" etc to not disappear */
5552 o_addchr(word, SPECIAL_VAR_SYMBOL);
5553 o_addchr(word, SPECIAL_VAR_SYMBOL);
5554 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00005555 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005556 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005557 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005558 }
Eric Andersen25f27032001-04-26 23:22:31 +00005559
Denis Vlasenko06810332007-05-21 23:30:54 +00005560#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005561 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005562 if (word->o_quoted
5563 || !is_well_formed_var_name(command->argv[0], '\0')
5564 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005565 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005566 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005567 return 1;
5568 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005569 /* Force FOR to have just one word (variable name) */
5570 /* NB: basically, this makes hush see "for v in ..."
5571 * syntax as if it is "for v; in ...". FOR and IN become
5572 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005573 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005574 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005575#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005576#if ENABLE_HUSH_CASE
5577 /* Force CASE to have just one word */
5578 if (ctx->ctx_res_w == RES_CASE) {
5579 done_pipe(ctx, PIPE_SEQ);
5580 }
5581#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005582
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005583 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005584
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005585 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005586 return 0;
5587}
5588
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005589
5590/* Peek ahead in the input to find out if we have a "&n" construct,
5591 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005592 * Return:
5593 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5594 * REDIRFD_SYNTAX_ERR if syntax error,
5595 * REDIRFD_TO_FILE if no & was seen,
5596 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005597 */
5598#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005599#define parse_redir_right_fd(as_string, input) \
5600 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005601#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005602static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005603{
5604 int ch, d, ok;
5605
5606 ch = i_peek(input);
5607 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005608 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005609
5610 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005611 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005612 ch = i_peek(input);
5613 if (ch == '-') {
5614 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005615 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005616 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005617 }
5618 d = 0;
5619 ok = 0;
5620 while (ch != EOF && isdigit(ch)) {
5621 d = d*10 + (ch-'0');
5622 ok = 1;
5623 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005624 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005625 ch = i_peek(input);
5626 }
5627 if (ok) return d;
5628
5629//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5630
5631 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005632 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005633}
5634
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005635/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005636 */
5637static int parse_redirect(struct parse_context *ctx,
5638 int fd,
5639 redir_type style,
5640 struct in_str *input)
5641{
5642 struct command *command = ctx->command;
5643 struct redir_struct *redir;
5644 struct redir_struct **redirp;
5645 int dup_num;
5646
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005647 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005648 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005649 /* Check for a '>&1' type redirect */
5650 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5651 if (dup_num == REDIRFD_SYNTAX_ERR)
5652 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005653 } else {
5654 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005655 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005656 if (dup_num) { /* <<-... */
5657 ch = i_getch(input);
5658 nommu_addchr(&ctx->as_string, ch);
5659 ch = i_peek(input);
5660 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005661 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005662
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005663 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005664 int ch = i_peek(input);
5665 if (ch == '|') {
5666 /* >|FILE redirect ("clobbering" >).
5667 * Since we do not support "set -o noclobber" yet,
5668 * >| and > are the same for now. Just eat |.
5669 */
5670 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005671 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005672 }
5673 }
5674
5675 /* Create a new redir_struct and append it to the linked list */
5676 redirp = &command->redirects;
5677 while ((redir = *redirp) != NULL) {
5678 redirp = &(redir->next);
5679 }
5680 *redirp = redir = xzalloc(sizeof(*redir));
5681 /* redir->next = NULL; */
5682 /* redir->rd_filename = NULL; */
5683 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005684 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005685
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005686 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5687 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005688
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005689 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005690 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005691 /* Erik had a check here that the file descriptor in question
5692 * is legit; I postpone that to "run time"
5693 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005694 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5695 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005696 } else {
5697 /* Set ctx->pending_redirect, so we know what to do at the
5698 * end of the next parsed word. */
5699 ctx->pending_redirect = redir;
5700 }
5701 return 0;
5702}
5703
Eric Andersen25f27032001-04-26 23:22:31 +00005704/* If a redirect is immediately preceded by a number, that number is
5705 * supposed to tell which file descriptor to redirect. This routine
5706 * looks for such preceding numbers. In an ideal world this routine
5707 * needs to handle all the following classes of redirects...
5708 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5709 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5710 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5711 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005712 *
5713 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5714 * "2.7 Redirection
5715 * ... If n is quoted, the number shall not be recognized as part of
5716 * the redirection expression. For example:
5717 * echo \2>a
5718 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005719 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005720 *
5721 * A -1 return means no valid number was found,
5722 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005723 */
5724static int redirect_opt_num(o_string *o)
5725{
5726 int num;
5727
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005728 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005729 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005730 num = bb_strtou(o->data, NULL, 10);
5731 if (errno || num < 0)
5732 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005733 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005734 return num;
5735}
5736
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005737#if BB_MMU
5738#define fetch_till_str(as_string, input, word, skip_tabs) \
5739 fetch_till_str(input, word, skip_tabs)
5740#endif
5741static char *fetch_till_str(o_string *as_string,
5742 struct in_str *input,
5743 const char *word,
5744 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005745{
5746 o_string heredoc = NULL_O_STRING;
5747 int past_EOL = 0;
5748 int ch;
5749
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005750 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005751 while (1) {
5752 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005753 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005754 if (ch == '\n') {
5755 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5756 heredoc.data[past_EOL] = '\0';
5757 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5758 return heredoc.data;
5759 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005760 do {
5761 o_addchr(&heredoc, ch);
5762 past_EOL = heredoc.length;
5763 jump_in:
5764 do {
5765 ch = i_getch(input);
5766 nommu_addchr(as_string, ch);
5767 } while (skip_tabs && ch == '\t');
5768 } while (ch == '\n');
5769 }
5770 if (ch == EOF) {
5771 o_free_unsafe(&heredoc);
5772 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005773 }
5774 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005775 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005776 }
5777}
5778
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005779/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5780 * and load them all. There should be exactly heredoc_cnt of them.
5781 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005782static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5783{
5784 struct pipe *pi = ctx->list_head;
5785
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005786 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005787 int i;
5788 struct command *cmd = pi->cmds;
5789
5790 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5791 pi->num_cmds,
5792 cmd->argv ? cmd->argv[0] : "NONE");
5793 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005794 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005795
5796 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5797 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005798 while (redir) {
5799 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005800 char *p;
5801
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005802 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005803 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005804 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005805 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005806 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005807 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005808 return 1;
5809 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005810 free(redir->rd_filename);
5811 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005812 heredoc_cnt--;
5813 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005814 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005815 }
5816 cmd++;
5817 }
5818 pi = pi->next;
5819 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005820#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005821 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005822 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005823 bb_error_msg_and_die("heredoc BUG 2");
5824#endif
5825 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005826}
5827
5828
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005829#if ENABLE_HUSH_TICK
Denys Vlasenko647553a2009-11-15 19:58:19 +01005830static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
Eric Andersen25f27032001-04-26 23:22:31 +00005831{
Denys Vlasenko647553a2009-11-15 19:58:19 +01005832 pid_t pid;
5833 int channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005834# if !BB_MMU
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01005835 char **to_free = NULL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005836# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005837
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005838 xpipe(channel);
Pascal Bellard926031b2010-07-04 15:32:38 +02005839 pid = BB_MMU ? xfork() : xvfork();
Denis Vlasenko05743d72008-02-10 12:10:08 +00005840 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005841 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005842 /* Process substitution is not considered to be usual
5843 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005844 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5845 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005846 bb_signals(0
5847 + (1 << SIGTSTP)
5848 + (1 << SIGTTIN)
5849 + (1 << SIGTTOU)
5850 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005851 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005852 close(channel[0]); /* NB: close _first_, then move fd! */
5853 xmove_fd(channel[1], 1);
5854 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005855 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005856 /* Awful hack for `trap` or $(trap).
5857 *
5858 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5859 * contains an example where "trap" is executed in a subshell:
5860 *
5861 * save_traps=$(trap)
5862 * ...
5863 * eval "$save_traps"
5864 *
5865 * Standard does not say that "trap" in subshell shall print
5866 * parent shell's traps. It only says that its output
5867 * must have suitable form, but then, in the above example
5868 * (which is not supposed to be normative), it implies that.
5869 *
5870 * bash (and probably other shell) does implement it
5871 * (traps are reset to defaults, but "trap" still shows them),
5872 * but as a result, "trap" logic is hopelessly messed up:
5873 *
5874 * # trap
5875 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5876 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5877 * # true | trap <--- trap is in subshell - no output (ditto)
5878 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5879 * trap -- 'echo Ho' SIGWINCH
5880 * # echo `(trap)` <--- in subshell in subshell - output
5881 * trap -- 'echo Ho' SIGWINCH
5882 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5883 * trap -- 'echo Ho' SIGWINCH
5884 *
5885 * The rules when to forget and when to not forget traps
5886 * get really complex and nonsensical.
5887 *
5888 * Our solution: ONLY bare $(trap) or `trap` is special.
5889 */
5890 s = skip_whitespace(s);
5891 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5892 {
5893 static const char *const argv[] = { NULL, NULL };
5894 builtin_trap((char**)argv);
5895 exit(0); /* not _exit() - we need to fflush */
5896 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005897# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005898 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005899 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005900 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005901# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005902 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005903 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5904 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005905 * echo OK
5906 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005907 re_execute_shell(&to_free,
5908 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005909 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005910 G.global_argv + 1,
5911 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005912# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005913 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005914
5915 /* parent */
Denys Vlasenko647553a2009-11-15 19:58:19 +01005916 *pid_p = pid;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005917# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005918 G.count_SIGCHLD++;
5919//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 +02005920# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005921 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005922# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005923 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005924# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005925 close(channel[1]);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005926 close_on_exec_on(channel[0]);
5927 return xfdopen_for_read(channel[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00005928}
5929
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005930/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005931static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005932{
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005933 FILE *fp;
Eric Andersen25f27032001-04-26 23:22:31 +00005934 struct in_str pipe_str;
Denys Vlasenko647553a2009-11-15 19:58:19 +01005935 pid_t pid;
5936 int status, ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005937
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005938 fp = generate_stream_from_string(s, &pid);
Eric Andersen25f27032001-04-26 23:22:31 +00005939
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005940 /* Now send results of command back into original context */
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005941 setup_file_in_str(&pipe_str, fp);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005942 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005943 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005944 if (ch == '\n') {
5945 eol_cnt++;
5946 continue;
5947 }
5948 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005949 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005950 eol_cnt--;
5951 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005952 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005953 }
5954
Denys Vlasenko647553a2009-11-15 19:58:19 +01005955 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005956 fclose(fp);
Denys Vlasenko647553a2009-11-15 19:58:19 +01005957 /* We need to extract exitcode. Test case
5958 * "true; echo `sleep 1; false` $?"
5959 * should print 1 */
5960 safe_waitpid(pid, &status, 0);
5961 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5962 return WEXITSTATUS(status);
Eric Andersen25f27032001-04-26 23:22:31 +00005963}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005964#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005965
Denys Vlasenkoc2704542009-11-20 19:14:19 +01005966#if !ENABLE_HUSH_FUNCTIONS
5967#define parse_group(dest, ctx, input, ch) \
5968 parse_group(ctx, input, ch)
5969#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005970static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005971 struct in_str *input, int ch)
5972{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005973 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005974 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005975 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005976 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005977 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005978 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005979
5980 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005981#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005982 if (ch == '(' && !dest->o_quoted) {
5983 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005984 if (done_word(dest, ctx))
5985 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005986 if (!command->argv)
5987 goto skip; /* (... */
5988 if (command->argv[1]) { /* word word ... (... */
5989 syntax_error_unexpected_ch('(');
5990 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005991 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005992 /* it is "word(..." or "word (..." */
5993 do
5994 ch = i_getch(input);
5995 while (ch == ' ' || ch == '\t');
5996 if (ch != ')') {
5997 syntax_error_unexpected_ch(ch);
5998 return 1;
5999 }
6000 nommu_addchr(&ctx->as_string, ch);
6001 do
6002 ch = i_getch(input);
6003 while (ch == ' ' || ch == '\t' || ch == '\n');
6004 if (ch != '{') {
6005 syntax_error_unexpected_ch(ch);
6006 return 1;
6007 }
6008 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02006009 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006010 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00006011 }
6012#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006013
6014#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006015 if (command->argv /* word [word]{... */
6016 || dest->length /* word{... */
6017 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006018 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006019 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006020 debug_printf_parse("parse_group return 1: "
6021 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006022 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006023 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006024#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006025
6026#if ENABLE_HUSH_FUNCTIONS
6027 skip:
6028#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006029 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006030 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00006031 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02006032 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00006033 } else {
6034 /* bash does not allow "{echo...", requires whitespace */
6035 ch = i_getch(input);
6036 if (ch != ' ' && ch != '\t' && ch != '\n') {
6037 syntax_error_unexpected_ch(ch);
6038 return 1;
6039 }
6040 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006041 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006042
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006043 {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006044#if BB_MMU
6045# define as_string NULL
6046#else
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006047 char *as_string = NULL;
6048#endif
6049 pipe_list = parse_stream(&as_string, input, endch);
6050#if !BB_MMU
6051 if (as_string)
6052 o_addstr(&ctx->as_string, as_string);
6053#endif
6054 /* empty ()/{} or parse error? */
6055 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00006056 /* parse_stream already emitted error msg */
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006057 if (!BB_MMU)
6058 free(as_string);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006059 debug_printf_parse("parse_group return 1: "
6060 "parse_stream returned %p\n", pipe_list);
6061 return 1;
6062 }
6063 command->group = pipe_list;
6064#if !BB_MMU
6065 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
6066 command->group_as_string = as_string;
6067 debug_printf_parse("end of group, remembering as:'%s'\n",
6068 command->group_as_string);
6069#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006070#undef as_string
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006071 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006072 debug_printf_parse("parse_group return 0\n");
6073 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006074 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00006075}
6076
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006077#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006078/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006079static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006080/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006081static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006082{
6083 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006084 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006085 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006086 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006087 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006088 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006089 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006090 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006091 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006092 }
6093}
6094/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006095static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006096{
6097 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006098 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006099 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006100 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006101 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006102 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006103 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006104 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006105 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006106 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006107 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006108 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006109 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006110 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006111 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006112 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006113 continue;
6114 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00006115 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006116 }
6117}
6118/* Process `cmd` - copy contents until "`" is seen. Complicated by
6119 * \` quoting.
6120 * "Within the backquoted style of command substitution, backslash
6121 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
6122 * The search for the matching backquote shall be satisfied by the first
6123 * backquote found without a preceding backslash; during this search,
6124 * if a non-escaped backquote is encountered within a shell comment,
6125 * a here-document, an embedded command substitution of the $(command)
6126 * form, or a quoted string, undefined results occur. A single-quoted
6127 * or double-quoted string that begins, but does not end, within the
6128 * "`...`" sequence produces undefined results."
6129 * Example Output
6130 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
6131 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006132static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006133{
6134 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006135 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006136 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006137 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006138 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006139 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006140 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006141 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006142 if (ch == '\\') {
6143 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006144 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006145 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006146 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006147 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006148 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006149 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006150 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006151 ch = ch2;
6152 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006153 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006154 }
6155}
6156/* Process $(cmd) - copy contents until ")" is seen. Complicated by
6157 * quoting and nested ()s.
6158 * "With the $(command) style of command substitution, all characters
6159 * following the open parenthesis to the matching closing parenthesis
6160 * constitute the command. Any valid shell script can be used for command,
6161 * except a script consisting solely of redirections which produces
6162 * unspecified results."
6163 * Example Output
6164 * echo $(echo '(TEST)' BEST) (TEST) BEST
6165 * echo $(echo 'TEST)' BEST) TEST) BEST
6166 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
Denys Vlasenko74369502010-05-21 19:52:01 +02006167 *
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006168 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006169 * can contain arbitrary constructs, just like $(cmd).
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006170 * In bash compat mode, it needs to also be able to stop on '}' or ':'
6171 * for ${var:N[:M]} parsing.
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006172 */
Denys Vlasenko74369502010-05-21 19:52:01 +02006173#define DOUBLE_CLOSE_CHAR_FLAG 0x80
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006174static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006175{
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006176 int ch;
Denys Vlasenko74369502010-05-21 19:52:01 +02006177 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006178# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006179 char end_char2 = end_ch >> 8;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006180# endif
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006181 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
6182
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006183 while (1) {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006184 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006185 if (ch == EOF) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006186 syntax_error_unterm_ch(end_ch);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006187 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006188 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006189 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006190 if (!dbl)
6191 break;
6192 /* we look for closing )) of $((EXPR)) */
6193 if (i_peek(input) == end_ch) {
6194 i_getch(input); /* eat second ')' */
6195 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00006196 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006197 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006198 o_addchr(dest, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006199 if (ch == '(' || ch == '{') {
6200 ch = (ch == '(' ? ')' : '}');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006201 add_till_closing_bracket(dest, input, ch);
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006202 o_addchr(dest, ch);
6203 continue;
6204 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006205 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006206 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006207 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006208 continue;
6209 }
6210 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006211 add_till_double_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 }
Denys Vlasenkoa6ad3972010-05-22 00:26:06 +02006215 if (ch == '`') {
6216 add_till_backquote(dest, input);
6217 o_addchr(dest, ch);
6218 continue;
6219 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006220 if (ch == '\\') {
6221 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006222 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006223 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006224 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006225 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006226 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00006227 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006228 continue;
6229 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006230 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006231 return ch;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006232}
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006233#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006234
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006235/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006236#if BB_MMU
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006237#define parse_dollar(as_string, dest, input) \
6238 parse_dollar(dest, input)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006239#define as_string NULL
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006240#endif
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006241static int parse_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006242 o_string *dest,
6243 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00006244{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006245 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006246 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006247
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006248 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00006249 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006250 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006251 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00006252 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006253 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006254 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006255 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006256 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00006257 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006258 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006259 if (!isalnum(ch) && ch != '_')
6260 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006261 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006262 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006263 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006264 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006265 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006266 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006267 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006268 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006269 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00006270 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006271 o_addchr(dest, ch | quote_mask);
6272 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006273 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006274 case '$': /* pid */
6275 case '!': /* last bg pid */
6276 case '?': /* last exit code */
6277 case '#': /* number of args */
6278 case '*': /* args */
6279 case '@': /* args */
6280 goto make_one_char_var;
6281 case '{': {
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04006282 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6283
Denys Vlasenko74369502010-05-21 19:52:01 +02006284 ch = i_getch(input); /* eat '{' */
6285 nommu_addchr(as_string, ch);
6286
6287 ch = i_getch(input); /* first char after '{' */
6288 nommu_addchr(as_string, ch);
6289 /* It should be ${?}, or ${#var},
6290 * or even ${?+subst} - operator acting on a special variable,
6291 * or the beginning of variable name.
6292 */
Denys Vlasenkoe85248a2010-05-22 06:20:26 +02006293 if (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) { /* not one of those */
Denys Vlasenko74369502010-05-21 19:52:01 +02006294 bad_dollar_syntax:
6295 syntax_error_unterm_str("${name}");
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006296 debug_printf_parse("parse_dollar return 1: unterminated ${name}\n");
Denys Vlasenko74369502010-05-21 19:52:01 +02006297 return 1;
6298 }
6299 ch |= quote_mask;
6300
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006301 /* It's possible to just call add_till_closing_bracket() at this point.
Denys Vlasenko74369502010-05-21 19:52:01 +02006302 * However, this regresses some of our testsuite cases
6303 * which check invalid constructs like ${%}.
6304 * Oh well... let's check that the var name part is fine... */
6305
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006306 while (1) {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006307 unsigned pos;
6308
Denys Vlasenko74369502010-05-21 19:52:01 +02006309 o_addchr(dest, ch);
6310 debug_printf_parse(": '%c'\n", ch);
6311
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006312 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006313 nommu_addchr(as_string, ch);
Denys Vlasenko74369502010-05-21 19:52:01 +02006314 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00006315 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00006316
Denys Vlasenko74369502010-05-21 19:52:01 +02006317 if (!isalnum(ch) && ch != '_') {
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006318 unsigned end_ch;
6319 unsigned char last_ch;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006320 /* handle parameter expansions
6321 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
6322 */
Denys Vlasenko74369502010-05-21 19:52:01 +02006323 if (!strchr("%#:-=+?", ch)) /* ${var<bad_char>... */
6324 goto bad_dollar_syntax;
Denys Vlasenko74369502010-05-21 19:52:01 +02006325 o_addchr(dest, ch);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006326
6327 /* Eat everything until closing '}' (or ':') */
6328 end_ch = '}';
6329 if (ENABLE_HUSH_BASH_COMPAT
6330 && ch == ':'
6331 && !strchr("%#:-=+?"+3, i_peek(input))
6332 ) {
6333 /* It's ${var:N[:M]} thing */
6334 end_ch = '}' * 0x100 + ':';
6335 }
6336 again:
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006337 if (!BB_MMU)
6338 pos = dest->length;
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006339#if ENABLE_HUSH_DOLLAR_OPS
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006340 last_ch = add_till_closing_bracket(dest, input, end_ch);
Denys Vlasenko9297dbc2010-07-05 21:37:12 +02006341#else
6342#error Simple code to only allow ${var} is not implemented
6343#endif
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006344 if (as_string) {
6345 o_addstr(as_string, dest->data + pos);
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006346 o_addchr(as_string, last_ch);
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006347 }
Denys Vlasenko1e811b12010-05-22 03:12:29 +02006348
6349 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
6350 /* close the first block: */
6351 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6352 /* while parsing N from ${var:N[:M]}... */
6353 if ((end_ch & 0xff) == last_ch) {
6354 /* ...got ':' - parse the rest */
6355 end_ch = '}';
6356 goto again;
6357 }
6358 /* ...got '}', not ':' - it's ${var:N}! emulate :999999999 */
6359 o_addstr(dest, "999999999");
6360 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006361 break;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006362 }
Denys Vlasenko74369502010-05-21 19:52:01 +02006363 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006364 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6365 break;
6366 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006367#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006368 case '(': {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006369 unsigned pos;
6370
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006371 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006372 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006373# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006374 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006375 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006376 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006377 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6378 o_addchr(dest, /*quote_mask |*/ '+');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006379 if (!BB_MMU)
6380 pos = dest->length;
6381 add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG);
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006382 if (as_string) {
6383 o_addstr(as_string, dest->data + pos);
6384 o_addchr(as_string, ')');
6385 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006386 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006387 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00006388 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00006389 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006390# endif
6391# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006392 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6393 o_addchr(dest, quote_mask | '`');
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006394 if (!BB_MMU)
6395 pos = dest->length;
6396 add_till_closing_bracket(dest, input, ')');
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006397 if (as_string) {
6398 o_addstr(as_string, dest->data + pos);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006399 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006400 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006401 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006402# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006403 break;
6404 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00006405#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006406 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006407 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006408 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006409 ch = i_peek(input);
6410 if (isalnum(ch)) { /* it's $_name or $_123 */
6411 ch = '_';
6412 goto make_var;
6413 }
6414 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02006415 /* TODO: $_ and $-: */
6416 /* $_ Shell or shell script name; or last argument of last command
6417 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6418 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006419 /* $- Option flags set by set builtin or shell options (-i etc) */
6420 default:
6421 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00006422 }
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006423 debug_printf_parse("parse_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00006424 return 0;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006425#undef as_string
Eric Andersen25f27032001-04-26 23:22:31 +00006426}
6427
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006428#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006429#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006430 parse_stream_dquoted(dest, input, dquote_end)
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006431#define as_string NULL
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006432#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006433static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006434 o_string *dest,
6435 struct in_str *input,
6436 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006437{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006438 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006439 int next;
6440
6441 again:
6442 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006443 if (ch != EOF)
6444 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006445 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006446 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006447 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006448 debug_printf_parse("parse_stream_dquoted return 0\n");
6449 return 0;
6450 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006451 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006452 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006453 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006454 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006455 }
6456 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006457 if (ch != '\n') {
6458 next = i_peek(input);
6459 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006460 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006461 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006462 if (ch == '\\') {
6463 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006464 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006465 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006466 }
6467 /* bash:
6468 * "The backslash retains its special meaning [in "..."]
6469 * only when followed by one of the following characters:
6470 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006471 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006472 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006473 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00006474 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006475 if (ch != '\n') {
6476 o_addqchr(dest, ch);
6477 nommu_addchr(as_string, ch);
6478 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006479 } else {
6480 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00006481 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006482 }
6483 goto again;
6484 }
6485 if (ch == '$') {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006486 if (parse_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006487 debug_printf_parse("parse_stream_dquoted return 1: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006488 "parse_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006489 return 1;
6490 }
6491 goto again;
6492 }
6493#if ENABLE_HUSH_TICK
6494 if (ch == '`') {
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006495 //unsigned pos = dest->length;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006496 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6497 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006498 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006499 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6500 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00006501 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006502 }
6503#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00006504 o_addQchr(dest, ch);
6505 if (ch == '='
6506 && (dest->o_assignment == MAYBE_ASSIGNMENT
6507 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006508 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00006509 ) {
6510 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6511 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006512 goto again;
Denys Vlasenkoddc62f62010-05-22 00:53:32 +02006513#undef as_string
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006514}
6515
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006516/*
6517 * Scan input until EOF or end_trigger char.
6518 * Return a list of pipes to execute, or NULL on EOF
6519 * or if end_trigger character is met.
6520 * On syntax error, exit is shell is not interactive,
6521 * reset parsing machinery and start parsing anew,
6522 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006523 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006524static struct pipe *parse_stream(char **pstring,
6525 struct in_str *input,
6526 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006527{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006528 struct parse_context ctx;
6529 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006530 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006531 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00006532
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006533 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00006534 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006535 * found. When recursing, quote state is passed in via dest->o_escape.
6536 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006537 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02006538 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006539 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006540
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006541 /* If very first arg is "" or '', dest.data may end up NULL.
6542 * Preventing this: */
6543 o_addchr(&dest, '\0');
6544 dest.length = 0;
6545
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006546 G.ifs = get_local_var_value("IFS");
6547 if (G.ifs == NULL)
Denys Vlasenko03dad222010-01-12 23:29:57 +01006548 G.ifs = defifs;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006549
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006550 reset:
6551#if ENABLE_HUSH_INTERACTIVE
6552 input->promptmode = 0; /* PS1 */
6553#endif
6554 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6555 initialize_context(&ctx);
6556 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006557 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006558 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006559 const char *is_ifs;
6560 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006561 int ch;
6562 int next;
6563 int redir_fd;
6564 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006565
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006566 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006567 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006568 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006569 goto parse_error;
6570 }
6571 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006572 is_in_dquote = 0;
6573 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006574 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006575 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6576 ch, ch, dest.o_escape);
6577 if (ch == EOF) {
6578 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006579
6580 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006581 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006582 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006583 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006584 /* end_trigger == '}' case errors out earlier,
6585 * checking only ')' */
6586 if (end_trigger == ')') {
6587 syntax_error_unterm_ch('('); /* exits */
6588 /* goto parse_error; */
6589 }
6590
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006591 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006592 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006593 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006594 o_free(&dest);
6595 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006596 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006597 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006598 /* (this makes bare "&" cmd a no-op.
6599 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006600 if (pi->num_cmds == 0
6601 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6602 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006603 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006604 pi = NULL;
6605 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006606#if !BB_MMU
6607 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6608 if (pstring)
6609 *pstring = ctx.as_string.data;
6610 else
6611 o_free_unsafe(&ctx.as_string);
6612#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006613 debug_leave();
6614 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006615 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006616 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006617 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006618
6619 next = '\0';
6620 if (ch != '\n')
6621 next = i_peek(input);
6622
6623 is_special = "{}<>;&|()#'" /* special outside of "str" */
6624 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6625 /* Are { and } special here? */
Denys Vlasenko3227d3f2010-05-17 09:49:47 +02006626 if (ctx.command->argv /* word [word]{... - non-special */
6627 || dest.length /* word{... - non-special */
6628 || dest.o_quoted /* ""{... - non-special */
6629 || (next != ';' /* }; - special */
6630 && next != ')' /* }) - special */
6631 && next != '&' /* }& and }&& ... - special */
6632 && next != '|' /* }|| ... - special */
6633 && !strchr(G.ifs, next) /* {word - non-special */
6634 )
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006635 ) {
6636 /* They are not special, skip "{}" */
6637 is_special += 2;
6638 }
6639 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006640 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006641
6642 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006643 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006644 o_addQchr(&dest, ch);
6645 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6646 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00006647 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006648 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00006649 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006650 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006651 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006652 continue;
6653 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00006654
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006655 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006656 if (done_word(&dest, &ctx)) {
6657 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00006658 }
Denis Vlasenko37181682009-04-03 03:19:15 +00006659 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00006660#if ENABLE_HUSH_CASE
6661 /* "case ... in <newline> word) ..." -
6662 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006663 if (ctx.command->argv == NULL
6664 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00006665 ) {
6666 continue;
6667 }
6668#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006669 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006670 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006671 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6672 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006673 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006674 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006675 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006676 heredoc_cnt = 0;
6677 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006678 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006679 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006680 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006681 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006682 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006683 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006684
6685 /* "cmd}" or "cmd }..." without semicolon or &:
6686 * } is an ordinary char in this case, even inside { cmd; }
6687 * Pathological example: { ""}; } should exec "}" cmd
6688 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006689 if (ch == '}') {
6690 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6691 || dest.length != 0 /* word} */
6692 || dest.o_quoted /* ""} */
6693 ) {
6694 goto ordinary_char;
6695 }
6696 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6697 goto skip_end_trigger;
6698 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006699 }
6700
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006701 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006702 && (ch != ';' || heredoc_cnt == 0)
6703#if ENABLE_HUSH_CASE
6704 && (ch != ')'
6705 || ctx.ctx_res_w != RES_MATCH
6706 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6707 )
6708#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006709 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006710 if (heredoc_cnt) {
6711 /* This is technically valid:
6712 * { cat <<HERE; }; echo Ok
6713 * heredoc
6714 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006715 * HERE
6716 * but we don't support this.
6717 * We require heredoc to be in enclosing {}/(),
6718 * if any.
6719 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006720 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006721 goto parse_error;
6722 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006723 if (done_word(&dest, &ctx)) {
6724 goto parse_error;
6725 }
6726 done_pipe(&ctx, PIPE_SEQ);
6727 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006728 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006729 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006730 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006731 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006732 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006733#if !BB_MMU
6734 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6735 if (pstring)
6736 *pstring = ctx.as_string.data;
6737 else
6738 o_free_unsafe(&ctx.as_string);
6739#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006740 debug_leave();
6741 debug_printf_parse("parse_stream return %p: "
6742 "end_trigger char found\n",
6743 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006744 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006745 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006746 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006747 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006748 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006749 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006750
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006751 /* Catch <, > before deciding whether this word is
6752 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6753 switch (ch) {
6754 case '>':
6755 redir_fd = redirect_opt_num(&dest);
6756 if (done_word(&dest, &ctx)) {
6757 goto parse_error;
6758 }
6759 redir_style = REDIRECT_OVERWRITE;
6760 if (next == '>') {
6761 redir_style = REDIRECT_APPEND;
6762 ch = i_getch(input);
6763 nommu_addchr(&ctx.as_string, ch);
6764 }
6765#if 0
6766 else if (next == '(') {
6767 syntax_error(">(process) not supported");
6768 goto parse_error;
6769 }
6770#endif
6771 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6772 goto parse_error;
6773 continue; /* back to top of while (1) */
6774 case '<':
6775 redir_fd = redirect_opt_num(&dest);
6776 if (done_word(&dest, &ctx)) {
6777 goto parse_error;
6778 }
6779 redir_style = REDIRECT_INPUT;
6780 if (next == '<') {
6781 redir_style = REDIRECT_HEREDOC;
6782 heredoc_cnt++;
6783 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6784 ch = i_getch(input);
6785 nommu_addchr(&ctx.as_string, ch);
6786 } else if (next == '>') {
6787 redir_style = REDIRECT_IO;
6788 ch = i_getch(input);
6789 nommu_addchr(&ctx.as_string, ch);
6790 }
6791#if 0
6792 else if (next == '(') {
6793 syntax_error("<(process) not supported");
6794 goto parse_error;
6795 }
6796#endif
6797 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6798 goto parse_error;
6799 continue; /* back to top of while (1) */
6800 }
6801
6802 if (dest.o_assignment == MAYBE_ASSIGNMENT
6803 /* check that we are not in word in "a=1 2>word b=1": */
6804 && !ctx.pending_redirect
6805 ) {
6806 /* ch is a special char and thus this word
6807 * cannot be an assignment */
6808 dest.o_assignment = NOT_ASSIGNMENT;
6809 }
6810
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006811 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6812
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006813 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006814 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006815 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006816 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006817 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006818 if (ch == EOF || ch == '\n')
6819 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006820 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006821 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006822 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006823 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006824 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006825 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006826 }
6827 break;
6828 case '\\':
6829 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006830 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006831 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006832 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006833 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006834 if (ch != '\n') {
6835 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006836 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006837 o_addchr(&dest, ch);
6838 nommu_addchr(&ctx.as_string, ch);
6839 /* Example: echo Hello \2>file
6840 * we need to know that word 2 is quoted */
6841 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006842 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006843#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006844 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006845 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6846 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006847 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006848#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006849 break;
6850 case '$':
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006851 if (parse_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006852 debug_printf_parse("parse_stream parse error: "
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006853 "parse_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006854 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006855 }
Eric Andersen25f27032001-04-26 23:22:31 +00006856 break;
6857 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006858 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006859 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006860 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006861 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006862 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006863 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006864 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006865 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006866 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006867 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006868 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006869 }
Eric Andersen25f27032001-04-26 23:22:31 +00006870 break;
6871 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006872 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006873 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006874 if (dest.o_assignment == NOT_ASSIGNMENT)
6875 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006876 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006877#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006878 case '`': {
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006879 unsigned pos;
6880
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006881 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6882 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006883 pos = dest.length;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006884 add_till_backquote(&dest, input);
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006885# if !BB_MMU
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006886 o_addstr(&ctx.as_string, dest.data + pos);
6887 o_addchr(&ctx.as_string, '`');
Denys Vlasenko2e48d532010-05-22 17:30:39 +02006888# endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006889 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6890 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006891 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006892 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006893#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006894 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006895#if ENABLE_HUSH_CASE
6896 case_semi:
6897#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006898 if (done_word(&dest, &ctx)) {
6899 goto parse_error;
6900 }
6901 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006902#if ENABLE_HUSH_CASE
6903 /* Eat multiple semicolons, detect
6904 * whether it means something special */
6905 while (1) {
6906 ch = i_peek(input);
6907 if (ch != ';')
6908 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006909 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006910 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006911 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006912 ctx.ctx_dsemicolon = 1;
6913 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006914 break;
6915 }
6916 }
6917#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006918 new_cmd:
6919 /* We just finished a cmd. New one may start
6920 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006921 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006922 break;
6923 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006924 if (done_word(&dest, &ctx)) {
6925 goto parse_error;
6926 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006927 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006928 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006929 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006930 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006931 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006932 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006933 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006934 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006935 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006936 if (done_word(&dest, &ctx)) {
6937 goto parse_error;
6938 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006939#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006940 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006941 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006942#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006943 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006944 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006945 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006946 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006947 } else {
6948 /* we could pick up a file descriptor choice here
6949 * with redirect_opt_num(), but bash doesn't do it.
6950 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006951 done_command(&ctx);
Denys Vlasenkob70cef72010-01-12 13:45:45 +01006952#if !BB_MMU
6953 o_reset_to_empty_unquoted(&ctx.as_string);
6954#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006955 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006956 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006957 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006958#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006959 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006960 if (ctx.ctx_res_w == RES_MATCH
6961 && ctx.command->argv == NULL /* not (word|(... */
6962 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006963 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006964 ) {
6965 continue;
6966 }
6967#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006968 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006969 if (parse_group(&dest, &ctx, input, ch) != 0) {
6970 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006971 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006972 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006973 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006974#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006975 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006976 goto case_semi;
6977#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006978 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006979 /* proper use of this character is caught by end_trigger:
6980 * if we see {, we call parse_group(..., end_trigger='}')
6981 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006982 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006983 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006984 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006985 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006986 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006987 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006988 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006989
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006990 parse_error:
6991 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006992 struct parse_context *pctx;
6993 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006994
6995 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006996 * Sample for finding leaks on syntax error recovery path.
6997 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006998 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006999 * Samples to catch leaks at execution:
7000 * while if (true | {true;}); then echo ok; fi; do break; done
7001 * 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 +00007002 */
7003 pctx = &ctx;
7004 do {
7005 /* Update pipe/command counts,
7006 * otherwise freeing may miss some */
7007 done_pipe(pctx, PIPE_SEQ);
7008 debug_printf_clean("freeing list %p from ctx %p\n",
7009 pctx->list_head, pctx);
7010 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00007011 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007012 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007013#if !BB_MMU
7014 o_free_unsafe(&pctx->as_string);
7015#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007016 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007017 if (pctx != &ctx) {
7018 free(pctx);
7019 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007020 IF_HAS_KEYWORDS(pctx = p2;)
7021 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007022 /* Free text, clear all dest fields */
7023 o_free(&dest);
7024 /* If we are not in top-level parse, we return,
7025 * our caller will propagate error.
7026 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007027 if (end_trigger != ';') {
7028#if !BB_MMU
7029 if (pstring)
7030 *pstring = NULL;
7031#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00007032 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007033 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007034 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007035 /* Discard cached input, force prompt */
7036 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007037 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007038 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00007039 }
Eric Andersen25f27032001-04-26 23:22:31 +00007040}
7041
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007042/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007043 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
7044 * end_trigger controls how often we stop parsing
7045 * NUL: parse all, execute, return
7046 * ';': parse till ';' or newline, execute, repeat till EOF
7047 */
7048static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00007049{
Denys Vlasenko00243b02009-11-16 02:00:03 +01007050 /* Why we need empty flag?
7051 * An obscure corner case "false; ``; echo $?":
7052 * empty command in `` should still set $? to 0.
7053 * But we can't just set $? to 0 at the start,
7054 * this breaks "false; echo `echo $?`" case.
7055 */
7056 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007057 while (1) {
7058 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00007059
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00007060 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007061 if (!pipe_list) { /* EOF */
7062 if (empty)
7063 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007064 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01007065 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007066 debug_print_tree(pipe_list, 0);
7067 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
7068 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01007069 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007070 }
Eric Andersen25f27032001-04-26 23:22:31 +00007071}
7072
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007073static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00007074{
7075 struct in_str input;
7076 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007077 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00007078}
7079
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007080static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00007081{
Eric Andersen25f27032001-04-26 23:22:31 +00007082 struct in_str input;
7083 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007084 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00007085}
7086
Denis Vlasenkof9375282009-04-05 19:13:39 +00007087/* Called a few times only (or even once if "sh -c") */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007088static void init_sigmasks(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00007089{
Denis Vlasenkof9375282009-04-05 19:13:39 +00007090 unsigned sig;
7091 unsigned mask;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007092 sigset_t old_blocked_set;
7093
7094 if (!G.inherited_set_is_saved) {
7095 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
7096 G.inherited_set = G.blocked_set;
7097 }
7098 old_blocked_set = G.blocked_set;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007099
Denis Vlasenkof9375282009-04-05 19:13:39 +00007100 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007101 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00007102 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04007103 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007104 mask |= SPECIAL_JOB_SIGS;
7105 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007106 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00007107
Denis Vlasenkof9375282009-04-05 19:13:39 +00007108 sig = 0;
7109 while (mask) {
7110 if (mask & 1)
7111 sigaddset(&G.blocked_set, sig);
7112 mask >>= 1;
7113 sig++;
7114 }
7115 sigdelset(&G.blocked_set, SIGCHLD);
7116
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007117 if (memcmp(&old_blocked_set, &G.blocked_set, sizeof(old_blocked_set)) != 0)
7118 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7119
Denis Vlasenkof9375282009-04-05 19:13:39 +00007120 /* POSIX allows shell to re-enable SIGCHLD
7121 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007122#if ENABLE_HUSH_FAST
7123 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007124 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007125 signal(SIGCHLD, SIGCHLD_handler);
7126#else
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007127 if (!G.inherited_set_is_saved)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02007128 signal(SIGCHLD, SIG_DFL);
7129#endif
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007130
7131 G.inherited_set_is_saved = 1;
Denis Vlasenkof9375282009-04-05 19:13:39 +00007132}
7133
7134#if ENABLE_HUSH_JOB
7135/* helper */
7136static void maybe_set_to_sigexit(int sig)
7137{
7138 void (*handler)(int);
7139 /* non_DFL_mask'ed signals are, well, masked,
7140 * no need to set handler for them.
7141 */
7142 if (!((G.non_DFL_mask >> sig) & 1)) {
7143 handler = signal(sig, sigexit);
7144 if (handler == SIG_IGN) /* oops... restore back to IGN! */
7145 signal(sig, handler);
7146 }
7147}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007148/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007149static void set_fatal_handlers(void)
7150{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00007151 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007152 if (HUSH_DEBUG) {
7153 maybe_set_to_sigexit(SIGILL );
7154 maybe_set_to_sigexit(SIGFPE );
7155 maybe_set_to_sigexit(SIGBUS );
7156 maybe_set_to_sigexit(SIGSEGV);
7157 maybe_set_to_sigexit(SIGTRAP);
7158 } /* else: hush is perfect. what SEGV? */
7159 maybe_set_to_sigexit(SIGABRT);
7160 /* bash 3.2 seems to handle these just like 'fatal' ones */
7161 maybe_set_to_sigexit(SIGPIPE);
7162 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007163 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007164 * if we aren't interactive... but in this case
7165 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007166 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00007167 /*maybe_set_to_sigexit(SIGTERM);*/
7168 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00007169}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00007170#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00007171
Denis Vlasenkod5762932009-03-31 11:22:57 +00007172static int set_mode(const char cstate, const char mode)
7173{
7174 int state = (cstate == '-' ? 1 : 0);
7175 switch (mode) {
Denys Vlasenko202a2d12010-07-16 12:36:14 +02007176 case 'n': G.n_mode = state; break;
7177 case 'x': IF_HUSH_MODE_X(G_x_mode = state;) break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007178 default: return EXIT_FAILURE;
7179 }
7180 return EXIT_SUCCESS;
7181}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007182
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00007183int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00007184int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00007185{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007186 static const struct variable const_shell_ver = {
7187 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00007188 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007189 .max_len = 1, /* 0 can provoke free(name) */
7190 .flg_export = 1,
7191 .flg_read_only = 1,
7192 };
Eric Andersen25f27032001-04-26 23:22:31 +00007193 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007194 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007195 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007196 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00007197
Denis Vlasenko574f2f42008-02-27 18:41:59 +00007198 INIT_G();
Denys Vlasenkocddbb612010-05-20 14:27:09 +02007199 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, it is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007200 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007201#if !BB_MMU
7202 G.argv0_for_re_execing = argv[0];
7203#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007204 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007205 G.shell_ver = const_shell_ver; /* copying struct here */
7206 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007207 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007208 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7209 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007210 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00007211 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00007212 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007213 if (e) while (*e) {
7214 char *value = strchr(*e, '=');
7215 if (value) { /* paranoia */
7216 cur_var->next = xzalloc(sizeof(*cur_var));
7217 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007218 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007219 cur_var->max_len = strlen(*e);
7220 cur_var->flg_export = 1;
7221 }
7222 e++;
7223 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007224 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00007225 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02007226 putenv((char *)hush_version_str);
7227
7228 /* Export PWD */
7229 set_pwd_var(/*exp:*/ 1);
7230 /* bash also exports SHLVL and _,
7231 * and sets (but doesn't export) the following variables:
7232 * BASH=/bin/bash
7233 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7234 * BASH_VERSION='3.2.0(1)-release'
7235 * HOSTTYPE=i386
7236 * MACHTYPE=i386-pc-linux-gnu
7237 * OSTYPE=linux-gnu
7238 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02007239 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02007240 * EUID=<NNNNN>
7241 * UID=<NNNNN>
7242 * GROUPS=()
7243 * LINES=<NNN>
7244 * COLUMNS=<NNN>
7245 * BASH_ARGC=()
7246 * BASH_ARGV=()
7247 * BASH_LINENO=()
7248 * BASH_SOURCE=()
7249 * DIRSTACK=()
7250 * PIPESTATUS=([0]="0")
7251 * HISTFILE=/<xxx>/.bash_history
7252 * HISTFILESIZE=500
7253 * HISTSIZE=500
7254 * MAILCHECK=60
7255 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7256 * SHELL=/bin/bash
7257 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7258 * TERM=dumb
7259 * OPTERR=1
7260 * OPTIND=1
7261 * IFS=$' \t\n'
7262 * PS1='\s-\v\$ '
7263 * PS2='> '
7264 * PS4='+ '
7265 */
7266
Denis Vlasenko38f63192007-01-22 09:03:07 +00007267#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00007268 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00007269#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00007270 G.global_argc = argc;
7271 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00007272 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00007273 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00007274
Denis Vlasenkoed782372009-04-10 00:45:02 +00007275 if (setjmp(die_jmp)) {
7276 /* xfunc has failed! die die die */
7277 /* no EXIT traps, this is an escape hatch! */
7278 G.exiting = 1;
7279 hush_exit(xfunc_error_retval);
7280 }
7281
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007282 /* Shell is non-interactive at first. We need to call
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007283 * init_sigmasks() if we are going to execute "sh <script>",
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007284 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007285 * If we later decide that we are interactive, we run init_sigmasks()
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007286 * in order to intercept (more) signals.
7287 */
7288
7289 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007290 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007291 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007292 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02007293 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007294#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00007295 "<:$:R:V:"
7296# if ENABLE_HUSH_FUNCTIONS
7297 "F:"
7298# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007299#endif
7300 );
7301 if (opt <= 0)
7302 break;
Eric Andersen25f27032001-04-26 23:22:31 +00007303 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007304 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007305 /* Possibilities:
7306 * sh ... -c 'script'
7307 * sh ... -c 'script' ARG0 [ARG1...]
7308 * On NOMMU, if builtin_argc != 0,
Denys Vlasenko17323a62010-01-28 01:57:05 +01007309 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007310 * "" needs to be replaced with NULL
7311 * and BARGV vector fed to builtin function.
Denys Vlasenko17323a62010-01-28 01:57:05 +01007312 * Note: the form without ARG0 never happens:
7313 * sh ... -c 'builtin' BARGV... ""
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007314 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02007315 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007316 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007317 G.root_ppid = getppid();
7318 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007319 G.global_argv = argv + optind;
7320 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007321 if (builtin_argc) {
7322 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7323 const struct built_in_command *x;
7324
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007325 init_sigmasks();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007326 x = find_builtin(optarg);
7327 if (x) { /* paranoia */
7328 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7329 G.global_argv += builtin_argc;
7330 G.global_argv[-1] = NULL; /* replace "" */
Denys Vlasenko17323a62010-01-28 01:57:05 +01007331 G.last_exitcode = x->b_function(argv + optind - 1);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007332 }
7333 goto final_return;
7334 }
7335 if (!G.global_argv[0]) {
7336 /* -c 'script' (no params): prevent empty $0 */
7337 G.global_argv--; /* points to argv[i] of 'script' */
7338 G.global_argv[0] = argv[0];
Denys Vlasenko5ae8f1c2010-05-22 06:32:11 +02007339 G.global_argc++;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007340 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007341 init_sigmasks();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007342 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007343 goto final_return;
7344 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00007345 /* Well, we cannot just declare interactiveness,
7346 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007347 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007348 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00007349 case 's':
7350 /* "-s" means "read from stdin", but this is how we always
7351 * operate, so simply do nothing here. */
7352 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007353#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007354 case '<': /* "big heredoc" support */
Denys Vlasenko729ecb82010-06-07 14:14:26 +02007355 full_write1_str(optarg);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00007356 _exit(0);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007357 case '$': {
7358 unsigned long long empty_trap_mask;
7359
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007360 G.root_pid = bb_strtou(optarg, &optarg, 16);
7361 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02007362 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7363 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007364 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7365 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007366 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007367 optarg++;
7368 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007369 optarg++;
7370 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7371 if (empty_trap_mask != 0) {
7372 int sig;
7373 init_sigmasks();
7374 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7375 for (sig = 1; sig < NSIG; sig++) {
7376 if (empty_trap_mask & (1LL << sig)) {
7377 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7378 sigaddset(&G.blocked_set, sig);
7379 }
7380 }
7381 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7382 }
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007383# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007384 optarg++;
7385 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007386# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00007387 break;
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007388 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007389 case 'R':
7390 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02007391 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007392 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00007393# if ENABLE_HUSH_FUNCTIONS
7394 case 'F': {
7395 struct function *funcp = new_function(optarg);
7396 /* funcp->name is already set to optarg */
7397 /* funcp->body is set to NULL. It's a special case. */
7398 funcp->body_as_string = argv[optind];
7399 optind++;
7400 break;
7401 }
7402# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00007403#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007404 case 'n':
7405 case 'x':
Denys Vlasenko889550b2010-07-14 19:01:25 +02007406 if (set_mode('-', opt) == 0) /* no error */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007407 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007408 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007409#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007410 fprintf(stderr, "Usage: sh [FILE]...\n"
7411 " or: sh -c command [args]...\n\n");
7412 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007413#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00007414 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00007415#endif
Eric Andersen25f27032001-04-26 23:22:31 +00007416 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007417 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007418
Denys Vlasenkodea47882009-10-09 15:40:49 +02007419 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007420 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02007421 G.root_ppid = getppid();
7422 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007423
7424 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007425 if (argv[0] && argv[0][0] == '-') {
7426 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007427 debug_printf("sourcing /etc/profile\n");
7428 input = fopen_for_read("/etc/profile");
7429 if (input != NULL) {
7430 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007431 init_sigmasks();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007432 parse_and_run_file(input);
7433 fclose(input);
7434 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007435 /* bash: after sourcing /etc/profile,
7436 * tries to source (in the given order):
7437 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007438 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00007439 * bash also sources ~/.bash_logout on exit.
7440 * If called as sh, skips .bash_XXX files.
7441 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007442 }
7443
Denis Vlasenkof9375282009-04-05 19:13:39 +00007444 if (argv[optind]) {
7445 FILE *input;
7446 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007447 * "bash <script>" (which is never interactive (unless -i?))
7448 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007449 * If called as sh, does the same but with $ENV.
7450 */
7451 debug_printf("running script '%s'\n", argv[optind]);
7452 G.global_argv = argv + optind;
7453 G.global_argc = argc - optind;
7454 input = xfopen_for_read(argv[optind]);
7455 close_on_exec_on(fileno(input));
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007456 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007457 parse_and_run_file(input);
7458#if ENABLE_FEATURE_CLEAN_UP
7459 fclose(input);
7460#endif
7461 goto final_return;
7462 }
7463
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007464 /* Up to here, shell was non-interactive. Now it may become one.
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007465 * NB: don't forget to (re)run init_sigmasks() as needed.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007466 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007467
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007468 /* A shell is interactive if the '-i' flag was given,
7469 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007470 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007471 * no arguments remaining or the -s flag given
7472 * standard input is a terminal
7473 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007474 * Refer to Posix.2, the description of the 'sh' utility.
7475 */
7476#if ENABLE_HUSH_JOB
7477 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007478 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7479 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7480 if (G_saved_tty_pgrp < 0)
7481 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007482
7483 /* try to dup stdin to high fd#, >= 255 */
7484 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7485 if (G_interactive_fd < 0) {
7486 /* try to dup to any fd */
7487 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007488 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007489 /* give up */
7490 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007491 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007492 }
7493 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007494// TODO: track & disallow any attempts of user
7495// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007496 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007497 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007498 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007499 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007500
Mike Frysinger38478a62009-05-20 04:48:06 -04007501 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007502 /* If we were run as 'hush &', sleep until we are
7503 * in the foreground (tty pgrp == our pgrp).
7504 * If we get started under a job aware app (like bash),
7505 * make sure we are now in charge so we don't fight over
7506 * who gets the foreground */
7507 while (1) {
7508 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007509 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7510 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007511 break;
7512 /* send TTIN to ourself (should stop us) */
7513 kill(- shell_pgrp, SIGTTIN);
7514 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007515 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007516
Denis Vlasenkof9375282009-04-05 19:13:39 +00007517 /* Block some signals */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007518 init_sigmasks();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007519
Mike Frysinger38478a62009-05-20 04:48:06 -04007520 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007521 /* Set other signals to restore saved_tty_pgrp */
7522 set_fatal_handlers();
7523 /* Put ourselves in our own process group
7524 * (bash, too, does this only if ctty is available) */
7525 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7526 /* Grab control of the terminal */
7527 tcsetpgrp(G_interactive_fd, getpid());
7528 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007529 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007530 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007531 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007532 } else {
7533 init_sigmasks();
7534 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007535#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007536 /* No job control compiled in, only prompt/line editing */
7537 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007538 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7539 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007540 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007541 G_interactive_fd = dup(STDIN_FILENO);
7542 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007543 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007544 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007545 }
7546 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007547 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007548 close_on_exec_on(G_interactive_fd);
Denis Vlasenkof9375282009-04-05 19:13:39 +00007549 }
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007550 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007551#else
7552 /* We have interactiveness code disabled */
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007553 init_sigmasks();
Denis Vlasenkof9375282009-04-05 19:13:39 +00007554#endif
7555 /* bash:
7556 * if interactive but not a login shell, sources ~/.bashrc
7557 * (--norc turns this off, --rcfile <file> overrides)
7558 */
7559
7560 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007561 /* note: ash and hush share this string */
7562 printf("\n\n%s %s\n"
7563 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7564 "\n",
7565 bb_banner,
7566 "hush - the humble shell"
7567 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007568 }
7569
Denis Vlasenkof9375282009-04-05 19:13:39 +00007570 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007571
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007572 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007573#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007574 if (G.cwd != bb_msg_unknown)
7575 free((char*)G.cwd);
7576 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007577 while (cur_var) {
7578 struct variable *tmp = cur_var;
7579 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007580 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007581 cur_var = cur_var->next;
7582 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007583 }
Eric Andersen25f27032001-04-26 23:22:31 +00007584#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007585 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007586}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007587
7588
7589#if ENABLE_LASH
7590int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7591int lash_main(int argc, char **argv)
7592{
Denys Vlasenko07934912009-08-20 03:40:04 +02007593 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007594 return hush_main(argc, argv);
7595}
7596#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007597
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007598#if ENABLE_MSH
7599int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7600int msh_main(int argc, char **argv)
7601{
7602 //bb_error_msg("msh is deprecated, please use hush instead");
7603 return hush_main(argc, argv);
7604}
7605#endif
7606
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007607
7608/*
7609 * Built-ins
7610 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007611static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007612{
7613 return 0;
7614}
7615
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007616static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007617{
7618 int argc = 0;
7619 while (*argv) {
7620 argc++;
7621 argv++;
7622 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007623 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007624}
7625
7626static int FAST_FUNC builtin_test(char **argv)
7627{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007628 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007629}
7630
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007631static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007632{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007633 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007634}
7635
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007636#if ENABLE_PRINTF
7637static int FAST_FUNC builtin_printf(char **argv)
7638{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007639 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007640}
7641#endif
7642
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007643static char **skip_dash_dash(char **argv)
7644{
7645 argv++;
7646 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
7647 argv++;
7648 return argv;
7649}
7650
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007651static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007652{
7653 int rcode = EXIT_SUCCESS;
7654
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007655 argv = skip_dash_dash(argv);
7656 if (*argv) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007657 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007658 /* bash:
7659 * eval "echo Hi; done" ("done" is syntax error):
7660 * "echo Hi" will not execute too.
7661 */
7662 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007663 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007664 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007665 }
7666 return rcode;
7667}
7668
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007669static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007670{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007671 const char *newdir;
7672
7673 argv = skip_dash_dash(argv);
7674 newdir = argv[0];
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007675 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007676 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007677 * bash says "bash: cd: HOME not set" and does nothing
7678 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007679 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007680 const char *home = get_local_var_value("HOME");
7681 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007682 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007683 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007684 /* Mimic bash message exactly */
7685 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007686 return EXIT_FAILURE;
7687 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007688 /* Read current dir (get_cwd(1) is inside) and set PWD.
7689 * Note: do not enforce exporting. If PWD was unset or unexported,
7690 * set it again, but do not export. bash does the same.
7691 */
7692 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007693 return EXIT_SUCCESS;
7694}
7695
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007696static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007697{
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007698 argv = skip_dash_dash(argv);
7699 if (argv[0] == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007700 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007701
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007702 /* Careful: we can end up here after [v]fork. Do not restore
7703 * tty pgrp then, only top-level shell process does that */
7704 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7705 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7706
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007707 /* TODO: if exec fails, bash does NOT exit! We do.
7708 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7709 * and tcsetpgrp, and this is inherently racy.
7710 */
7711 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007712}
7713
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007714static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007715{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007716 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007717
7718 /* interactive bash:
7719 * # trap "echo EEE" EXIT
7720 * # exit
7721 * exit
7722 * There are stopped jobs.
7723 * (if there are _stopped_ jobs, running ones don't count)
7724 * # exit
7725 * exit
7726 # EEE (then bash exits)
7727 *
7728 * we can use G.exiting = -1 as indicator "last cmd was exit"
7729 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007730
7731 /* note: EXIT trap is run by hush_exit */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007732 argv = skip_dash_dash(argv);
7733 if (argv[0] == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007734 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007735 /* mimic bash: exit 123abc == exit 255 + error msg */
7736 xfunc_error_retval = 255;
7737 /* bash: exit -2 == exit 254, no error msg */
Denys Vlasenkob131cce2010-05-20 03:39:43 +02007738 hush_exit(xatoi(argv[0]) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007739}
7740
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007741static void print_escaped(const char *s)
7742{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007743 if (*s == '\'')
7744 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007745 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007746 const char *p = strchrnul(s, '\'');
7747 /* print 'xxxx', possibly just '' */
7748 printf("'%.*s'", (int)(p - s), s);
7749 if (*p == '\0')
7750 break;
7751 s = p;
7752 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007753 /* s points to '; print "'''...'''" */
7754 putchar('"');
7755 do putchar('\''); while (*++s == '\'');
7756 putchar('"');
7757 } while (*s);
7758}
7759
Denys Vlasenko295fef82009-06-03 12:47:26 +02007760#if !ENABLE_HUSH_LOCAL
7761#define helper_export_local(argv, exp, lvl) \
7762 helper_export_local(argv, exp)
7763#endif
7764static void helper_export_local(char **argv, int exp, int lvl)
7765{
7766 do {
7767 char *name = *argv;
7768
7769 /* So far we do not check that name is valid (TODO?) */
7770
7771 if (strchr(name, '=') == NULL) {
7772 struct variable *var;
7773
7774 var = get_local_var(name);
7775 if (exp == -1) { /* unexporting? */
7776 /* export -n NAME (without =VALUE) */
7777 if (var) {
7778 var->flg_export = 0;
7779 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7780 unsetenv(name);
7781 } /* else: export -n NOT_EXISTING_VAR: no-op */
7782 continue;
7783 }
7784 if (exp == 1) { /* exporting? */
7785 /* export NAME (without =VALUE) */
7786 if (var) {
7787 var->flg_export = 1;
7788 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7789 putenv(var->varstr);
7790 continue;
7791 }
7792 }
7793 /* Exporting non-existing variable.
7794 * bash does not put it in environment,
7795 * but remembers that it is exported,
7796 * and does put it in env when it is set later.
7797 * We just set it to "" and export. */
7798 /* Or, it's "local NAME" (without =VALUE).
7799 * bash sets the value to "". */
7800 name = xasprintf("%s=", name);
7801 } else {
7802 /* (Un)exporting/making local NAME=VALUE */
7803 name = xstrdup(name);
7804 }
7805 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7806 } while (*++argv);
7807}
7808
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007809static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007810{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007811 unsigned opt_unexport;
7812
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007813#if ENABLE_HUSH_EXPORT_N
7814 /* "!": do not abort on errors */
7815 opt_unexport = getopt32(argv, "!n");
7816 if (opt_unexport == (uint32_t)-1)
7817 return EXIT_FAILURE;
7818 argv += optind;
7819#else
7820 opt_unexport = 0;
7821 argv++;
7822#endif
7823
7824 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007825 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007826 if (e) {
7827 while (*e) {
7828#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007829 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007830#else
7831 /* ash emits: export VAR='VAL'
7832 * bash: declare -x VAR="VAL"
7833 * we follow ash example */
7834 const char *s = *e++;
7835 const char *p = strchr(s, '=');
7836
7837 if (!p) /* wtf? take next variable */
7838 continue;
7839 /* export var= */
7840 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007841 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007842 putchar('\n');
7843#endif
7844 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007845 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007846 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007847 return EXIT_SUCCESS;
7848 }
7849
Denys Vlasenko295fef82009-06-03 12:47:26 +02007850 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007851
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007852 return EXIT_SUCCESS;
7853}
7854
Denys Vlasenko295fef82009-06-03 12:47:26 +02007855#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007856static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007857{
7858 if (G.func_nest_level == 0) {
7859 bb_error_msg("%s: not in a function", argv[0]);
7860 return EXIT_FAILURE; /* bash compat */
7861 }
7862 helper_export_local(argv, 0, G.func_nest_level);
7863 return EXIT_SUCCESS;
7864}
7865#endif
7866
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007867static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007868{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007869 int sig;
7870 char *new_cmd;
7871
7872 if (!G.traps)
7873 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7874
7875 argv++;
7876 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007877 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007878 /* No args: print all trapped */
7879 for (i = 0; i < NSIG; ++i) {
7880 if (G.traps[i]) {
7881 printf("trap -- ");
7882 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007883 /* note: bash adds "SIG", but only if invoked
7884 * as "bash". If called as "sh", or if set -o posix,
7885 * then it prints short signal names.
7886 * We are printing short names: */
7887 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007888 }
7889 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007890 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007891 return EXIT_SUCCESS;
7892 }
7893
7894 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007895 /* If first arg is a number: reset all specified signals */
7896 sig = bb_strtou(*argv, NULL, 10);
7897 if (errno == 0) {
7898 int ret;
7899 process_sig_list:
7900 ret = EXIT_SUCCESS;
7901 while (*argv) {
7902 sig = get_signum(*argv++);
7903 if (sig < 0 || sig >= NSIG) {
7904 ret = EXIT_FAILURE;
7905 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007906 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007907 continue;
7908 }
7909
7910 free(G.traps[sig]);
7911 G.traps[sig] = xstrdup(new_cmd);
7912
Denys Vlasenkoe89a2412010-01-12 15:19:31 +01007913 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007914 get_signame(sig), sig, G.traps[sig]);
7915
7916 /* There is no signal for 0 (EXIT) */
7917 if (sig == 0)
7918 continue;
7919
7920 if (new_cmd) {
7921 sigaddset(&G.blocked_set, sig);
7922 } else {
7923 /* There was a trap handler, we are removing it
7924 * (if sig has non-DFL handling,
7925 * we don't need to do anything) */
7926 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7927 continue;
7928 sigdelset(&G.blocked_set, sig);
7929 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007930 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007931 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007932 return ret;
7933 }
7934
7935 if (!argv[1]) { /* no second arg */
7936 bb_error_msg("trap: invalid arguments");
7937 return EXIT_FAILURE;
7938 }
7939
7940 /* First arg is "-": reset all specified to default */
7941 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7942 /* Everything else: set arg as signal handler
7943 * (includes "" case, which ignores signal) */
7944 if (argv[0][0] == '-') {
7945 if (argv[0][1] == '\0') { /* "-" */
7946 /* new_cmd remains NULL: "reset these sigs" */
7947 goto reset_traps;
7948 }
7949 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7950 argv++;
7951 }
7952 /* else: "-something", no special meaning */
7953 }
7954 new_cmd = *argv;
7955 reset_traps:
7956 argv++;
7957 goto process_sig_list;
7958}
7959
Mike Frysinger93cadc22009-05-27 17:06:25 -04007960/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007961static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007962{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007963 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007964
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007965 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007966 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007967 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007968
7969 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007970 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007971 type = "an alias";*/
7972#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007973 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007974 type = "a function";
7975#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007976 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007977 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007978 else if ((path = find_in_path(*argv)) != NULL)
7979 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007980 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007981 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007982 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007983 continue;
7984 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007985
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007986 printf("%s is %s\n", *argv, type);
7987 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007988 }
7989
7990 return ret;
7991}
7992
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007993#if ENABLE_HUSH_JOB
7994/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007995static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007996{
7997 int i, jobnum;
7998 struct pipe *pi;
7999
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008000 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008001 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00008002
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008003 /* If they gave us no args, assume they want the last backgrounded task */
8004 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00008005 for (pi = G.job_list; pi; pi = pi->next) {
8006 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008007 goto found;
8008 }
8009 }
8010 bb_error_msg("%s: no current job", argv[0]);
8011 return EXIT_FAILURE;
8012 }
8013 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8014 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8015 return EXIT_FAILURE;
8016 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008017 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008018 if (pi->jobid == jobnum) {
8019 goto found;
8020 }
8021 }
8022 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8023 return EXIT_FAILURE;
8024 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00008025 /* TODO: bash prints a string representation
8026 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04008027 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008028 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00008029 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008030 }
8031
8032 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008033 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8034 for (i = 0; i < pi->num_cmds; i++) {
8035 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8036 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008037 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008038 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008039
8040 i = kill(- pi->pgrp, SIGCONT);
8041 if (i < 0) {
8042 if (errno == ESRCH) {
8043 delete_finished_bg_job(pi);
8044 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008045 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008046 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008047 }
8048
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008049 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008050 remove_bg_job(pi);
8051 return checkjobs_and_fg_shell(pi);
8052 }
8053 return EXIT_SUCCESS;
8054}
8055#endif
8056
8057#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008058static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008059{
8060 const struct built_in_command *x;
8061
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008062 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00008063 "Built-in commands:\n"
8064 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008065 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
Denys Vlasenko17323a62010-01-28 01:57:05 +01008066 if (x->b_descr)
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008067 printf("%-10s%s\n", x->b_cmd, x->b_descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008068 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008069 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008070 return EXIT_SUCCESS;
8071}
8072#endif
8073
8074#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008075static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008076{
8077 struct pipe *job;
8078 const char *status_string;
8079
Denis Vlasenko87a86552008-07-29 19:43:10 +00008080 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00008081 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008082 status_string = "Stopped";
8083 else
8084 status_string = "Running";
8085
8086 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8087 }
8088 return EXIT_SUCCESS;
8089}
8090#endif
8091
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008092#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008093static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008094{
8095 void *p;
8096 unsigned long l;
8097
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008098# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02008099 /* Optional. Reduces probability of false positives */
8100 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02008101# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008102 /* Crude attempt to find where "free memory" starts,
8103 * sans fragmentation. */
8104 p = malloc(240);
8105 l = (unsigned long)p;
8106 free(p);
8107 p = malloc(3400);
8108 if (l < (unsigned long)p) l = (unsigned long)p;
8109 free(p);
8110
8111 if (!G.memleak_value)
8112 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02008113
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00008114 l -= G.memleak_value;
8115 if ((long)l < 0)
8116 l = 0;
8117 l /= 1024;
8118 if (l > 127)
8119 l = 127;
8120
8121 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8122 return l;
8123}
8124#endif
8125
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008126static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008127{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02008128 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008129 return EXIT_SUCCESS;
8130}
8131
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008132static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008133{
Denys Vlasenko03dad222010-01-12 23:29:57 +01008134 const char *r;
8135 char *opt_n = NULL;
8136 char *opt_p = NULL;
8137 char *opt_t = NULL;
8138 char *opt_u = NULL;
8139 int read_flags;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008140
Denys Vlasenko03dad222010-01-12 23:29:57 +01008141 /* "!": do not abort on errors.
8142 * Option string must start with "sr" to match BUILTIN_READ_xxx
8143 */
8144 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8145 if (read_flags == (uint32_t)-1)
8146 return EXIT_FAILURE;
8147 argv += optind;
8148
8149 r = shell_builtin_read(set_local_var_from_halves,
8150 argv,
8151 get_local_var_value("IFS"), /* can be NULL */
8152 read_flags,
8153 opt_n,
8154 opt_p,
8155 opt_t,
8156 opt_u
8157 );
8158
8159 if ((uintptr_t)r > 1) {
8160 bb_error_msg("%s", r);
8161 r = (char*)(uintptr_t)1;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00008162 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008163
Denys Vlasenko03dad222010-01-12 23:29:57 +01008164 return (uintptr_t)r;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008165}
8166
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008167/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8168 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008169 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008170 * set [-abCefhmnuvx] [-o option] [argument...]
8171 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008172 * set -- [argument...]
8173 * set -o
8174 * set +o
8175 * Implementations shall support the options in both their hyphen and
8176 * plus-sign forms. These options can also be specified as options to sh.
8177 * Examples:
8178 * Write out all variables and their values: set
8179 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8180 * Turn on the -x and -v options: set -xv
8181 * Unset all positional parameters: set --
8182 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8183 * Set the positional parameters to the expansion of x, even if x expands
8184 * with a leading '-' or '+': set -- $x
8185 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008186 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008187 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008188static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008189{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008190 int n;
8191 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008192 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008193
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008194 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008195 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008196 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008197 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008198 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00008199 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008200
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008201 do {
8202 if (!strcmp(arg, "--")) {
8203 ++argv;
8204 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008205 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00008206 if (arg[0] != '+' && arg[0] != '-')
8207 break;
8208 for (n = 1; arg[n]; ++n)
8209 if (set_mode(arg[0], arg[n]))
8210 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008211 } while ((arg = *++argv) != NULL);
8212 /* Now argv[0] is 1st argument */
8213
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008214 if (arg == NULL)
8215 return EXIT_SUCCESS;
8216 set_argv:
8217
Denis Vlasenko424f79b2009-03-22 14:23:34 +00008218 /* NB: G.global_argv[0] ($0) is never freed/changed */
8219 g_argv = G.global_argv;
8220 if (G.global_args_malloced) {
8221 pp = g_argv;
8222 while (*++pp)
8223 free(*pp);
8224 g_argv[1] = NULL;
8225 } else {
8226 G.global_args_malloced = 1;
8227 pp = xzalloc(sizeof(pp[0]) * 2);
8228 pp[0] = g_argv[0]; /* retain $0 */
8229 g_argv = pp;
8230 }
8231 /* This realloc's G.global_argv */
8232 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8233
8234 n = 1;
8235 while (*++pp)
8236 n++;
8237 G.global_argc = n;
8238
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008239 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00008240
8241 /* Nothing known, so abort */
8242 error:
8243 bb_error_msg("set: %s: invalid option", arg);
8244 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008245}
8246
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008247static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008248{
8249 int n = 1;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008250 argv = skip_dash_dash(argv);
8251 if (argv[0]) {
8252 n = atoi(argv[0]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008253 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008254 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008255 if (G.global_args_malloced) {
8256 int m = 1;
8257 while (m <= n)
8258 free(G.global_argv[m++]);
8259 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008260 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00008261 memmove(&G.global_argv[1], &G.global_argv[n+1],
8262 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008263 return EXIT_SUCCESS;
8264 }
8265 return EXIT_FAILURE;
8266}
8267
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008268static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008269{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008270 char *arg_path, *filename;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008271 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008272 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008273#if ENABLE_HUSH_FUNCTIONS
8274 smallint sv_flg;
8275#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008276
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008277 argv = skip_dash_dash(argv);
8278 filename = argv[0];
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008279 if (!filename) {
8280 /* bash says: "bash: .: filename argument required" */
8281 return 2; /* bash compat */
8282 }
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008283 arg_path = NULL;
Denys Vlasenkoe66cf822010-05-18 09:12:53 +02008284 if (!strchr(filename, '/')) {
8285 arg_path = find_in_path(filename);
8286 if (arg_path)
8287 filename = arg_path;
8288 }
8289 input = fopen_or_warn(filename, "r");
8290 free(arg_path);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008291 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008292 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008293 return EXIT_FAILURE;
8294 }
8295 close_on_exec_on(fileno(input));
8296
Mike Frysinger885b6f22009-04-18 21:04:25 +00008297#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008298 sv_flg = G.flag_return_in_progress;
8299 /* "we are inside sourced file, ok to use return" */
8300 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008301#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008302 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008303
Denis Vlasenkob6e65562009-04-03 16:49:04 +00008304 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008305 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00008306
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008307 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00008308#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008309 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00008310#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008311
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00008312 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008313}
8314
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008315static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008316{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008317 int rc;
8318 mode_t mask;
8319
8320 mask = umask(0);
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008321 argv = skip_dash_dash(argv);
8322 if (argv[0]) {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008323 mode_t old_mask = mask;
8324
8325 mask ^= 0777;
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008326 rc = bb_parse_mode(argv[0], &mask);
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008327 mask ^= 0777;
8328 if (rc == 0) {
8329 mask = old_mask;
8330 /* bash messages:
8331 * bash: umask: 'q': invalid symbolic mode operator
8332 * bash: umask: 999: octal number out of range
8333 */
Denys Vlasenko44c86ce2010-05-20 04:22:55 +02008334 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008335 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008336 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008337 rc = 1;
8338 /* Mimic bash */
8339 printf("%04o\n", (unsigned) mask);
8340 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008341 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00008342 umask(mask);
8343
8344 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008345}
8346
Mike Frysingerd690f682009-03-30 06:50:54 +00008347/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008348static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008349{
Mike Frysingerd690f682009-03-30 06:50:54 +00008350 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00008351 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00008352
Denis Vlasenko28e67962009-04-26 23:22:40 +00008353 /* "!": do not abort on errors */
8354 /* "+": stop at 1st non-option */
8355 opts = getopt32(argv, "!+vf");
8356 if (opts == (unsigned)-1)
8357 return EXIT_FAILURE;
8358 if (opts == 3) {
8359 bb_error_msg("unset: -v and -f are exclusive");
8360 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00008361 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00008362 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00008363
8364 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008365 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00008366 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008367 if (unset_local_var(*argv)) {
8368 /* unset <nonexistent_var> doesn't fail.
8369 * Error is when one tries to unset RO var.
8370 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00008371 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008372 }
Mike Frysingerd690f682009-03-30 06:50:54 +00008373 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00008374#if ENABLE_HUSH_FUNCTIONS
8375 else {
8376 unset_func(*argv);
8377 }
8378#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00008379 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00008380 }
8381 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00008382}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008383
Mike Frysinger56bdea12009-03-28 20:01:58 +00008384/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008385static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00008386{
8387 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008388 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008389
Denys Vlasenkob131cce2010-05-20 03:39:43 +02008390 argv = skip_dash_dash(argv);
8391 if (argv[0] == NULL) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008392 /* Don't care about wait results */
8393 /* Note 1: must wait until there are no more children */
8394 /* Note 2: must be interruptible */
8395 /* Examples:
8396 * $ sleep 3 & sleep 6 & wait
8397 * [1] 30934 sleep 3
8398 * [2] 30935 sleep 6
8399 * [1] Done sleep 3
8400 * [2] Done sleep 6
8401 * $ sleep 3 & sleep 6 & wait
8402 * [1] 30936 sleep 3
8403 * [2] 30937 sleep 6
8404 * [1] Done sleep 3
8405 * ^C <-- after ~4 sec from keyboard
8406 * $
8407 */
8408 sigaddset(&G.blocked_set, SIGCHLD);
8409 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8410 while (1) {
8411 checkjobs(NULL);
8412 if (errno == ECHILD)
8413 break;
8414 /* Wait for SIGCHLD or any other signal of interest */
8415 /* sigtimedwait with infinite timeout: */
8416 sig = sigwaitinfo(&G.blocked_set, NULL);
8417 if (sig > 0) {
8418 sig = check_and_run_traps(sig);
8419 if (sig && sig != SIGCHLD) { /* see note 2 */
8420 ret = 128 + sig;
8421 break;
8422 }
8423 }
8424 }
8425 sigdelset(&G.blocked_set, SIGCHLD);
8426 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
8427 return ret;
8428 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00008429
Denis Vlasenko7566bae2009-03-31 17:24:49 +00008430 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00008431 while (*argv) {
8432 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00008433 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008434 /* mimic bash message */
8435 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008436 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00008437 }
8438 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00008439 if (WIFSIGNALED(status))
8440 ret = 128 + WTERMSIG(status);
8441 else if (WIFEXITED(status))
8442 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00008443 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00008444 ret = EXIT_FAILURE;
8445 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00008446 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00008447 ret = 127;
8448 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00008449 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00008450 }
8451
8452 return ret;
8453}
8454
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008455#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
8456static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
8457{
8458 if (argv[1]) {
8459 def = bb_strtou(argv[1], NULL, 10);
8460 if (errno || def < def_min || argv[2]) {
8461 bb_error_msg("%s: bad arguments", argv[0]);
8462 def = UINT_MAX;
8463 }
8464 }
8465 return def;
8466}
8467#endif
8468
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008469#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008470static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008471{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008472 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008473 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008474 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008475 return EXIT_SUCCESS; /* bash compat */
8476 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008477 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008478
8479 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8480 if (depth == UINT_MAX)
8481 G.flag_break_continue = BC_BREAK;
8482 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008483 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008484
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008485 return EXIT_SUCCESS;
8486}
8487
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008488static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008489{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008490 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8491 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008492}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008493#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008494
8495#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008496static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008497{
8498 int rc;
8499
8500 if (G.flag_return_in_progress != -1) {
8501 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8502 return EXIT_FAILURE; /* bash compat */
8503 }
8504
8505 G.flag_return_in_progress = 1;
8506
8507 /* bash:
8508 * out of range: wraps around at 256, does not error out
8509 * non-numeric param:
8510 * f() { false; return qwe; }; f; echo $?
8511 * bash: return: qwe: numeric argument required <== we do this
8512 * 255 <== we also do this
8513 */
8514 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8515 return rc;
8516}
8517#endif